code
stringlengths
6
250k
repo_name
stringlengths
5
70
path
stringlengths
3
177
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
6
250k
/* * This file is part of wl1271 * * Copyright (C) 2008-2010 Nokia Corporation * * Contact: Luciano Coelho <luciano.coelho@nokia.com> * * 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. * * This program 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 this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA * */ #include <linux/module.h> #include <linux/firmware.h> #include <linux/delay.h> #include <linux/spi/spi.h> #include <linux/crc32.h> #include <linux/etherdevice.h> #include <linux/vmalloc.h> #include <linux/platform_device.h> #include <linux/slab.h> #include <linux/wl12xx.h> #include <linux/sched.h> #include <linux/interrupt.h> #include "wl12xx.h" #include "debug.h" #include "wl12xx_80211.h" #include "reg.h" #include "io.h" #include "event.h" #include "tx.h" #include "rx.h" #include "ps.h" #include "init.h" #include "debugfs.h" #include "cmd.h" #include "boot.h" #include "testmode.h" #include "scan.h" #define WL1271_BOOT_RETRIES 3 static struct conf_drv_settings default_conf = { .sg = { .params = { [CONF_SG_ACL_BT_MASTER_MIN_BR] = 10, [CONF_SG_ACL_BT_MASTER_MAX_BR] = 180, [CONF_SG_ACL_BT_SLAVE_MIN_BR] = 10, [CONF_SG_ACL_BT_SLAVE_MAX_BR] = 180, [CONF_SG_ACL_BT_MASTER_MIN_EDR] = 10, [CONF_SG_ACL_BT_MASTER_MAX_EDR] = 80, [CONF_SG_ACL_BT_SLAVE_MIN_EDR] = 10, [CONF_SG_ACL_BT_SLAVE_MAX_EDR] = 80, [CONF_SG_ACL_WLAN_PS_MASTER_BR] = 8, [CONF_SG_ACL_WLAN_PS_SLAVE_BR] = 8, [CONF_SG_ACL_WLAN_PS_MASTER_EDR] = 20, [CONF_SG_ACL_WLAN_PS_SLAVE_EDR] = 20, [CONF_SG_ACL_WLAN_ACTIVE_MASTER_MIN_BR] = 20, [CONF_SG_ACL_WLAN_ACTIVE_MASTER_MAX_BR] = 35, [CONF_SG_ACL_WLAN_ACTIVE_SLAVE_MIN_BR] = 16, [CONF_SG_ACL_WLAN_ACTIVE_SLAVE_MAX_BR] = 35, [CONF_SG_ACL_WLAN_ACTIVE_MASTER_MIN_EDR] = 32, [CONF_SG_ACL_WLAN_ACTIVE_MASTER_MAX_EDR] = 50, [CONF_SG_ACL_WLAN_ACTIVE_SLAVE_MIN_EDR] = 28, [CONF_SG_ACL_WLAN_ACTIVE_SLAVE_MAX_EDR] = 50, [CONF_SG_ACL_ACTIVE_SCAN_WLAN_BR] = 10, [CONF_SG_ACL_ACTIVE_SCAN_WLAN_EDR] = 20, [CONF_SG_ACL_PASSIVE_SCAN_BT_BR] = 75, [CONF_SG_ACL_PASSIVE_SCAN_WLAN_BR] = 15, [CONF_SG_ACL_PASSIVE_SCAN_BT_EDR] = 27, [CONF_SG_ACL_PASSIVE_SCAN_WLAN_EDR] = 17, /* active scan params */ [CONF_SG_AUTO_SCAN_PROBE_REQ] = 170, [CONF_SG_ACTIVE_SCAN_DURATION_FACTOR_HV3] = 50, [CONF_SG_ACTIVE_SCAN_DURATION_FACTOR_A2DP] = 100, /* passive scan params */ [CONF_SG_PASSIVE_SCAN_DURATION_FACTOR_A2DP_BR] = 800, [CONF_SG_PASSIVE_SCAN_DURATION_FACTOR_A2DP_EDR] = 200, [CONF_SG_PASSIVE_SCAN_DURATION_FACTOR_HV3] = 200, /* passive scan in dual antenna params */ [CONF_SG_CONSECUTIVE_HV3_IN_PASSIVE_SCAN] = 0, [CONF_SG_BCN_HV3_COLLISION_THRESH_IN_PASSIVE_SCAN] = 0, [CONF_SG_TX_RX_PROTECTION_BWIDTH_IN_PASSIVE_SCAN] = 0, /* general params */ [CONF_SG_STA_FORCE_PS_IN_BT_SCO] = 1, [CONF_SG_ANTENNA_CONFIGURATION] = 0, [CONF_SG_BEACON_MISS_PERCENT] = 60, [CONF_SG_DHCP_TIME] = 5000, [CONF_SG_RXT] = 1200, [CONF_SG_TXT] = 1000, [CONF_SG_ADAPTIVE_RXT_TXT] = 1, [CONF_SG_GENERAL_USAGE_BIT_MAP] = 3, [CONF_SG_HV3_MAX_SERVED] = 6, [CONF_SG_PS_POLL_TIMEOUT] = 10, [CONF_SG_UPSD_TIMEOUT] = 10, [CONF_SG_CONSECUTIVE_CTS_THRESHOLD] = 2, [CONF_SG_STA_RX_WINDOW_AFTER_DTIM] = 5, [CONF_SG_STA_CONNECTION_PROTECTION_TIME] = 30, /* AP params */ [CONF_AP_BEACON_MISS_TX] = 3, [CONF_AP_RX_WINDOW_AFTER_BEACON] = 10, [CONF_AP_BEACON_WINDOW_INTERVAL] = 2, [CONF_AP_CONNECTION_PROTECTION_TIME] = 0, [CONF_AP_BT_ACL_VAL_BT_SERVE_TIME] = 25, [CONF_AP_BT_ACL_VAL_WL_SERVE_TIME] = 25, /* CTS Diluting params */ [CONF_SG_CTS_DILUTED_BAD_RX_PACKETS_TH] = 0, [CONF_SG_CTS_CHOP_IN_DUAL_ANT_SCO_MASTER] = 0, }, .state = CONF_SG_PROTECTIVE, }, .rx = { .rx_msdu_life_time = 512000, .packet_detection_threshold = 0, .ps_poll_timeout = 15, .upsd_timeout = 15, .rts_threshold = IEEE80211_MAX_RTS_THRESHOLD, .rx_cca_threshold = 0, .irq_blk_threshold = 0xFFFF, .irq_pkt_threshold = 0, .irq_timeout = 600, .queue_type = CONF_RX_QUEUE_TYPE_LOW_PRIORITY, }, .tx = { .tx_energy_detection = 0, .sta_rc_conf = { .enabled_rates = 0, .short_retry_limit = 10, .long_retry_limit = 10, .aflags = 0, }, .ac_conf_count = 4, .ac_conf = { [CONF_TX_AC_BE] = { .ac = CONF_TX_AC_BE, .cw_min = 15, .cw_max = 63, .aifsn = 3, .tx_op_limit = 0, }, [CONF_TX_AC_BK] = { .ac = CONF_TX_AC_BK, .cw_min = 15, .cw_max = 63, .aifsn = 7, .tx_op_limit = 0, }, [CONF_TX_AC_VI] = { .ac = CONF_TX_AC_VI, .cw_min = 15, .cw_max = 63, .aifsn = CONF_TX_AIFS_PIFS, .tx_op_limit = 3008, }, [CONF_TX_AC_VO] = { .ac = CONF_TX_AC_VO, .cw_min = 15, .cw_max = 63, .aifsn = CONF_TX_AIFS_PIFS, .tx_op_limit = 1504, }, }, .max_tx_retries = 100, .ap_aging_period = 300, .tid_conf_count = 4, .tid_conf = { [CONF_TX_AC_BE] = { .queue_id = CONF_TX_AC_BE, .channel_type = CONF_CHANNEL_TYPE_EDCF, .tsid = CONF_TX_AC_BE, .ps_scheme = CONF_PS_SCHEME_LEGACY, .ack_policy = CONF_ACK_POLICY_LEGACY, .apsd_conf = {0, 0}, }, [CONF_TX_AC_BK] = { .queue_id = CONF_TX_AC_BK, .channel_type = CONF_CHANNEL_TYPE_EDCF, .tsid = CONF_TX_AC_BK, .ps_scheme = CONF_PS_SCHEME_LEGACY, .ack_policy = CONF_ACK_POLICY_LEGACY, .apsd_conf = {0, 0}, }, [CONF_TX_AC_VI] = { .queue_id = CONF_TX_AC_VI, .channel_type = CONF_CHANNEL_TYPE_EDCF, .tsid = CONF_TX_AC_VI, .ps_scheme = CONF_PS_SCHEME_LEGACY, .ack_policy = CONF_ACK_POLICY_LEGACY, .apsd_conf = {0, 0}, }, [CONF_TX_AC_VO] = { .queue_id = CONF_TX_AC_VO, .channel_type = CONF_CHANNEL_TYPE_EDCF, .tsid = CONF_TX_AC_VO, .ps_scheme = CONF_PS_SCHEME_LEGACY, .ack_policy = CONF_ACK_POLICY_LEGACY, .apsd_conf = {0, 0}, }, }, .frag_threshold = IEEE80211_MAX_FRAG_THRESHOLD, .tx_compl_timeout = 700, .tx_compl_threshold = 4, .basic_rate = CONF_HW_BIT_RATE_1MBPS, .basic_rate_5 = CONF_HW_BIT_RATE_6MBPS, .tmpl_short_retry_limit = 10, .tmpl_long_retry_limit = 10, .tx_watchdog_timeout = 5000, }, .conn = { .wake_up_event = CONF_WAKE_UP_EVENT_DTIM, .listen_interval = 1, .suspend_wake_up_event = CONF_WAKE_UP_EVENT_N_DTIM, .suspend_listen_interval = 3, .bcn_filt_mode = CONF_BCN_FILT_MODE_ENABLED, .bcn_filt_ie_count = 2, .bcn_filt_ie = { [0] = { .ie = WLAN_EID_CHANNEL_SWITCH, .rule = CONF_BCN_RULE_PASS_ON_APPEARANCE, }, [1] = { .ie = WLAN_EID_HT_INFORMATION, .rule = CONF_BCN_RULE_PASS_ON_CHANGE, }, }, .synch_fail_thold = 10, .bss_lose_timeout = 100, .beacon_rx_timeout = 10000, .broadcast_timeout = 20000, .rx_broadcast_in_ps = 1, .ps_poll_threshold = 10, .bet_enable = CONF_BET_MODE_ENABLE, .bet_max_consecutive = 50, .psm_entry_retries = 8, .psm_exit_retries = 16, .psm_entry_nullfunc_retries = 3, .dynamic_ps_timeout = 200, .forced_ps = false, .keep_alive_interval = 55000, .max_listen_interval = 20, }, .itrim = { .enable = false, .timeout = 50000, }, .pm_config = { .host_clk_settling_time = 5000, .host_fast_wakeup_support = false }, .roam_trigger = { .trigger_pacing = 1, .avg_weight_rssi_beacon = 20, .avg_weight_rssi_data = 10, .avg_weight_snr_beacon = 20, .avg_weight_snr_data = 10, }, .scan = { .min_dwell_time_active = 7500, .max_dwell_time_active = 30000, .min_dwell_time_passive = 100000, .max_dwell_time_passive = 100000, .num_probe_reqs = 2, .split_scan_timeout = 50000, }, .sched_scan = { /* sched_scan requires dwell times in TU instead of TU/1000 */ .min_dwell_time_active = 30, .max_dwell_time_active = 60, .dwell_time_passive = 100, .dwell_time_dfs = 150, .num_probe_reqs = 2, .rssi_threshold = -90, .snr_threshold = 0, }, .rf = { .tx_per_channel_power_compensation_2 = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }, .tx_per_channel_power_compensation_5 = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }, }, .ht = { .rx_ba_win_size = 8, .tx_ba_win_size = 64, .inactivity_timeout = 10000, .tx_ba_tid_bitmap = CONF_TX_BA_ENABLED_TID_BITMAP, }, .mem_wl127x = { .num_stations = 1, .ssid_profiles = 1, .rx_block_num = 70, .tx_min_block_num = 40, .dynamic_memory = 1, .min_req_tx_blocks = 100, .min_req_rx_blocks = 22, .tx_min = 27, }, .mem_wl128x = { .num_stations = 1, .ssid_profiles = 1, .rx_block_num = 40, .tx_min_block_num = 40, .dynamic_memory = 1, .min_req_tx_blocks = 45, .min_req_rx_blocks = 22, .tx_min = 27, }, .fm_coex = { .enable = true, .swallow_period = 5, .n_divider_fref_set_1 = 0xff, /* default */ .n_divider_fref_set_2 = 12, .m_divider_fref_set_1 = 148, .m_divider_fref_set_2 = 0xffff, /* default */ .coex_pll_stabilization_time = 0xffffffff, /* default */ .ldo_stabilization_time = 0xffff, /* default */ .fm_disturbed_band_margin = 0xff, /* default */ .swallow_clk_diff = 0xff, /* default */ }, .rx_streaming = { .duration = 150, .queues = 0x1, .interval = 20, .always = 0, }, .fwlog = { .mode = WL12XX_FWLOG_ON_DEMAND, .mem_blocks = 2, .severity = 0, .timestamp = WL12XX_FWLOG_TIMESTAMP_DISABLED, .output = WL12XX_FWLOG_OUTPUT_HOST, .threshold = 0, }, .hci_io_ds = HCI_IO_DS_6MA, .rate = { .rate_retry_score = 32000, .per_add = 8192, .per_th1 = 2048, .per_th2 = 4096, .max_per = 8100, .inverse_curiosity_factor = 5, .tx_fail_low_th = 4, .tx_fail_high_th = 10, .per_alpha_shift = 4, .per_add_shift = 13, .per_beta1_shift = 10, .per_beta2_shift = 8, .rate_check_up = 2, .rate_check_down = 12, .rate_retry_policy = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }, }, .hangover = { .recover_time = 0, .hangover_period = 20, .dynamic_mode = 1, .early_termination_mode = 1, .max_period = 20, .min_period = 1, .increase_delta = 1, .decrease_delta = 2, .quiet_time = 4, .increase_time = 1, .window_size = 16, }, }; static char *fwlog_param; static bool bug_on_recovery; static void __wl1271_op_remove_interface(struct wl1271 *wl, struct ieee80211_vif *vif, bool reset_tx_queues); static void wl1271_op_stop(struct ieee80211_hw *hw); static void wl1271_free_ap_keys(struct wl1271 *wl, struct wl12xx_vif *wlvif); static int wl12xx_set_authorized(struct wl1271 *wl, struct wl12xx_vif *wlvif) { int ret; if (WARN_ON(wlvif->bss_type != BSS_TYPE_STA_BSS)) return -EINVAL; if (!test_bit(WLVIF_FLAG_STA_ASSOCIATED, &wlvif->flags)) return 0; if (test_and_set_bit(WLVIF_FLAG_STA_STATE_SENT, &wlvif->flags)) return 0; ret = wl12xx_cmd_set_peer_state(wl, wlvif->sta.hlid); if (ret < 0) return ret; wl12xx_croc(wl, wlvif->role_id); wl1271_info("Association completed."); return 0; } static int wl1271_reg_notify(struct wiphy *wiphy, struct regulatory_request *request) { struct ieee80211_supported_band *band; struct ieee80211_channel *ch; int i; band = wiphy->bands[IEEE80211_BAND_5GHZ]; for (i = 0; i < band->n_channels; i++) { ch = &band->channels[i]; if (ch->flags & IEEE80211_CHAN_DISABLED) continue; if (ch->flags & IEEE80211_CHAN_RADAR) ch->flags |= IEEE80211_CHAN_NO_IBSS | IEEE80211_CHAN_PASSIVE_SCAN; } return 0; } static int wl1271_set_rx_streaming(struct wl1271 *wl, struct wl12xx_vif *wlvif, bool enable) { int ret = 0; /* we should hold wl->mutex */ ret = wl1271_acx_ps_rx_streaming(wl, wlvif, enable); if (ret < 0) goto out; if (enable) set_bit(WLVIF_FLAG_RX_STREAMING_STARTED, &wlvif->flags); else clear_bit(WLVIF_FLAG_RX_STREAMING_STARTED, &wlvif->flags); out: return ret; } /* * this function is being called when the rx_streaming interval * has beed changed or rx_streaming should be disabled */ int wl1271_recalc_rx_streaming(struct wl1271 *wl, struct wl12xx_vif *wlvif) { int ret = 0; int period = wl->conf.rx_streaming.interval; /* don't reconfigure if rx_streaming is disabled */ if (!test_bit(WLVIF_FLAG_RX_STREAMING_STARTED, &wlvif->flags)) goto out; /* reconfigure/disable according to new streaming_period */ if (period && test_bit(WLVIF_FLAG_STA_ASSOCIATED, &wlvif->flags) && (wl->conf.rx_streaming.always || test_bit(WL1271_FLAG_SOFT_GEMINI, &wl->flags))) ret = wl1271_set_rx_streaming(wl, wlvif, true); else { ret = wl1271_set_rx_streaming(wl, wlvif, false); /* don't cancel_work_sync since we might deadlock */ del_timer_sync(&wlvif->rx_streaming_timer); } out: return ret; } static void wl1271_rx_streaming_enable_work(struct work_struct *work) { int ret; struct wl12xx_vif *wlvif = container_of(work, struct wl12xx_vif, rx_streaming_enable_work); struct wl1271 *wl = wlvif->wl; mutex_lock(&wl->mutex); if (test_bit(WLVIF_FLAG_RX_STREAMING_STARTED, &wlvif->flags) || !test_bit(WLVIF_FLAG_STA_ASSOCIATED, &wlvif->flags) || (!wl->conf.rx_streaming.always && !test_bit(WL1271_FLAG_SOFT_GEMINI, &wl->flags))) goto out; if (!wl->conf.rx_streaming.interval) goto out; ret = wl1271_ps_elp_wakeup(wl); if (ret < 0) goto out; ret = wl1271_set_rx_streaming(wl, wlvif, true); if (ret < 0) goto out_sleep; /* stop it after some time of inactivity */ mod_timer(&wlvif->rx_streaming_timer, jiffies + msecs_to_jiffies(wl->conf.rx_streaming.duration)); out_sleep: wl1271_ps_elp_sleep(wl); out: mutex_unlock(&wl->mutex); } static void wl1271_rx_streaming_disable_work(struct work_struct *work) { int ret; struct wl12xx_vif *wlvif = container_of(work, struct wl12xx_vif, rx_streaming_disable_work); struct wl1271 *wl = wlvif->wl; mutex_lock(&wl->mutex); if (!test_bit(WLVIF_FLAG_RX_STREAMING_STARTED, &wlvif->flags)) goto out; ret = wl1271_ps_elp_wakeup(wl); if (ret < 0) goto out; ret = wl1271_set_rx_streaming(wl, wlvif, false); if (ret) goto out_sleep; out_sleep: wl1271_ps_elp_sleep(wl); out: mutex_unlock(&wl->mutex); } static void wl1271_rx_streaming_timer(unsigned long data) { struct wl12xx_vif *wlvif = (struct wl12xx_vif *)data; struct wl1271 *wl = wlvif->wl; ieee80211_queue_work(wl->hw, &wlvif->rx_streaming_disable_work); } /* wl->mutex must be taken */ void wl12xx_rearm_tx_watchdog_locked(struct wl1271 *wl) { /* if the watchdog is not armed, don't do anything */ if (wl->tx_allocated_blocks == 0) return; cancel_delayed_work(&wl->tx_watchdog_work); ieee80211_queue_delayed_work(wl->hw, &wl->tx_watchdog_work, msecs_to_jiffies(wl->conf.tx.tx_watchdog_timeout)); } static void wl12xx_tx_watchdog_work(struct work_struct *work) { struct delayed_work *dwork; struct wl1271 *wl; dwork = container_of(work, struct delayed_work, work); wl = container_of(dwork, struct wl1271, tx_watchdog_work); mutex_lock(&wl->mutex); if (unlikely(wl->state == WL1271_STATE_OFF)) goto out; /* Tx went out in the meantime - everything is ok */ if (unlikely(wl->tx_allocated_blocks == 0)) goto out; /* * if a ROC is in progress, we might not have any Tx for a long * time (e.g. pending Tx on the non-ROC channels) */ if (find_first_bit(wl->roc_map, WL12XX_MAX_ROLES) < WL12XX_MAX_ROLES) { wl1271_debug(DEBUG_TX, "No Tx (in FW) for %d ms due to ROC", wl->conf.tx.tx_watchdog_timeout); wl12xx_rearm_tx_watchdog_locked(wl); goto out; } /* * if a scan is in progress, we might not have any Tx for a long * time */ if (wl->scan.state != WL1271_SCAN_STATE_IDLE) { wl1271_debug(DEBUG_TX, "No Tx (in FW) for %d ms due to scan", wl->conf.tx.tx_watchdog_timeout); wl12xx_rearm_tx_watchdog_locked(wl); goto out; } /* * AP might cache a frame for a long time for a sleeping station, * so rearm the timer if there's an AP interface with stations. If * Tx is genuinely stuck we will most hopefully discover it when all * stations are removed due to inactivity. */ if (wl->active_sta_count) { wl1271_debug(DEBUG_TX, "No Tx (in FW) for %d ms. AP has " " %d stations", wl->conf.tx.tx_watchdog_timeout, wl->active_sta_count); wl12xx_rearm_tx_watchdog_locked(wl); goto out; } wl1271_error("Tx stuck (in FW) for %d ms. Starting recovery", wl->conf.tx.tx_watchdog_timeout); wl12xx_queue_recovery_work(wl); out: mutex_unlock(&wl->mutex); } static void wl1271_conf_init(struct wl1271 *wl) { /* * This function applies the default configuration to the driver. This * function is invoked upon driver load (spi probe.) * * The configuration is stored in a run-time structure in order to * facilitate for run-time adjustment of any of the parameters. Making * changes to the configuration structure will apply the new values on * the next interface up (wl1271_op_start.) */ /* apply driver default configuration */ memcpy(&wl->conf, &default_conf, sizeof(default_conf)); /* Adjust settings according to optional module parameters */ if (fwlog_param) { if (!strcmp(fwlog_param, "continuous")) { wl->conf.fwlog.mode = WL12XX_FWLOG_CONTINUOUS; } else if (!strcmp(fwlog_param, "ondemand")) { wl->conf.fwlog.mode = WL12XX_FWLOG_ON_DEMAND; } else if (!strcmp(fwlog_param, "dbgpins")) { wl->conf.fwlog.mode = WL12XX_FWLOG_CONTINUOUS; wl->conf.fwlog.output = WL12XX_FWLOG_OUTPUT_DBG_PINS; } else if (!strcmp(fwlog_param, "disable")) { wl->conf.fwlog.mem_blocks = 0; wl->conf.fwlog.output = WL12XX_FWLOG_OUTPUT_NONE; } else { wl1271_error("Unknown fwlog parameter %s", fwlog_param); } } } static int wl1271_plt_init(struct wl1271 *wl) { int ret; if (wl->chip.id == CHIP_ID_1283_PG20) ret = wl128x_cmd_general_parms(wl); else ret = wl1271_cmd_general_parms(wl); if (ret < 0) return ret; if (wl->chip.id == CHIP_ID_1283_PG20) ret = wl128x_cmd_radio_parms(wl); else ret = wl1271_cmd_radio_parms(wl); if (ret < 0) return ret; if (wl->chip.id != CHIP_ID_1283_PG20) { ret = wl1271_cmd_ext_radio_parms(wl); if (ret < 0) return ret; } /* Chip-specific initializations */ ret = wl1271_chip_specific_init(wl); if (ret < 0) return ret; ret = wl1271_acx_init_mem_config(wl); if (ret < 0) return ret; ret = wl12xx_acx_mem_cfg(wl); if (ret < 0) goto out_free_memmap; /* Enable data path */ ret = wl1271_cmd_data_path(wl, 1); if (ret < 0) goto out_free_memmap; /* Configure for CAM power saving (ie. always active) */ ret = wl1271_acx_sleep_auth(wl, WL1271_PSM_CAM); if (ret < 0) goto out_free_memmap; /* configure PM */ ret = wl1271_acx_pm_config(wl); if (ret < 0) goto out_free_memmap; return 0; out_free_memmap: kfree(wl->target_mem_map); wl->target_mem_map = NULL; return ret; } static void wl12xx_irq_ps_regulate_link(struct wl1271 *wl, struct wl12xx_vif *wlvif, u8 hlid, u8 tx_pkts) { bool fw_ps, single_sta; fw_ps = test_bit(hlid, (unsigned long *)&wl->ap_fw_ps_map); single_sta = (wl->active_sta_count == 1); /* * Wake up from high level PS if the STA is asleep with too little * packets in FW or if the STA is awake. */ if (!fw_ps || tx_pkts < WL1271_PS_STA_MAX_PACKETS) wl12xx_ps_link_end(wl, wlvif, hlid); /* * Start high-level PS if the STA is asleep with enough blocks in FW. * Make an exception if this is the only connected station. In this * case FW-memory congestion is not a problem. */ else if (!single_sta && fw_ps && tx_pkts >= WL1271_PS_STA_MAX_PACKETS) wl12xx_ps_link_start(wl, wlvif, hlid, true); } static void wl12xx_irq_update_links_status(struct wl1271 *wl, struct wl12xx_vif *wlvif, struct wl12xx_fw_status *status) { struct wl1271_link *lnk; u32 cur_fw_ps_map; u8 hlid, cnt; /* TODO: also use link_fast_bitmap here */ cur_fw_ps_map = le32_to_cpu(status->link_ps_bitmap); if (wl->ap_fw_ps_map != cur_fw_ps_map) { wl1271_debug(DEBUG_PSM, "link ps prev 0x%x cur 0x%x changed 0x%x", wl->ap_fw_ps_map, cur_fw_ps_map, wl->ap_fw_ps_map ^ cur_fw_ps_map); wl->ap_fw_ps_map = cur_fw_ps_map; } for_each_set_bit(hlid, wlvif->ap.sta_hlid_map, WL12XX_MAX_LINKS) { lnk = &wl->links[hlid]; cnt = status->tx_lnk_free_pkts[hlid] - lnk->prev_freed_pkts; lnk->prev_freed_pkts = status->tx_lnk_free_pkts[hlid]; lnk->allocated_pkts -= cnt; wl12xx_irq_ps_regulate_link(wl, wlvif, hlid, lnk->allocated_pkts); } } static void wl12xx_fw_status(struct wl1271 *wl, struct wl12xx_fw_status *status) { struct wl12xx_vif *wlvif; struct timespec ts; u32 old_tx_blk_count = wl->tx_blocks_available; int avail, freed_blocks; int i; wl1271_raw_read(wl, FW_STATUS_ADDR, status, sizeof(*status), false); wl1271_debug(DEBUG_IRQ, "intr: 0x%x (fw_rx_counter = %d, " "drv_rx_counter = %d, tx_results_counter = %d)", status->intr, status->fw_rx_counter, status->drv_rx_counter, status->tx_results_counter); for (i = 0; i < NUM_TX_QUEUES; i++) { /* prevent wrap-around in freed-packets counter */ wl->tx_allocated_pkts[i] -= (status->tx_released_pkts[i] - wl->tx_pkts_freed[i]) & 0xff; wl->tx_pkts_freed[i] = status->tx_released_pkts[i]; } /* prevent wrap-around in total blocks counter */ if (likely(wl->tx_blocks_freed <= le32_to_cpu(status->total_released_blks))) freed_blocks = le32_to_cpu(status->total_released_blks) - wl->tx_blocks_freed; else freed_blocks = 0x100000000LL - wl->tx_blocks_freed + le32_to_cpu(status->total_released_blks); wl->tx_blocks_freed = le32_to_cpu(status->total_released_blks); wl->tx_allocated_blocks -= freed_blocks; /* * If the FW freed some blocks: * If we still have allocated blocks - re-arm the timer, Tx is * not stuck. Otherwise, cancel the timer (no Tx currently). */ if (freed_blocks) { if (wl->tx_allocated_blocks) wl12xx_rearm_tx_watchdog_locked(wl); else cancel_delayed_work(&wl->tx_watchdog_work); } avail = le32_to_cpu(status->tx_total) - wl->tx_allocated_blocks; /* * The FW might change the total number of TX memblocks before * we get a notification about blocks being released. Thus, the * available blocks calculation might yield a temporary result * which is lower than the actual available blocks. Keeping in * mind that only blocks that were allocated can be moved from * TX to RX, tx_blocks_available should never decrease here. */ wl->tx_blocks_available = max((int)wl->tx_blocks_available, avail); /* if more blocks are available now, tx work can be scheduled */ if (wl->tx_blocks_available > old_tx_blk_count) clear_bit(WL1271_FLAG_FW_TX_BUSY, &wl->flags); /* for AP update num of allocated TX blocks per link and ps status */ wl12xx_for_each_wlvif_ap(wl, wlvif) { wl12xx_irq_update_links_status(wl, wlvif, status); } /* update the host-chipset time offset */ getnstimeofday(&ts); wl->time_offset = (timespec_to_ns(&ts) >> 10) - (s64)le32_to_cpu(status->fw_localtime); } static void wl1271_flush_deferred_work(struct wl1271 *wl) { struct sk_buff *skb; /* Pass all received frames to the network stack */ while ((skb = skb_dequeue(&wl->deferred_rx_queue))) ieee80211_rx_ni(wl->hw, skb); /* Return sent skbs to the network stack */ while ((skb = skb_dequeue(&wl->deferred_tx_queue))) ieee80211_tx_status_ni(wl->hw, skb); } static void wl1271_netstack_work(struct work_struct *work) { struct wl1271 *wl = container_of(work, struct wl1271, netstack_work); do { wl1271_flush_deferred_work(wl); } while (skb_queue_len(&wl->deferred_rx_queue)); } #define WL1271_IRQ_MAX_LOOPS 256 static irqreturn_t wl1271_irq(int irq, void *cookie) { int ret; u32 intr; int loopcount = WL1271_IRQ_MAX_LOOPS; struct wl1271 *wl = (struct wl1271 *)cookie; bool done = false; unsigned int defer_count; unsigned long flags; /* TX might be handled here, avoid redundant work */ set_bit(WL1271_FLAG_TX_PENDING, &wl->flags); cancel_work_sync(&wl->tx_work); /* * In case edge triggered interrupt must be used, we cannot iterate * more than once without introducing race conditions with the hardirq. */ if (wl->platform_quirks & WL12XX_PLATFORM_QUIRK_EDGE_IRQ) loopcount = 1; mutex_lock(&wl->mutex); wl1271_debug(DEBUG_IRQ, "IRQ work"); if (unlikely(wl->state == WL1271_STATE_OFF)) goto out; ret = wl1271_ps_elp_wakeup(wl); if (ret < 0) goto out; while (!done && loopcount--) { /* * In order to avoid a race with the hardirq, clear the flag * before acknowledging the chip. Since the mutex is held, * wl1271_ps_elp_wakeup cannot be called concurrently. */ clear_bit(WL1271_FLAG_IRQ_RUNNING, &wl->flags); smp_mb__after_clear_bit(); wl12xx_fw_status(wl, wl->fw_status); intr = le32_to_cpu(wl->fw_status->intr); intr &= WL1271_INTR_MASK; if (!intr) { done = true; continue; } if (unlikely(intr & WL1271_ACX_INTR_WATCHDOG)) { wl1271_error("watchdog interrupt received! " "starting recovery."); wl12xx_queue_recovery_work(wl); /* restarting the chip. ignore any other interrupt. */ goto out; } if (likely(intr & WL1271_ACX_INTR_DATA)) { wl1271_debug(DEBUG_IRQ, "WL1271_ACX_INTR_DATA"); wl12xx_rx(wl, wl->fw_status); /* Check if any tx blocks were freed */ spin_lock_irqsave(&wl->wl_lock, flags); if (!test_bit(WL1271_FLAG_FW_TX_BUSY, &wl->flags) && wl1271_tx_total_queue_count(wl) > 0) { spin_unlock_irqrestore(&wl->wl_lock, flags); /* * In order to avoid starvation of the TX path, * call the work function directly. */ wl1271_tx_work_locked(wl); } else { spin_unlock_irqrestore(&wl->wl_lock, flags); } /* check for tx results */ if (wl->fw_status->tx_results_counter != (wl->tx_results_count & 0xff)) wl1271_tx_complete(wl); /* Make sure the deferred queues don't get too long */ defer_count = skb_queue_len(&wl->deferred_tx_queue) + skb_queue_len(&wl->deferred_rx_queue); if (defer_count > WL1271_DEFERRED_QUEUE_LIMIT) wl1271_flush_deferred_work(wl); } if (intr & WL1271_ACX_INTR_EVENT_A) { wl1271_debug(DEBUG_IRQ, "WL1271_ACX_INTR_EVENT_A"); wl1271_event_handle(wl, 0); } if (intr & WL1271_ACX_INTR_EVENT_B) { wl1271_debug(DEBUG_IRQ, "WL1271_ACX_INTR_EVENT_B"); wl1271_event_handle(wl, 1); } if (intr & WL1271_ACX_INTR_INIT_COMPLETE) wl1271_debug(DEBUG_IRQ, "WL1271_ACX_INTR_INIT_COMPLETE"); if (intr & WL1271_ACX_INTR_HW_AVAILABLE) wl1271_debug(DEBUG_IRQ, "WL1271_ACX_INTR_HW_AVAILABLE"); } wl1271_ps_elp_sleep(wl); out: spin_lock_irqsave(&wl->wl_lock, flags); /* In case TX was not handled here, queue TX work */ clear_bit(WL1271_FLAG_TX_PENDING, &wl->flags); if (!test_bit(WL1271_FLAG_FW_TX_BUSY, &wl->flags) && wl1271_tx_total_queue_count(wl) > 0) ieee80211_queue_work(wl->hw, &wl->tx_work); spin_unlock_irqrestore(&wl->wl_lock, flags); mutex_unlock(&wl->mutex); return IRQ_HANDLED; } struct vif_counter_data { u8 counter; struct ieee80211_vif *cur_vif; bool cur_vif_running; }; static void wl12xx_vif_count_iter(void *data, u8 *mac, struct ieee80211_vif *vif) { struct vif_counter_data *counter = data; counter->counter++; if (counter->cur_vif == vif) counter->cur_vif_running = true; } /* caller must not hold wl->mutex, as it might deadlock */ static void wl12xx_get_vif_count(struct ieee80211_hw *hw, struct ieee80211_vif *cur_vif, struct vif_counter_data *data) { memset(data, 0, sizeof(*data)); data->cur_vif = cur_vif; ieee80211_iterate_active_interfaces(hw, wl12xx_vif_count_iter, data); } static int wl12xx_fetch_firmware(struct wl1271 *wl, bool plt) { const struct firmware *fw; const char *fw_name; enum wl12xx_fw_type fw_type; int ret; if (plt) { fw_type = WL12XX_FW_TYPE_PLT; if (wl->chip.id == CHIP_ID_1283_PG20) fw_name = WL128X_PLT_FW_NAME; else fw_name = WL127X_PLT_FW_NAME; } else { /* * we can't call wl12xx_get_vif_count() here because * wl->mutex is taken, so use the cached last_vif_count value */ if (wl->last_vif_count > 1) { fw_type = WL12XX_FW_TYPE_MULTI; if (wl->chip.id == CHIP_ID_1283_PG20) fw_name = WL128X_FW_NAME_MULTI; else fw_name = WL127X_FW_NAME_MULTI; } else { fw_type = WL12XX_FW_TYPE_NORMAL; if (wl->chip.id == CHIP_ID_1283_PG20) fw_name = WL128X_FW_NAME_SINGLE; else fw_name = WL127X_FW_NAME_SINGLE; } } if (wl->fw_type == fw_type) return 0; wl1271_debug(DEBUG_BOOT, "booting firmware %s", fw_name); ret = request_firmware(&fw, fw_name, wl->dev); if (ret < 0) { wl1271_error("could not get firmware %s: %d", fw_name, ret); return ret; } if (fw->size % 4) { wl1271_error("firmware size is not multiple of 32 bits: %zu", fw->size); ret = -EILSEQ; goto out; } vfree(wl->fw); wl->fw_type = WL12XX_FW_TYPE_NONE; wl->fw_len = fw->size; wl->fw = vmalloc(wl->fw_len); if (!wl->fw) { wl1271_error("could not allocate memory for the firmware"); ret = -ENOMEM; goto out; } memcpy(wl->fw, fw->data, wl->fw_len); ret = 0; wl->fw_type = fw_type; out: release_firmware(fw); return ret; } static int wl1271_fetch_nvs(struct wl1271 *wl) { const struct firmware *fw; int ret; ret = request_firmware(&fw, WL12XX_NVS_NAME, wl->dev); if (ret < 0) { wl1271_error("could not get nvs file %s: %d", WL12XX_NVS_NAME, ret); return ret; } wl->nvs = kmemdup(fw->data, fw->size, GFP_KERNEL); if (!wl->nvs) { wl1271_error("could not allocate memory for the nvs file"); ret = -ENOMEM; goto out; } wl->nvs_len = fw->size; out: release_firmware(fw); return ret; } void wl12xx_queue_recovery_work(struct wl1271 *wl) { if (!test_bit(WL1271_FLAG_RECOVERY_IN_PROGRESS, &wl->flags)) ieee80211_queue_work(wl->hw, &wl->recovery_work); } size_t wl12xx_copy_fwlog(struct wl1271 *wl, u8 *memblock, size_t maxlen) { size_t len = 0; /* The FW log is a length-value list, find where the log end */ while (len < maxlen) { if (memblock[len] == 0) break; if (len + memblock[len] + 1 > maxlen) break; len += memblock[len] + 1; } /* Make sure we have enough room */ len = min(len, (size_t)(PAGE_SIZE - wl->fwlog_size)); /* Fill the FW log file, consumed by the sysfs fwlog entry */ memcpy(wl->fwlog + wl->fwlog_size, memblock, len); wl->fwlog_size += len; return len; } static void wl12xx_read_fwlog_panic(struct wl1271 *wl) { u32 addr; u32 first_addr; u8 *block; if ((wl->quirks & WL12XX_QUIRK_FWLOG_NOT_IMPLEMENTED) || (wl->conf.fwlog.mode != WL12XX_FWLOG_ON_DEMAND) || (wl->conf.fwlog.mem_blocks == 0)) return; wl1271_info("Reading FW panic log"); block = kmalloc(WL12XX_HW_BLOCK_SIZE, GFP_KERNEL); if (!block) return; /* * Make sure the chip is awake and the logger isn't active. * This might fail if the firmware hanged. */ if (!wl1271_ps_elp_wakeup(wl)) wl12xx_cmd_stop_fwlog(wl); /* Read the first memory block address */ wl12xx_fw_status(wl, wl->fw_status); first_addr = le32_to_cpu(wl->fw_status->log_start_addr); if (!first_addr) goto out; /* Traverse the memory blocks linked list */ addr = first_addr; do { memset(block, 0, WL12XX_HW_BLOCK_SIZE); wl1271_read_hwaddr(wl, addr, block, WL12XX_HW_BLOCK_SIZE, false); /* * Memory blocks are linked to one another. The first 4 bytes * of each memory block hold the hardware address of the next * one. The last memory block points to the first one. */ addr = le32_to_cpup((__le32 *)block); if (!wl12xx_copy_fwlog(wl, block + sizeof(addr), WL12XX_HW_BLOCK_SIZE - sizeof(addr))) break; } while (addr && (addr != first_addr)); wake_up_interruptible(&wl->fwlog_waitq); out: kfree(block); } static void wl1271_recovery_work(struct work_struct *work) { struct wl1271 *wl = container_of(work, struct wl1271, recovery_work); struct wl12xx_vif *wlvif; struct ieee80211_vif *vif; mutex_lock(&wl->mutex); if (wl->state != WL1271_STATE_ON || wl->plt) goto out_unlock; /* Avoid a recursive recovery */ set_bit(WL1271_FLAG_RECOVERY_IN_PROGRESS, &wl->flags); wl12xx_read_fwlog_panic(wl); wl1271_info("Hardware recovery in progress. FW ver: %s pc: 0x%x", wl->chip.fw_ver_str, wl1271_read32(wl, SCR_PAD4)); BUG_ON(bug_on_recovery && !test_bit(WL1271_FLAG_INTENDED_FW_RECOVERY, &wl->flags)); /* * Advance security sequence number to overcome potential progress * in the firmware during recovery. This doens't hurt if the network is * not encrypted. */ wl12xx_for_each_wlvif(wl, wlvif) { if (test_bit(WLVIF_FLAG_STA_ASSOCIATED, &wlvif->flags) || test_bit(WLVIF_FLAG_AP_STARTED, &wlvif->flags)) wlvif->tx_security_seq += WL1271_TX_SQN_POST_RECOVERY_PADDING; } /* Prevent spurious TX during FW restart */ ieee80211_stop_queues(wl->hw); if (wl->sched_scanning) { ieee80211_sched_scan_stopped(wl->hw); wl->sched_scanning = false; } /* reboot the chipset */ while (!list_empty(&wl->wlvif_list)) { wlvif = list_first_entry(&wl->wlvif_list, struct wl12xx_vif, list); vif = wl12xx_wlvif_to_vif(wlvif); __wl1271_op_remove_interface(wl, vif, false); } mutex_unlock(&wl->mutex); wl1271_op_stop(wl->hw); clear_bit(WL1271_FLAG_RECOVERY_IN_PROGRESS, &wl->flags); ieee80211_restart_hw(wl->hw); /* * Its safe to enable TX now - the queues are stopped after a request * to restart the HW. */ ieee80211_wake_queues(wl->hw); return; out_unlock: mutex_unlock(&wl->mutex); } static void wl1271_fw_wakeup(struct wl1271 *wl) { u32 elp_reg; elp_reg = ELPCTRL_WAKE_UP; wl1271_raw_write32(wl, HW_ACCESS_ELP_CTRL_REG_ADDR, elp_reg); } static int wl1271_setup(struct wl1271 *wl) { wl->fw_status = kmalloc(sizeof(*wl->fw_status), GFP_KERNEL); if (!wl->fw_status) return -ENOMEM; wl->tx_res_if = kmalloc(sizeof(*wl->tx_res_if), GFP_KERNEL); if (!wl->tx_res_if) { kfree(wl->fw_status); return -ENOMEM; } return 0; } static int wl12xx_set_power_on(struct wl1271 *wl) { int ret; msleep(WL1271_PRE_POWER_ON_SLEEP); ret = wl1271_power_on(wl); if (ret < 0) goto out; msleep(WL1271_POWER_ON_SLEEP); wl1271_io_reset(wl); wl1271_io_init(wl); wl1271_set_partition(wl, &wl12xx_part_table[PART_DOWN]); /* ELP module wake up */ wl1271_fw_wakeup(wl); out: return ret; } static int wl12xx_chip_wakeup(struct wl1271 *wl, bool plt) { int ret = 0; ret = wl12xx_set_power_on(wl); if (ret < 0) goto out; /* * For wl127x based devices we could use the default block * size (512 bytes), but due to a bug in the sdio driver, we * need to set it explicitly after the chip is powered on. To * simplify the code and since the performance impact is * negligible, we use the same block size for all different * chip types. */ if (!wl1271_set_block_size(wl)) wl->quirks |= WL12XX_QUIRK_NO_BLOCKSIZE_ALIGNMENT; switch (wl->chip.id) { case CHIP_ID_1271_PG10: wl1271_warning("chip id 0x%x (1271 PG10) support is obsolete", wl->chip.id); ret = wl1271_setup(wl); if (ret < 0) goto out; wl->quirks |= WL12XX_QUIRK_NO_BLOCKSIZE_ALIGNMENT; break; case CHIP_ID_1271_PG20: wl1271_debug(DEBUG_BOOT, "chip id 0x%x (1271 PG20)", wl->chip.id); ret = wl1271_setup(wl); if (ret < 0) goto out; wl->quirks |= WL12XX_QUIRK_NO_BLOCKSIZE_ALIGNMENT; break; case CHIP_ID_1283_PG20: wl1271_debug(DEBUG_BOOT, "chip id 0x%x (1283 PG20)", wl->chip.id); ret = wl1271_setup(wl); if (ret < 0) goto out; break; case CHIP_ID_1283_PG10: default: wl1271_warning("unsupported chip id: 0x%x", wl->chip.id); ret = -ENODEV; goto out; } ret = wl12xx_fetch_firmware(wl, plt); if (ret < 0) goto out; /* No NVS from netlink, try to get it from the filesystem */ if (wl->nvs == NULL) { ret = wl1271_fetch_nvs(wl); if (ret < 0) goto out; } out: return ret; } int wl1271_plt_start(struct wl1271 *wl) { int retries = WL1271_BOOT_RETRIES; struct wiphy *wiphy = wl->hw->wiphy; int ret; mutex_lock(&wl->mutex); wl1271_notice("power up"); if (wl->state != WL1271_STATE_OFF) { wl1271_error("cannot go into PLT state because not " "in off state: %d", wl->state); ret = -EBUSY; goto out; } while (retries) { retries--; ret = wl12xx_chip_wakeup(wl, true); if (ret < 0) goto power_off; ret = wl1271_boot(wl); if (ret < 0) goto power_off; ret = wl1271_plt_init(wl); if (ret < 0) goto irq_disable; wl->plt = true; wl->state = WL1271_STATE_ON; wl1271_notice("firmware booted in PLT mode (%s)", wl->chip.fw_ver_str); /* update hw/fw version info in wiphy struct */ wiphy->hw_version = wl->chip.id; strncpy(wiphy->fw_version, wl->chip.fw_ver_str, sizeof(wiphy->fw_version)); goto out; irq_disable: mutex_unlock(&wl->mutex); /* Unlocking the mutex in the middle of handling is inherently unsafe. In this case we deem it safe to do, because we need to let any possibly pending IRQ out of the system (and while we are WL1271_STATE_OFF the IRQ work function will not do anything.) Also, any other possible concurrent operations will fail due to the current state, hence the wl1271 struct should be safe. */ wl1271_disable_interrupts(wl); wl1271_flush_deferred_work(wl); cancel_work_sync(&wl->netstack_work); mutex_lock(&wl->mutex); power_off: wl1271_power_off(wl); } wl1271_error("firmware boot in PLT mode failed despite %d retries", WL1271_BOOT_RETRIES); out: mutex_unlock(&wl->mutex); return ret; } int wl1271_plt_stop(struct wl1271 *wl) { int ret = 0; wl1271_notice("power down"); /* * Interrupts must be disabled before setting the state to OFF. * Otherwise, the interrupt handler might be called and exit without * reading the interrupt status. */ wl1271_disable_interrupts(wl); mutex_lock(&wl->mutex); if (!wl->plt) { mutex_unlock(&wl->mutex); /* * This will not necessarily enable interrupts as interrupts * may have been disabled when op_stop was called. It will, * however, balance the above call to disable_interrupts(). */ wl1271_enable_interrupts(wl); wl1271_error("cannot power down because not in PLT " "state: %d", wl->state); ret = -EBUSY; goto out; } mutex_unlock(&wl->mutex); wl1271_flush_deferred_work(wl); cancel_work_sync(&wl->netstack_work); cancel_work_sync(&wl->recovery_work); cancel_delayed_work_sync(&wl->elp_work); cancel_delayed_work_sync(&wl->tx_watchdog_work); mutex_lock(&wl->mutex); wl1271_power_off(wl); wl->flags = 0; wl->state = WL1271_STATE_OFF; wl->plt = false; wl->rx_counter = 0; mutex_unlock(&wl->mutex); out: return ret; } static void wl1271_op_tx(struct ieee80211_hw *hw, struct sk_buff *skb) { struct wl1271 *wl = hw->priv; struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb); struct ieee80211_vif *vif = info->control.vif; struct wl12xx_vif *wlvif = NULL; unsigned long flags; int q, mapping; u8 hlid; if (vif) wlvif = wl12xx_vif_to_data(vif); mapping = skb_get_queue_mapping(skb); q = wl1271_tx_get_queue(mapping); hlid = wl12xx_tx_get_hlid(wl, wlvif, skb); spin_lock_irqsave(&wl->wl_lock, flags); /* queue the packet */ if (hlid == WL12XX_INVALID_LINK_ID || (wlvif && !test_bit(hlid, wlvif->links_map))) { wl1271_debug(DEBUG_TX, "DROP skb hlid %d q %d", hlid, q); ieee80211_free_txskb(hw, skb); goto out; } wl1271_debug(DEBUG_TX, "queue skb hlid %d q %d len %d", hlid, q, skb->len); skb_queue_tail(&wl->links[hlid].tx_queue[q], skb); wl->tx_queue_count[q]++; /* * The workqueue is slow to process the tx_queue and we need stop * the queue here, otherwise the queue will get too long. */ if (wl->tx_queue_count[q] >= WL1271_TX_QUEUE_HIGH_WATERMARK) { wl1271_debug(DEBUG_TX, "op_tx: stopping queues for q %d", q); ieee80211_stop_queue(wl->hw, mapping); set_bit(q, &wl->stopped_queues_map); } /* * The chip specific setup must run before the first TX packet - * before that, the tx_work will not be initialized! */ if (!test_bit(WL1271_FLAG_FW_TX_BUSY, &wl->flags) && !test_bit(WL1271_FLAG_TX_PENDING, &wl->flags)) ieee80211_queue_work(wl->hw, &wl->tx_work); out: spin_unlock_irqrestore(&wl->wl_lock, flags); } int wl1271_tx_dummy_packet(struct wl1271 *wl) { unsigned long flags; int q; /* no need to queue a new dummy packet if one is already pending */ if (test_bit(WL1271_FLAG_DUMMY_PACKET_PENDING, &wl->flags)) return 0; q = wl1271_tx_get_queue(skb_get_queue_mapping(wl->dummy_packet)); spin_lock_irqsave(&wl->wl_lock, flags); set_bit(WL1271_FLAG_DUMMY_PACKET_PENDING, &wl->flags); wl->tx_queue_count[q]++; spin_unlock_irqrestore(&wl->wl_lock, flags); /* The FW is low on RX memory blocks, so send the dummy packet asap */ if (!test_bit(WL1271_FLAG_FW_TX_BUSY, &wl->flags)) wl1271_tx_work_locked(wl); /* * If the FW TX is busy, TX work will be scheduled by the threaded * interrupt handler function */ return 0; } /* * The size of the dummy packet should be at least 1400 bytes. However, in * order to minimize the number of bus transactions, aligning it to 512 bytes * boundaries could be beneficial, performance wise */ #define TOTAL_TX_DUMMY_PACKET_SIZE (ALIGN(1400, 512)) static struct sk_buff *wl12xx_alloc_dummy_packet(struct wl1271 *wl) { struct sk_buff *skb; struct ieee80211_hdr_3addr *hdr; unsigned int dummy_packet_size; dummy_packet_size = TOTAL_TX_DUMMY_PACKET_SIZE - sizeof(struct wl1271_tx_hw_descr) - sizeof(*hdr); skb = dev_alloc_skb(TOTAL_TX_DUMMY_PACKET_SIZE); if (!skb) { wl1271_warning("Failed to allocate a dummy packet skb"); return NULL; } skb_reserve(skb, sizeof(struct wl1271_tx_hw_descr)); hdr = (struct ieee80211_hdr_3addr *) skb_put(skb, sizeof(*hdr)); memset(hdr, 0, sizeof(*hdr)); hdr->frame_control = cpu_to_le16(IEEE80211_FTYPE_DATA | IEEE80211_STYPE_NULLFUNC | IEEE80211_FCTL_TODS); memset(skb_put(skb, dummy_packet_size), 0, dummy_packet_size); /* Dummy packets require the TID to be management */ skb->priority = WL1271_TID_MGMT; /* Initialize all fields that might be used */ skb_set_queue_mapping(skb, 0); memset(IEEE80211_SKB_CB(skb), 0, sizeof(struct ieee80211_tx_info)); return skb; } #ifdef CONFIG_PM static int wl1271_configure_suspend_sta(struct wl1271 *wl, struct wl12xx_vif *wlvif) { int ret = 0; mutex_lock(&wl->mutex); if (!test_bit(WLVIF_FLAG_STA_ASSOCIATED, &wlvif->flags)) goto out_unlock; ret = wl1271_ps_elp_wakeup(wl); if (ret < 0) goto out_unlock; ret = wl1271_acx_wake_up_conditions(wl, wlvif, wl->conf.conn.suspend_wake_up_event, wl->conf.conn.suspend_listen_interval); if (ret < 0) wl1271_error("suspend: set wake up conditions failed: %d", ret); wl1271_ps_elp_sleep(wl); out_unlock: mutex_unlock(&wl->mutex); return ret; } static int wl1271_configure_suspend_ap(struct wl1271 *wl, struct wl12xx_vif *wlvif) { int ret = 0; mutex_lock(&wl->mutex); if (!test_bit(WLVIF_FLAG_AP_STARTED, &wlvif->flags)) goto out_unlock; ret = wl1271_ps_elp_wakeup(wl); if (ret < 0) goto out_unlock; ret = wl1271_acx_beacon_filter_opt(wl, wlvif, true); wl1271_ps_elp_sleep(wl); out_unlock: mutex_unlock(&wl->mutex); return ret; } static int wl1271_configure_suspend(struct wl1271 *wl, struct wl12xx_vif *wlvif) { if (wlvif->bss_type == BSS_TYPE_STA_BSS) return wl1271_configure_suspend_sta(wl, wlvif); if (wlvif->bss_type == BSS_TYPE_AP_BSS) return wl1271_configure_suspend_ap(wl, wlvif); return 0; } static void wl1271_configure_resume(struct wl1271 *wl, struct wl12xx_vif *wlvif) { int ret = 0; bool is_ap = wlvif->bss_type == BSS_TYPE_AP_BSS; bool is_sta = wlvif->bss_type == BSS_TYPE_STA_BSS; if ((!is_ap) && (!is_sta)) return; mutex_lock(&wl->mutex); ret = wl1271_ps_elp_wakeup(wl); if (ret < 0) goto out; if (is_sta) { ret = wl1271_acx_wake_up_conditions(wl, wlvif, wl->conf.conn.wake_up_event, wl->conf.conn.listen_interval); if (ret < 0) wl1271_error("resume: wake up conditions failed: %d", ret); } else if (is_ap) { ret = wl1271_acx_beacon_filter_opt(wl, wlvif, false); } wl1271_ps_elp_sleep(wl); out: mutex_unlock(&wl->mutex); } static int wl1271_op_suspend(struct ieee80211_hw *hw, struct cfg80211_wowlan *wow) { struct wl1271 *wl = hw->priv; struct wl12xx_vif *wlvif; int ret; wl1271_debug(DEBUG_MAC80211, "mac80211 suspend wow=%d", !!wow); WARN_ON(!wow || !wow->any); wl1271_tx_flush(wl); wl->wow_enabled = true; wl12xx_for_each_wlvif(wl, wlvif) { ret = wl1271_configure_suspend(wl, wlvif); if (ret < 0) { wl1271_warning("couldn't prepare device to suspend"); return ret; } } /* flush any remaining work */ wl1271_debug(DEBUG_MAC80211, "flushing remaining works"); /* * disable and re-enable interrupts in order to flush * the threaded_irq */ wl1271_disable_interrupts(wl); /* * set suspended flag to avoid triggering a new threaded_irq * work. no need for spinlock as interrupts are disabled. */ set_bit(WL1271_FLAG_SUSPENDED, &wl->flags); wl1271_enable_interrupts(wl); flush_work(&wl->tx_work); flush_delayed_work(&wl->elp_work); return 0; } static int wl1271_op_resume(struct ieee80211_hw *hw) { struct wl1271 *wl = hw->priv; struct wl12xx_vif *wlvif; unsigned long flags; bool run_irq_work = false; wl1271_debug(DEBUG_MAC80211, "mac80211 resume wow=%d", wl->wow_enabled); WARN_ON(!wl->wow_enabled); /* * re-enable irq_work enqueuing, and call irq_work directly if * there is a pending work. */ spin_lock_irqsave(&wl->wl_lock, flags); clear_bit(WL1271_FLAG_SUSPENDED, &wl->flags); if (test_and_clear_bit(WL1271_FLAG_PENDING_WORK, &wl->flags)) run_irq_work = true; spin_unlock_irqrestore(&wl->wl_lock, flags); if (run_irq_work) { wl1271_debug(DEBUG_MAC80211, "run postponed irq_work directly"); wl1271_irq(0, wl); wl1271_enable_interrupts(wl); } wl12xx_for_each_wlvif(wl, wlvif) { wl1271_configure_resume(wl, wlvif); } wl->wow_enabled = false; return 0; } #endif static int wl1271_op_start(struct ieee80211_hw *hw) { wl1271_debug(DEBUG_MAC80211, "mac80211 start"); /* * We have to delay the booting of the hardware because * we need to know the local MAC address before downloading and * initializing the firmware. The MAC address cannot be changed * after boot, and without the proper MAC address, the firmware * will not function properly. * * The MAC address is first known when the corresponding interface * is added. That is where we will initialize the hardware. */ return 0; } static void wl1271_op_stop(struct ieee80211_hw *hw) { struct wl1271 *wl = hw->priv; int i; wl1271_debug(DEBUG_MAC80211, "mac80211 stop"); /* * Interrupts must be disabled before setting the state to OFF. * Otherwise, the interrupt handler might be called and exit without * reading the interrupt status. */ wl1271_disable_interrupts(wl); mutex_lock(&wl->mutex); if (wl->state == WL1271_STATE_OFF) { mutex_unlock(&wl->mutex); /* * This will not necessarily enable interrupts as interrupts * may have been disabled when op_stop was called. It will, * however, balance the above call to disable_interrupts(). */ wl1271_enable_interrupts(wl); return; } /* * this must be before the cancel_work calls below, so that the work * functions don't perform further work. */ wl->state = WL1271_STATE_OFF; mutex_unlock(&wl->mutex); wl1271_flush_deferred_work(wl); cancel_delayed_work_sync(&wl->scan_complete_work); cancel_work_sync(&wl->netstack_work); cancel_work_sync(&wl->tx_work); cancel_delayed_work_sync(&wl->elp_work); cancel_delayed_work_sync(&wl->tx_watchdog_work); /* let's notify MAC80211 about the remaining pending TX frames */ wl12xx_tx_reset(wl, true); mutex_lock(&wl->mutex); wl1271_power_off(wl); wl->band = IEEE80211_BAND_2GHZ; wl->rx_counter = 0; wl->power_level = WL1271_DEFAULT_POWER_LEVEL; wl->tx_blocks_available = 0; wl->tx_allocated_blocks = 0; wl->tx_results_count = 0; wl->tx_packets_count = 0; wl->time_offset = 0; wl->tx_spare_blocks = TX_HW_BLOCK_SPARE_DEFAULT; wl->ap_fw_ps_map = 0; wl->ap_ps_map = 0; wl->sched_scanning = false; memset(wl->roles_map, 0, sizeof(wl->roles_map)); memset(wl->links_map, 0, sizeof(wl->links_map)); memset(wl->roc_map, 0, sizeof(wl->roc_map)); wl->active_sta_count = 0; /* The system link is always allocated */ __set_bit(WL12XX_SYSTEM_HLID, wl->links_map); /* * this is performed after the cancel_work calls and the associated * mutex_lock, so that wl1271_op_add_interface does not accidentally * get executed before all these vars have been reset. */ wl->flags = 0; wl->tx_blocks_freed = 0; for (i = 0; i < NUM_TX_QUEUES; i++) { wl->tx_pkts_freed[i] = 0; wl->tx_allocated_pkts[i] = 0; } wl1271_debugfs_reset(wl); kfree(wl->fw_status); wl->fw_status = NULL; kfree(wl->tx_res_if); wl->tx_res_if = NULL; kfree(wl->target_mem_map); wl->target_mem_map = NULL; mutex_unlock(&wl->mutex); } static int wl12xx_allocate_rate_policy(struct wl1271 *wl, u8 *idx) { u8 policy = find_first_zero_bit(wl->rate_policies_map, WL12XX_MAX_RATE_POLICIES); if (policy >= WL12XX_MAX_RATE_POLICIES) return -EBUSY; __set_bit(policy, wl->rate_policies_map); *idx = policy; return 0; } static void wl12xx_free_rate_policy(struct wl1271 *wl, u8 *idx) { if (WARN_ON(*idx >= WL12XX_MAX_RATE_POLICIES)) return; __clear_bit(*idx, wl->rate_policies_map); *idx = WL12XX_MAX_RATE_POLICIES; } static u8 wl12xx_get_role_type(struct wl1271 *wl, struct wl12xx_vif *wlvif) { switch (wlvif->bss_type) { case BSS_TYPE_AP_BSS: if (wlvif->p2p) return WL1271_ROLE_P2P_GO; else return WL1271_ROLE_AP; case BSS_TYPE_STA_BSS: if (wlvif->p2p) return WL1271_ROLE_P2P_CL; else return WL1271_ROLE_STA; case BSS_TYPE_IBSS: return WL1271_ROLE_IBSS; default: wl1271_error("invalid bss_type: %d", wlvif->bss_type); } return WL12XX_INVALID_ROLE_TYPE; } static int wl12xx_init_vif_data(struct wl1271 *wl, struct ieee80211_vif *vif) { struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif); int i; /* clear everything but the persistent data */ memset(wlvif, 0, offsetof(struct wl12xx_vif, persistent)); switch (ieee80211_vif_type_p2p(vif)) { case NL80211_IFTYPE_P2P_CLIENT: wlvif->p2p = 1; /* fall-through */ case NL80211_IFTYPE_STATION: wlvif->bss_type = BSS_TYPE_STA_BSS; break; case NL80211_IFTYPE_ADHOC: wlvif->bss_type = BSS_TYPE_IBSS; break; case NL80211_IFTYPE_P2P_GO: wlvif->p2p = 1; /* fall-through */ case NL80211_IFTYPE_AP: wlvif->bss_type = BSS_TYPE_AP_BSS; break; default: wlvif->bss_type = MAX_BSS_TYPE; return -EOPNOTSUPP; } wlvif->role_id = WL12XX_INVALID_ROLE_ID; wlvif->dev_role_id = WL12XX_INVALID_ROLE_ID; wlvif->dev_hlid = WL12XX_INVALID_LINK_ID; if (wlvif->bss_type == BSS_TYPE_STA_BSS || wlvif->bss_type == BSS_TYPE_IBSS) { /* init sta/ibss data */ wlvif->sta.hlid = WL12XX_INVALID_LINK_ID; wl12xx_allocate_rate_policy(wl, &wlvif->sta.basic_rate_idx); wl12xx_allocate_rate_policy(wl, &wlvif->sta.ap_rate_idx); wl12xx_allocate_rate_policy(wl, &wlvif->sta.p2p_rate_idx); } else { /* init ap data */ wlvif->ap.bcast_hlid = WL12XX_INVALID_LINK_ID; wlvif->ap.global_hlid = WL12XX_INVALID_LINK_ID; wl12xx_allocate_rate_policy(wl, &wlvif->ap.mgmt_rate_idx); wl12xx_allocate_rate_policy(wl, &wlvif->ap.bcast_rate_idx); for (i = 0; i < CONF_TX_MAX_AC_COUNT; i++) wl12xx_allocate_rate_policy(wl, &wlvif->ap.ucast_rate_idx[i]); } wlvif->bitrate_masks[IEEE80211_BAND_2GHZ] = wl->conf.tx.basic_rate; wlvif->bitrate_masks[IEEE80211_BAND_5GHZ] = wl->conf.tx.basic_rate_5; wlvif->basic_rate_set = CONF_TX_RATE_MASK_BASIC; wlvif->basic_rate = CONF_TX_RATE_MASK_BASIC; wlvif->rate_set = CONF_TX_RATE_MASK_BASIC; wlvif->beacon_int = WL1271_DEFAULT_BEACON_INT; /* * mac80211 configures some values globally, while we treat them * per-interface. thus, on init, we have to copy them from wl */ wlvif->band = wl->band; wlvif->channel = wl->channel; wlvif->power_level = wl->power_level; INIT_WORK(&wlvif->rx_streaming_enable_work, wl1271_rx_streaming_enable_work); INIT_WORK(&wlvif->rx_streaming_disable_work, wl1271_rx_streaming_disable_work); INIT_LIST_HEAD(&wlvif->list); setup_timer(&wlvif->rx_streaming_timer, wl1271_rx_streaming_timer, (unsigned long) wlvif); return 0; } static bool wl12xx_init_fw(struct wl1271 *wl) { int retries = WL1271_BOOT_RETRIES; bool booted = false; struct wiphy *wiphy = wl->hw->wiphy; int ret; while (retries) { retries--; ret = wl12xx_chip_wakeup(wl, false); if (ret < 0) goto power_off; ret = wl1271_boot(wl); if (ret < 0) goto power_off; ret = wl1271_hw_init(wl); if (ret < 0) goto irq_disable; booted = true; break; irq_disable: mutex_unlock(&wl->mutex); /* Unlocking the mutex in the middle of handling is inherently unsafe. In this case we deem it safe to do, because we need to let any possibly pending IRQ out of the system (and while we are WL1271_STATE_OFF the IRQ work function will not do anything.) Also, any other possible concurrent operations will fail due to the current state, hence the wl1271 struct should be safe. */ wl1271_disable_interrupts(wl); wl1271_flush_deferred_work(wl); cancel_work_sync(&wl->netstack_work); mutex_lock(&wl->mutex); power_off: wl1271_power_off(wl); } if (!booted) { wl1271_error("firmware boot failed despite %d retries", WL1271_BOOT_RETRIES); goto out; } wl1271_info("firmware booted (%s)", wl->chip.fw_ver_str); /* update hw/fw version info in wiphy struct */ wiphy->hw_version = wl->chip.id; strncpy(wiphy->fw_version, wl->chip.fw_ver_str, sizeof(wiphy->fw_version)); /* * Now we know if 11a is supported (info from the NVS), so disable * 11a channels if not supported */ if (!wl->enable_11a) wiphy->bands[IEEE80211_BAND_5GHZ]->n_channels = 0; wl1271_debug(DEBUG_MAC80211, "11a is %ssupported", wl->enable_11a ? "" : "not "); wl->state = WL1271_STATE_ON; out: return booted; } static bool wl12xx_dev_role_started(struct wl12xx_vif *wlvif) { return wlvif->dev_hlid != WL12XX_INVALID_LINK_ID; } /* * Check whether a fw switch (i.e. moving from one loaded * fw to another) is needed. This function is also responsible * for updating wl->last_vif_count, so it must be called before * loading a non-plt fw (so the correct fw (single-role/multi-role) * will be used). */ static bool wl12xx_need_fw_change(struct wl1271 *wl, struct vif_counter_data vif_counter_data, bool add) { enum wl12xx_fw_type current_fw = wl->fw_type; u8 vif_count = vif_counter_data.counter; if (test_bit(WL1271_FLAG_VIF_CHANGE_IN_PROGRESS, &wl->flags)) return false; /* increase the vif count if this is a new vif */ if (add && !vif_counter_data.cur_vif_running) vif_count++; wl->last_vif_count = vif_count; /* no need for fw change if the device is OFF */ if (wl->state == WL1271_STATE_OFF) return false; if (vif_count > 1 && current_fw == WL12XX_FW_TYPE_NORMAL) return true; if (vif_count <= 1 && current_fw == WL12XX_FW_TYPE_MULTI) return true; return false; } /* * Enter "forced psm". Make sure the sta is in psm against the ap, * to make the fw switch a bit more disconnection-persistent. */ static void wl12xx_force_active_psm(struct wl1271 *wl) { struct wl12xx_vif *wlvif; wl12xx_for_each_wlvif_sta(wl, wlvif) { wl1271_ps_set_mode(wl, wlvif, STATION_POWER_SAVE_MODE); } } static int wl1271_op_add_interface(struct ieee80211_hw *hw, struct ieee80211_vif *vif) { struct wl1271 *wl = hw->priv; struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif); struct vif_counter_data vif_count; int ret = 0; u8 role_type; bool booted = false; vif->driver_flags |= IEEE80211_VIF_BEACON_FILTER | IEEE80211_VIF_SUPPORTS_CQM_RSSI; wl1271_debug(DEBUG_MAC80211, "mac80211 add interface type %d mac %pM", ieee80211_vif_type_p2p(vif), vif->addr); wl12xx_get_vif_count(hw, vif, &vif_count); mutex_lock(&wl->mutex); ret = wl1271_ps_elp_wakeup(wl); if (ret < 0) goto out_unlock; /* * in some very corner case HW recovery scenarios its possible to * get here before __wl1271_op_remove_interface is complete, so * opt out if that is the case. */ if (test_bit(WL1271_FLAG_RECOVERY_IN_PROGRESS, &wl->flags) || test_bit(WLVIF_FLAG_INITIALIZED, &wlvif->flags)) { ret = -EBUSY; goto out; } ret = wl12xx_init_vif_data(wl, vif); if (ret < 0) goto out; wlvif->wl = wl; role_type = wl12xx_get_role_type(wl, wlvif); if (role_type == WL12XX_INVALID_ROLE_TYPE) { ret = -EINVAL; goto out; } if (wl12xx_need_fw_change(wl, vif_count, true)) { wl12xx_force_active_psm(wl); set_bit(WL1271_FLAG_INTENDED_FW_RECOVERY, &wl->flags); mutex_unlock(&wl->mutex); wl1271_recovery_work(&wl->recovery_work); return 0; } /* * TODO: after the nvs issue will be solved, move this block * to start(), and make sure here the driver is ON. */ if (wl->state == WL1271_STATE_OFF) { /* * we still need this in order to configure the fw * while uploading the nvs */ memcpy(wl->addresses[0].addr, vif->addr, ETH_ALEN); booted = wl12xx_init_fw(wl); if (!booted) { ret = -EINVAL; goto out; } } if (wlvif->bss_type == BSS_TYPE_STA_BSS || wlvif->bss_type == BSS_TYPE_IBSS) { /* * The device role is a special role used for * rx and tx frames prior to association (as * the STA role can get packets only from * its associated bssid) */ ret = wl12xx_cmd_role_enable(wl, vif->addr, WL1271_ROLE_DEVICE, &wlvif->dev_role_id); if (ret < 0) goto out; } ret = wl12xx_cmd_role_enable(wl, vif->addr, role_type, &wlvif->role_id); if (ret < 0) goto out; ret = wl1271_init_vif_specific(wl, vif); if (ret < 0) goto out; list_add(&wlvif->list, &wl->wlvif_list); set_bit(WLVIF_FLAG_INITIALIZED, &wlvif->flags); if (wlvif->bss_type == BSS_TYPE_AP_BSS) wl->ap_count++; else wl->sta_count++; out: wl1271_ps_elp_sleep(wl); out_unlock: mutex_unlock(&wl->mutex); return ret; } static void __wl1271_op_remove_interface(struct wl1271 *wl, struct ieee80211_vif *vif, bool reset_tx_queues) { struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif); int i, ret; wl1271_debug(DEBUG_MAC80211, "mac80211 remove interface"); if (!test_and_clear_bit(WLVIF_FLAG_INITIALIZED, &wlvif->flags)) return; /* because of hardware recovery, we may get here twice */ if (wl->state != WL1271_STATE_ON) return; wl1271_info("down"); if (wl->scan.state != WL1271_SCAN_STATE_IDLE && wl->scan_vif == vif) { /* * Rearm the tx watchdog just before idling scan. This * prevents just-finished scans from triggering the watchdog */ wl12xx_rearm_tx_watchdog_locked(wl); wl->scan.state = WL1271_SCAN_STATE_IDLE; memset(wl->scan.scanned_ch, 0, sizeof(wl->scan.scanned_ch)); wl->scan_vif = NULL; wl->scan.req = NULL; ieee80211_scan_completed(wl->hw, true); } if (!test_bit(WL1271_FLAG_RECOVERY_IN_PROGRESS, &wl->flags)) { /* disable active roles */ ret = wl1271_ps_elp_wakeup(wl); if (ret < 0) goto deinit; if (wlvif->bss_type == BSS_TYPE_STA_BSS || wlvif->bss_type == BSS_TYPE_IBSS) { if (wl12xx_dev_role_started(wlvif)) wl12xx_stop_dev(wl, wlvif); ret = wl12xx_cmd_role_disable(wl, &wlvif->dev_role_id); if (ret < 0) goto deinit; } ret = wl12xx_cmd_role_disable(wl, &wlvif->role_id); if (ret < 0) goto deinit; wl1271_ps_elp_sleep(wl); } deinit: /* clear all hlids (except system_hlid) */ wlvif->dev_hlid = WL12XX_INVALID_LINK_ID; if (wlvif->bss_type == BSS_TYPE_STA_BSS || wlvif->bss_type == BSS_TYPE_IBSS) { wlvif->sta.hlid = WL12XX_INVALID_LINK_ID; wl12xx_free_rate_policy(wl, &wlvif->sta.basic_rate_idx); wl12xx_free_rate_policy(wl, &wlvif->sta.ap_rate_idx); wl12xx_free_rate_policy(wl, &wlvif->sta.p2p_rate_idx); } else { wlvif->ap.bcast_hlid = WL12XX_INVALID_LINK_ID; wlvif->ap.global_hlid = WL12XX_INVALID_LINK_ID; wl12xx_free_rate_policy(wl, &wlvif->ap.mgmt_rate_idx); wl12xx_free_rate_policy(wl, &wlvif->ap.bcast_rate_idx); for (i = 0; i < CONF_TX_MAX_AC_COUNT; i++) wl12xx_free_rate_policy(wl, &wlvif->ap.ucast_rate_idx[i]); } wl12xx_tx_reset_wlvif(wl, wlvif); wl1271_free_ap_keys(wl, wlvif); if (wl->last_wlvif == wlvif) wl->last_wlvif = NULL; list_del(&wlvif->list); memset(wlvif->ap.sta_hlid_map, 0, sizeof(wlvif->ap.sta_hlid_map)); wlvif->role_id = WL12XX_INVALID_ROLE_ID; wlvif->dev_role_id = WL12XX_INVALID_ROLE_ID; if (wlvif->bss_type == BSS_TYPE_AP_BSS) wl->ap_count--; else wl->sta_count--; mutex_unlock(&wl->mutex); del_timer_sync(&wlvif->rx_streaming_timer); cancel_work_sync(&wlvif->rx_streaming_enable_work); cancel_work_sync(&wlvif->rx_streaming_disable_work); mutex_lock(&wl->mutex); } static void wl1271_op_remove_interface(struct ieee80211_hw *hw, struct ieee80211_vif *vif) { struct wl1271 *wl = hw->priv; struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif); struct wl12xx_vif *iter; struct vif_counter_data vif_count; bool cancel_recovery = true; wl12xx_get_vif_count(hw, vif, &vif_count); mutex_lock(&wl->mutex); if (wl->state == WL1271_STATE_OFF || !test_bit(WLVIF_FLAG_INITIALIZED, &wlvif->flags)) goto out; /* * wl->vif can be null here if someone shuts down the interface * just when hardware recovery has been started. */ wl12xx_for_each_wlvif(wl, iter) { if (iter != wlvif) continue; __wl1271_op_remove_interface(wl, vif, true); break; } WARN_ON(iter != wlvif); if (wl12xx_need_fw_change(wl, vif_count, false)) { wl12xx_force_active_psm(wl); set_bit(WL1271_FLAG_INTENDED_FW_RECOVERY, &wl->flags); wl12xx_queue_recovery_work(wl); cancel_recovery = false; } out: mutex_unlock(&wl->mutex); if (cancel_recovery) cancel_work_sync(&wl->recovery_work); } static int wl12xx_op_change_interface(struct ieee80211_hw *hw, struct ieee80211_vif *vif, enum nl80211_iftype new_type, bool p2p) { struct wl1271 *wl = hw->priv; int ret; set_bit(WL1271_FLAG_VIF_CHANGE_IN_PROGRESS, &wl->flags); wl1271_op_remove_interface(hw, vif); vif->type = new_type; vif->p2p = p2p; ret = wl1271_op_add_interface(hw, vif); clear_bit(WL1271_FLAG_VIF_CHANGE_IN_PROGRESS, &wl->flags); return ret; } static int wl1271_join(struct wl1271 *wl, struct wl12xx_vif *wlvif, bool set_assoc) { int ret; bool is_ibss = (wlvif->bss_type == BSS_TYPE_IBSS); /* * One of the side effects of the JOIN command is that is clears * WPA/WPA2 keys from the chipset. Performing a JOIN while associated * to a WPA/WPA2 access point will therefore kill the data-path. * Currently the only valid scenario for JOIN during association * is on roaming, in which case we will also be given new keys. * Keep the below message for now, unless it starts bothering * users who really like to roam a lot :) */ if (test_bit(WLVIF_FLAG_STA_ASSOCIATED, &wlvif->flags)) wl1271_info("JOIN while associated."); /* clear encryption type */ wlvif->encryption_type = KEY_NONE; if (set_assoc) set_bit(WLVIF_FLAG_STA_ASSOCIATED, &wlvif->flags); if (is_ibss) ret = wl12xx_cmd_role_start_ibss(wl, wlvif); else ret = wl12xx_cmd_role_start_sta(wl, wlvif); if (ret < 0) goto out; if (!test_bit(WLVIF_FLAG_STA_ASSOCIATED, &wlvif->flags)) goto out; /* * The join command disable the keep-alive mode, shut down its process, * and also clear the template config, so we need to reset it all after * the join. The acx_aid starts the keep-alive process, and the order * of the commands below is relevant. */ ret = wl1271_acx_keep_alive_mode(wl, wlvif, true); if (ret < 0) goto out; ret = wl1271_acx_aid(wl, wlvif, wlvif->aid); if (ret < 0) goto out; ret = wl12xx_cmd_build_klv_null_data(wl, wlvif); if (ret < 0) goto out; ret = wl1271_acx_keep_alive_config(wl, wlvif, CMD_TEMPL_KLV_IDX_NULL_DATA, ACX_KEEP_ALIVE_TPL_VALID); if (ret < 0) goto out; out: return ret; } static int wl1271_unjoin(struct wl1271 *wl, struct wl12xx_vif *wlvif) { int ret; if (test_and_clear_bit(WLVIF_FLAG_CS_PROGRESS, &wlvif->flags)) { struct ieee80211_vif *vif = wl12xx_wlvif_to_vif(wlvif); wl12xx_cmd_stop_channel_switch(wl); ieee80211_chswitch_done(vif, false); } /* to stop listening to a channel, we disconnect */ ret = wl12xx_cmd_role_stop_sta(wl, wlvif); if (ret < 0) goto out; /* reset TX security counters on a clean disconnect */ wlvif->tx_security_last_seq_lsb = 0; wlvif->tx_security_seq = 0; out: return ret; } static void wl1271_set_band_rate(struct wl1271 *wl, struct wl12xx_vif *wlvif) { wlvif->basic_rate_set = wlvif->bitrate_masks[wlvif->band]; wlvif->rate_set = wlvif->basic_rate_set; } static int wl1271_sta_handle_idle(struct wl1271 *wl, struct wl12xx_vif *wlvif, bool idle) { int ret; bool cur_idle = !test_bit(WLVIF_FLAG_IN_USE, &wlvif->flags); if (idle == cur_idle) return 0; if (idle) { /* no need to croc if we weren't busy (e.g. during boot) */ if (wl12xx_dev_role_started(wlvif)) { ret = wl12xx_stop_dev(wl, wlvif); if (ret < 0) goto out; } wlvif->rate_set = wl1271_tx_min_rate_get(wl, wlvif->basic_rate_set); ret = wl1271_acx_sta_rate_policies(wl, wlvif); if (ret < 0) goto out; ret = wl1271_acx_keep_alive_config( wl, wlvif, CMD_TEMPL_KLV_IDX_NULL_DATA, ACX_KEEP_ALIVE_TPL_INVALID); if (ret < 0) goto out; clear_bit(WLVIF_FLAG_IN_USE, &wlvif->flags); } else { /* The current firmware only supports sched_scan in idle */ if (wl->sched_scanning) { wl1271_scan_sched_scan_stop(wl); ieee80211_sched_scan_stopped(wl->hw); } ret = wl12xx_start_dev(wl, wlvif); if (ret < 0) goto out; set_bit(WLVIF_FLAG_IN_USE, &wlvif->flags); } out: return ret; } static int wl12xx_config_vif(struct wl1271 *wl, struct wl12xx_vif *wlvif, struct ieee80211_conf *conf, u32 changed) { bool is_ap = (wlvif->bss_type == BSS_TYPE_AP_BSS); int channel, ret; channel = ieee80211_frequency_to_channel(conf->channel->center_freq); /* if the channel changes while joined, join again */ if (changed & IEEE80211_CONF_CHANGE_CHANNEL && ((wlvif->band != conf->channel->band) || (wlvif->channel != channel))) { /* send all pending packets */ wl1271_tx_work_locked(wl); wlvif->band = conf->channel->band; wlvif->channel = channel; if (!is_ap) { /* * FIXME: the mac80211 should really provide a fixed * rate to use here. for now, just use the smallest * possible rate for the band as a fixed rate for * association frames and other control messages. */ if (!test_bit(WLVIF_FLAG_STA_ASSOCIATED, &wlvif->flags)) wl1271_set_band_rate(wl, wlvif); wlvif->basic_rate = wl1271_tx_min_rate_get(wl, wlvif->basic_rate_set); ret = wl1271_acx_sta_rate_policies(wl, wlvif); if (ret < 0) wl1271_warning("rate policy for channel " "failed %d", ret); /* * change the ROC channel. do it only if we are * not idle. otherwise, CROC will be called * anyway. */ if (!test_bit(WLVIF_FLAG_STA_ASSOCIATED, &wlvif->flags) && wl12xx_dev_role_started(wlvif) && !(conf->flags & IEEE80211_CONF_IDLE)) { ret = wl12xx_stop_dev(wl, wlvif); if (ret < 0) return ret; ret = wl12xx_start_dev(wl, wlvif); if (ret < 0) return ret; } } } if ((changed & IEEE80211_CONF_CHANGE_PS) && !is_ap) { if ((conf->flags & IEEE80211_CONF_PS) && test_bit(WLVIF_FLAG_STA_ASSOCIATED, &wlvif->flags) && !test_bit(WLVIF_FLAG_IN_PS, &wlvif->flags)) { int ps_mode; char *ps_mode_str; if (wl->conf.conn.forced_ps) { ps_mode = STATION_POWER_SAVE_MODE; ps_mode_str = "forced"; } else { ps_mode = STATION_AUTO_PS_MODE; ps_mode_str = "auto"; } wl1271_debug(DEBUG_PSM, "%s ps enabled", ps_mode_str); ret = wl1271_ps_set_mode(wl, wlvif, ps_mode); if (ret < 0) wl1271_warning("enter %s ps failed %d", ps_mode_str, ret); } else if (!(conf->flags & IEEE80211_CONF_PS) && test_bit(WLVIF_FLAG_IN_PS, &wlvif->flags)) { wl1271_debug(DEBUG_PSM, "auto ps disabled"); ret = wl1271_ps_set_mode(wl, wlvif, STATION_ACTIVE_MODE); if (ret < 0) wl1271_warning("exit auto ps failed %d", ret); } } if (conf->power_level != wlvif->power_level) { ret = wl1271_acx_tx_power(wl, wlvif, conf->power_level); if (ret < 0) return ret; wlvif->power_level = conf->power_level; } return 0; } static int wl1271_op_config(struct ieee80211_hw *hw, u32 changed) { struct wl1271 *wl = hw->priv; struct wl12xx_vif *wlvif; struct ieee80211_conf *conf = &hw->conf; int channel, ret = 0; channel = ieee80211_frequency_to_channel(conf->channel->center_freq); wl1271_debug(DEBUG_MAC80211, "mac80211 config ch %d psm %s power %d %s" " changed 0x%x", channel, conf->flags & IEEE80211_CONF_PS ? "on" : "off", conf->power_level, conf->flags & IEEE80211_CONF_IDLE ? "idle" : "in use", changed); /* * mac80211 will go to idle nearly immediately after transmitting some * frames, such as the deauth. To make sure those frames reach the air, * wait here until the TX queue is fully flushed. */ if ((changed & IEEE80211_CONF_CHANGE_IDLE) && (conf->flags & IEEE80211_CONF_IDLE)) wl1271_tx_flush(wl); mutex_lock(&wl->mutex); /* we support configuring the channel and band even while off */ if (changed & IEEE80211_CONF_CHANGE_CHANNEL) { wl->band = conf->channel->band; wl->channel = channel; } if (changed & IEEE80211_CONF_CHANGE_POWER) wl->power_level = conf->power_level; if (unlikely(wl->state == WL1271_STATE_OFF)) goto out; ret = wl1271_ps_elp_wakeup(wl); if (ret < 0) goto out; /* configure each interface */ wl12xx_for_each_wlvif(wl, wlvif) { ret = wl12xx_config_vif(wl, wlvif, conf, changed); if (ret < 0) goto out_sleep; } out_sleep: wl1271_ps_elp_sleep(wl); out: mutex_unlock(&wl->mutex); return ret; } struct wl1271_filter_params { bool enabled; int mc_list_length; u8 mc_list[ACX_MC_ADDRESS_GROUP_MAX][ETH_ALEN]; }; #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,35)) static u64 wl1271_op_prepare_multicast(struct ieee80211_hw *hw, struct netdev_hw_addr_list *mc_list) #else static u64 wl1271_op_prepare_multicast(struct ieee80211_hw *hw, int mc_count, struct dev_addr_list *mc_list) #endif { struct wl1271_filter_params *fp; #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,35)) struct netdev_hw_addr *ha; #else int i; #endif struct wl1271 *wl = hw->priv; if (unlikely(wl->state == WL1271_STATE_OFF)) return 0; fp = kzalloc(sizeof(*fp), GFP_ATOMIC); if (!fp) { wl1271_error("Out of memory setting filters."); return 0; } /* update multicast filtering parameters */ #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,35)) fp->mc_list_length = 0; if (netdev_hw_addr_list_count(mc_list) > ACX_MC_ADDRESS_GROUP_MAX) { #else fp->enabled = true; if (mc_count > ACX_MC_ADDRESS_GROUP_MAX) { mc_count = 0; #endif fp->enabled = false; #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,35)) } else { fp->enabled = true; netdev_hw_addr_list_for_each(ha, mc_list) { #else } fp->mc_list_length = 0; for (i = 0; i < mc_count; i++) { if (mc_list->da_addrlen == ETH_ALEN) { #endif memcpy(fp->mc_list[fp->mc_list_length], #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,35)) ha->addr, ETH_ALEN); #else mc_list->da_addr, ETH_ALEN); #endif fp->mc_list_length++; #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,35)) } #else } else wl1271_warning("Unknown mc address length."); mc_list = mc_list->next; #endif } return (u64)(unsigned long)fp; } #define WL1271_SUPPORTED_FILTERS (FIF_PROMISC_IN_BSS | \ FIF_ALLMULTI | \ FIF_FCSFAIL | \ FIF_BCN_PRBRESP_PROMISC | \ FIF_CONTROL | \ FIF_OTHER_BSS) static void wl1271_op_configure_filter(struct ieee80211_hw *hw, unsigned int changed, unsigned int *total, u64 multicast) { struct wl1271_filter_params *fp = (void *)(unsigned long)multicast; struct wl1271 *wl = hw->priv; struct wl12xx_vif *wlvif; int ret; wl1271_debug(DEBUG_MAC80211, "mac80211 configure filter changed %x" " total %x", changed, *total); mutex_lock(&wl->mutex); *total &= WL1271_SUPPORTED_FILTERS; changed &= WL1271_SUPPORTED_FILTERS; if (unlikely(wl->state == WL1271_STATE_OFF)) goto out; ret = wl1271_ps_elp_wakeup(wl); if (ret < 0) goto out; wl12xx_for_each_wlvif(wl, wlvif) { if (wlvif->bss_type != BSS_TYPE_AP_BSS) { if (*total & FIF_ALLMULTI) ret = wl1271_acx_group_address_tbl(wl, wlvif, false, NULL, 0); else if (fp) ret = wl1271_acx_group_address_tbl(wl, wlvif, fp->enabled, fp->mc_list, fp->mc_list_length); if (ret < 0) goto out_sleep; } } /* * the fw doesn't provide an api to configure the filters. instead, * the filters configuration is based on the active roles / ROC * state. */ out_sleep: wl1271_ps_elp_sleep(wl); out: mutex_unlock(&wl->mutex); kfree(fp); } static int wl1271_record_ap_key(struct wl1271 *wl, struct wl12xx_vif *wlvif, u8 id, u8 key_type, u8 key_size, const u8 *key, u8 hlid, u32 tx_seq_32, u16 tx_seq_16) { struct wl1271_ap_key *ap_key; int i; wl1271_debug(DEBUG_CRYPT, "record ap key id %d", (int)id); if (key_size > MAX_KEY_SIZE) return -EINVAL; /* * Find next free entry in ap_keys. Also check we are not replacing * an existing key. */ for (i = 0; i < MAX_NUM_KEYS; i++) { if (wlvif->ap.recorded_keys[i] == NULL) break; if (wlvif->ap.recorded_keys[i]->id == id) { wl1271_warning("trying to record key replacement"); return -EINVAL; } } if (i == MAX_NUM_KEYS) return -EBUSY; ap_key = kzalloc(sizeof(*ap_key), GFP_KERNEL); if (!ap_key) return -ENOMEM; ap_key->id = id; ap_key->key_type = key_type; ap_key->key_size = key_size; memcpy(ap_key->key, key, key_size); ap_key->hlid = hlid; ap_key->tx_seq_32 = tx_seq_32; ap_key->tx_seq_16 = tx_seq_16; wlvif->ap.recorded_keys[i] = ap_key; return 0; } static void wl1271_free_ap_keys(struct wl1271 *wl, struct wl12xx_vif *wlvif) { int i; for (i = 0; i < MAX_NUM_KEYS; i++) { kfree(wlvif->ap.recorded_keys[i]); wlvif->ap.recorded_keys[i] = NULL; } } static int wl1271_ap_init_hwenc(struct wl1271 *wl, struct wl12xx_vif *wlvif) { int i, ret = 0; struct wl1271_ap_key *key; bool wep_key_added = false; for (i = 0; i < MAX_NUM_KEYS; i++) { u8 hlid; if (wlvif->ap.recorded_keys[i] == NULL) break; key = wlvif->ap.recorded_keys[i]; hlid = key->hlid; if (hlid == WL12XX_INVALID_LINK_ID) hlid = wlvif->ap.bcast_hlid; ret = wl1271_cmd_set_ap_key(wl, wlvif, KEY_ADD_OR_REPLACE, key->id, key->key_type, key->key_size, key->key, hlid, key->tx_seq_32, key->tx_seq_16); if (ret < 0) goto out; if (key->key_type == KEY_WEP) wep_key_added = true; } if (wep_key_added) { ret = wl12xx_cmd_set_default_wep_key(wl, wlvif->default_key, wlvif->ap.bcast_hlid); if (ret < 0) goto out; } out: wl1271_free_ap_keys(wl, wlvif); return ret; } static int wl1271_set_key(struct wl1271 *wl, struct wl12xx_vif *wlvif, u16 action, u8 id, u8 key_type, u8 key_size, const u8 *key, u32 tx_seq_32, u16 tx_seq_16, struct ieee80211_sta *sta) { int ret; bool is_ap = (wlvif->bss_type == BSS_TYPE_AP_BSS); if (is_ap) { struct wl1271_station *wl_sta; u8 hlid; if (sta) { wl_sta = (struct wl1271_station *)sta->drv_priv; hlid = wl_sta->hlid; } else { hlid = wlvif->ap.bcast_hlid; } if (!test_bit(WLVIF_FLAG_AP_STARTED, &wlvif->flags)) { /* * We do not support removing keys after AP shutdown. * Pretend we do to make mac80211 happy. */ if (action != KEY_ADD_OR_REPLACE) return 0; ret = wl1271_record_ap_key(wl, wlvif, id, key_type, key_size, key, hlid, tx_seq_32, tx_seq_16); } else { ret = wl1271_cmd_set_ap_key(wl, wlvif, action, id, key_type, key_size, key, hlid, tx_seq_32, tx_seq_16); } if (ret < 0) return ret; } else { const u8 *addr; static const u8 bcast_addr[ETH_ALEN] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }; /* * A STA set to GEM cipher requires 2 tx spare blocks. * Return to default value when GEM cipher key is removed */ if (key_type == KEY_GEM) { if (action == KEY_ADD_OR_REPLACE) wl->tx_spare_blocks = 2; else if (action == KEY_REMOVE) wl->tx_spare_blocks = TX_HW_BLOCK_SPARE_DEFAULT; } addr = sta ? sta->addr : bcast_addr; if (is_zero_ether_addr(addr)) { /* We dont support TX only encryption */ return -EOPNOTSUPP; } /* The wl1271 does not allow to remove unicast keys - they will be cleared automatically on next CMD_JOIN. Ignore the request silently, as we dont want the mac80211 to emit an error message. */ if (action == KEY_REMOVE && !is_broadcast_ether_addr(addr)) return 0; /* don't remove key if hlid was already deleted */ if (action == KEY_REMOVE && wlvif->sta.hlid == WL12XX_INVALID_LINK_ID) return 0; ret = wl1271_cmd_set_sta_key(wl, wlvif, action, id, key_type, key_size, key, addr, tx_seq_32, tx_seq_16); if (ret < 0) return ret; /* the default WEP key needs to be configured at least once */ if (key_type == KEY_WEP) { ret = wl12xx_cmd_set_default_wep_key(wl, wlvif->default_key, wlvif->sta.hlid); if (ret < 0) return ret; } } return 0; } static int wl1271_op_set_key(struct ieee80211_hw *hw, enum set_key_cmd cmd, struct ieee80211_vif *vif, struct ieee80211_sta *sta, struct ieee80211_key_conf *key_conf) { struct wl1271 *wl = hw->priv; struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif); int ret; u32 tx_seq_32 = 0; u16 tx_seq_16 = 0; u8 key_type; wl1271_debug(DEBUG_MAC80211, "mac80211 set key"); wl1271_debug(DEBUG_CRYPT, "CMD: 0x%x sta: %p", cmd, sta); wl1271_debug(DEBUG_CRYPT, "Key: algo:0x%x, id:%d, len:%d flags 0x%x", key_conf->cipher, key_conf->keyidx, key_conf->keylen, key_conf->flags); wl1271_dump(DEBUG_CRYPT, "KEY: ", key_conf->key, key_conf->keylen); mutex_lock(&wl->mutex); if (unlikely(wl->state == WL1271_STATE_OFF)) { ret = -EAGAIN; goto out_unlock; } ret = wl1271_ps_elp_wakeup(wl); if (ret < 0) goto out_unlock; switch (key_conf->cipher) { case WLAN_CIPHER_SUITE_WEP40: case WLAN_CIPHER_SUITE_WEP104: key_type = KEY_WEP; key_conf->hw_key_idx = key_conf->keyidx; break; case WLAN_CIPHER_SUITE_TKIP: key_type = KEY_TKIP; key_conf->hw_key_idx = key_conf->keyidx; tx_seq_32 = WL1271_TX_SECURITY_HI32(wlvif->tx_security_seq); tx_seq_16 = WL1271_TX_SECURITY_LO16(wlvif->tx_security_seq); break; case WLAN_CIPHER_SUITE_CCMP: key_type = KEY_AES; key_conf->flags |= IEEE80211_KEY_FLAG_PUT_IV_SPACE; tx_seq_32 = WL1271_TX_SECURITY_HI32(wlvif->tx_security_seq); tx_seq_16 = WL1271_TX_SECURITY_LO16(wlvif->tx_security_seq); break; case WL1271_CIPHER_SUITE_GEM: key_type = KEY_GEM; tx_seq_32 = WL1271_TX_SECURITY_HI32(wlvif->tx_security_seq); tx_seq_16 = WL1271_TX_SECURITY_LO16(wlvif->tx_security_seq); break; default: wl1271_error("Unknown key algo 0x%x", key_conf->cipher); ret = -EOPNOTSUPP; goto out_sleep; } switch (cmd) { case SET_KEY: ret = wl1271_set_key(wl, wlvif, KEY_ADD_OR_REPLACE, key_conf->keyidx, key_type, key_conf->keylen, key_conf->key, tx_seq_32, tx_seq_16, sta); if (ret < 0) { wl1271_error("Could not add or replace key"); goto out_sleep; } /* * reconfiguring arp response if the unicast (or common) * encryption key type was changed */ if (wlvif->bss_type == BSS_TYPE_STA_BSS && (sta || key_type == KEY_WEP) && wlvif->encryption_type != key_type) { wlvif->encryption_type = key_type; ret = wl1271_cmd_build_arp_rsp(wl, wlvif); if (ret < 0) { wl1271_warning("build arp rsp failed: %d", ret); goto out_sleep; } } break; case DISABLE_KEY: ret = wl1271_set_key(wl, wlvif, KEY_REMOVE, key_conf->keyidx, key_type, key_conf->keylen, key_conf->key, 0, 0, sta); if (ret < 0) { wl1271_error("Could not remove key"); goto out_sleep; } break; default: wl1271_error("Unsupported key cmd 0x%x", cmd); ret = -EOPNOTSUPP; break; } out_sleep: wl1271_ps_elp_sleep(wl); out_unlock: mutex_unlock(&wl->mutex); return ret; } static int wl1271_op_hw_scan(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct cfg80211_scan_request *req) { struct wl1271 *wl = hw->priv; int ret; u8 *ssid = NULL; size_t len = 0; wl1271_debug(DEBUG_MAC80211, "mac80211 hw scan"); if (req->n_ssids) { ssid = req->ssids[0].ssid; len = req->ssids[0].ssid_len; } mutex_lock(&wl->mutex); if (wl->state == WL1271_STATE_OFF) { /* * We cannot return -EBUSY here because cfg80211 will expect * a call to ieee80211_scan_completed if we do - in this case * there won't be any call. */ ret = -EAGAIN; goto out; } ret = wl1271_ps_elp_wakeup(wl); if (ret < 0) goto out; /* fail if there is any role in ROC */ if (find_first_bit(wl->roc_map, WL12XX_MAX_ROLES) < WL12XX_MAX_ROLES) { /* don't allow scanning right now */ ret = -EBUSY; goto out_sleep; } ret = wl1271_scan(hw->priv, vif, ssid, len, req); out_sleep: wl1271_ps_elp_sleep(wl); out: mutex_unlock(&wl->mutex); return ret; } static void wl1271_op_cancel_hw_scan(struct ieee80211_hw *hw, struct ieee80211_vif *vif) { struct wl1271 *wl = hw->priv; int ret; wl1271_debug(DEBUG_MAC80211, "mac80211 cancel hw scan"); mutex_lock(&wl->mutex); if (wl->state == WL1271_STATE_OFF) goto out; if (wl->scan.state == WL1271_SCAN_STATE_IDLE) goto out; ret = wl1271_ps_elp_wakeup(wl); if (ret < 0) goto out; if (wl->scan.state != WL1271_SCAN_STATE_DONE) { ret = wl1271_scan_stop(wl); if (ret < 0) goto out_sleep; } /* * Rearm the tx watchdog just before idling scan. This * prevents just-finished scans from triggering the watchdog */ wl12xx_rearm_tx_watchdog_locked(wl); wl->scan.state = WL1271_SCAN_STATE_IDLE; memset(wl->scan.scanned_ch, 0, sizeof(wl->scan.scanned_ch)); wl->scan_vif = NULL; wl->scan.req = NULL; ieee80211_scan_completed(wl->hw, true); out_sleep: wl1271_ps_elp_sleep(wl); out: mutex_unlock(&wl->mutex); cancel_delayed_work_sync(&wl->scan_complete_work); } static int wl1271_op_sched_scan_start(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct cfg80211_sched_scan_request *req, struct ieee80211_sched_scan_ies *ies) { struct wl1271 *wl = hw->priv; struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif); int ret; wl1271_debug(DEBUG_MAC80211, "wl1271_op_sched_scan_start"); mutex_lock(&wl->mutex); if (wl->state == WL1271_STATE_OFF) { ret = -EAGAIN; goto out; } ret = wl1271_ps_elp_wakeup(wl); if (ret < 0) goto out; ret = wl1271_scan_sched_scan_config(wl, wlvif, req, ies); if (ret < 0) goto out_sleep; ret = wl1271_scan_sched_scan_start(wl, wlvif); if (ret < 0) goto out_sleep; wl->sched_scanning = true; out_sleep: wl1271_ps_elp_sleep(wl); out: mutex_unlock(&wl->mutex); return ret; } static void wl1271_op_sched_scan_stop(struct ieee80211_hw *hw, struct ieee80211_vif *vif) { struct wl1271 *wl = hw->priv; int ret; wl1271_debug(DEBUG_MAC80211, "wl1271_op_sched_scan_stop"); mutex_lock(&wl->mutex); if (wl->state == WL1271_STATE_OFF) goto out; ret = wl1271_ps_elp_wakeup(wl); if (ret < 0) goto out; wl1271_scan_sched_scan_stop(wl); wl1271_ps_elp_sleep(wl); out: mutex_unlock(&wl->mutex); } static int wl1271_op_set_frag_threshold(struct ieee80211_hw *hw, u32 value) { struct wl1271 *wl = hw->priv; int ret = 0; mutex_lock(&wl->mutex); if (unlikely(wl->state == WL1271_STATE_OFF)) { ret = -EAGAIN; goto out; } ret = wl1271_ps_elp_wakeup(wl); if (ret < 0) goto out; ret = wl1271_acx_frag_threshold(wl, value); if (ret < 0) wl1271_warning("wl1271_op_set_frag_threshold failed: %d", ret); wl1271_ps_elp_sleep(wl); out: mutex_unlock(&wl->mutex); return ret; } static int wl1271_op_set_rts_threshold(struct ieee80211_hw *hw, u32 value) { struct wl1271 *wl = hw->priv; struct wl12xx_vif *wlvif; int ret = 0; mutex_lock(&wl->mutex); if (unlikely(wl->state == WL1271_STATE_OFF)) { ret = -EAGAIN; goto out; } ret = wl1271_ps_elp_wakeup(wl); if (ret < 0) goto out; wl12xx_for_each_wlvif(wl, wlvif) { ret = wl1271_acx_rts_threshold(wl, wlvif, value); if (ret < 0) wl1271_warning("set rts threshold failed: %d", ret); } wl1271_ps_elp_sleep(wl); out: mutex_unlock(&wl->mutex); return ret; } static int wl1271_ssid_set(struct ieee80211_vif *vif, struct sk_buff *skb, int offset) { struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif); u8 ssid_len; const u8 *ptr = cfg80211_find_ie(WLAN_EID_SSID, skb->data + offset, skb->len - offset); if (!ptr) { wl1271_error("No SSID in IEs!"); return -ENOENT; } ssid_len = ptr[1]; if (ssid_len > IEEE80211_MAX_SSID_LEN) { wl1271_error("SSID is too long!"); return -EINVAL; } wlvif->ssid_len = ssid_len; memcpy(wlvif->ssid, ptr+2, ssid_len); return 0; } static void wl12xx_remove_ie(struct sk_buff *skb, u8 eid, int ieoffset) { int len; const u8 *next, *end = skb->data + skb->len; u8 *ie = (u8 *)cfg80211_find_ie(eid, skb->data + ieoffset, skb->len - ieoffset); if (!ie) return; len = ie[1] + 2; next = ie + len; memmove(ie, next, end - next); skb_trim(skb, skb->len - len); } static void wl12xx_remove_vendor_ie(struct sk_buff *skb, unsigned int oui, u8 oui_type, int ieoffset) { int len; const u8 *next, *end = skb->data + skb->len; u8 *ie = (u8 *)cfg80211_find_vendor_ie(oui, oui_type, skb->data + ieoffset, skb->len - ieoffset); if (!ie) return; len = ie[1] + 2; next = ie + len; memmove(ie, next, end - next); skb_trim(skb, skb->len - len); } static int wl1271_ap_set_probe_resp_tmpl(struct wl1271 *wl, u32 rates, struct ieee80211_vif *vif) { struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif); struct sk_buff *skb; int ret; skb = ieee80211_proberesp_get(wl->hw, vif); if (!skb) return -EOPNOTSUPP; ret = wl1271_cmd_template_set(wl, wlvif->role_id, CMD_TEMPL_AP_PROBE_RESPONSE, skb->data, skb->len, 0, rates); dev_kfree_skb(skb); return ret; } static int wl1271_ap_set_probe_resp_tmpl_legacy(struct wl1271 *wl, struct ieee80211_vif *vif, u8 *probe_rsp_data, size_t probe_rsp_len, u32 rates) { struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif); struct ieee80211_bss_conf *bss_conf = &vif->bss_conf; u8 probe_rsp_templ[WL1271_CMD_TEMPL_MAX_SIZE]; int ssid_ie_offset, ie_offset, templ_len; const u8 *ptr; /* no need to change probe response if the SSID is set correctly */ if (wlvif->ssid_len > 0) return wl1271_cmd_template_set(wl, wlvif->role_id, CMD_TEMPL_AP_PROBE_RESPONSE, probe_rsp_data, probe_rsp_len, 0, rates); if (probe_rsp_len + bss_conf->ssid_len > WL1271_CMD_TEMPL_MAX_SIZE) { wl1271_error("probe_rsp template too big"); return -EINVAL; } /* start searching from IE offset */ ie_offset = offsetof(struct ieee80211_mgmt, u.probe_resp.variable); ptr = cfg80211_find_ie(WLAN_EID_SSID, probe_rsp_data + ie_offset, probe_rsp_len - ie_offset); if (!ptr) { wl1271_error("No SSID in beacon!"); return -EINVAL; } ssid_ie_offset = ptr - probe_rsp_data; ptr += (ptr[1] + 2); memcpy(probe_rsp_templ, probe_rsp_data, ssid_ie_offset); /* insert SSID from bss_conf */ probe_rsp_templ[ssid_ie_offset] = WLAN_EID_SSID; probe_rsp_templ[ssid_ie_offset + 1] = bss_conf->ssid_len; memcpy(probe_rsp_templ + ssid_ie_offset + 2, bss_conf->ssid, bss_conf->ssid_len); templ_len = ssid_ie_offset + 2 + bss_conf->ssid_len; memcpy(probe_rsp_templ + ssid_ie_offset + 2 + bss_conf->ssid_len, ptr, probe_rsp_len - (ptr - probe_rsp_data)); templ_len += probe_rsp_len - (ptr - probe_rsp_data); return wl1271_cmd_template_set(wl, wlvif->role_id, CMD_TEMPL_AP_PROBE_RESPONSE, probe_rsp_templ, templ_len, 0, rates); } static int wl1271_bss_erp_info_changed(struct wl1271 *wl, struct ieee80211_vif *vif, struct ieee80211_bss_conf *bss_conf, u32 changed) { struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif); int ret = 0; if (changed & BSS_CHANGED_ERP_SLOT) { if (bss_conf->use_short_slot) ret = wl1271_acx_slot(wl, wlvif, SLOT_TIME_SHORT); else ret = wl1271_acx_slot(wl, wlvif, SLOT_TIME_LONG); if (ret < 0) { wl1271_warning("Set slot time failed %d", ret); goto out; } } if (changed & BSS_CHANGED_ERP_PREAMBLE) { if (bss_conf->use_short_preamble) wl1271_acx_set_preamble(wl, wlvif, ACX_PREAMBLE_SHORT); else wl1271_acx_set_preamble(wl, wlvif, ACX_PREAMBLE_LONG); } if (changed & BSS_CHANGED_ERP_CTS_PROT) { if (bss_conf->use_cts_prot) ret = wl1271_acx_cts_protect(wl, wlvif, CTSPROTECT_ENABLE); else ret = wl1271_acx_cts_protect(wl, wlvif, CTSPROTECT_DISABLE); if (ret < 0) { wl1271_warning("Set ctsprotect failed %d", ret); goto out; } } out: return ret; } static int wl1271_bss_beacon_info_changed(struct wl1271 *wl, struct ieee80211_vif *vif, struct ieee80211_bss_conf *bss_conf, u32 changed) { struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif); bool is_ap = (wlvif->bss_type == BSS_TYPE_AP_BSS); int ret = 0; if ((changed & BSS_CHANGED_BEACON_INT)) { wl1271_debug(DEBUG_MASTER, "beacon interval updated: %d", bss_conf->beacon_int); wlvif->beacon_int = bss_conf->beacon_int; } if ((changed & BSS_CHANGED_AP_PROBE_RESP) && is_ap) { u32 rate = wl1271_tx_min_rate_get(wl, wlvif->basic_rate_set); if (!wl1271_ap_set_probe_resp_tmpl(wl, rate, vif)) { wl1271_debug(DEBUG_AP, "probe response updated"); set_bit(WLVIF_FLAG_AP_PROBE_RESP_SET, &wlvif->flags); } } if ((changed & BSS_CHANGED_BEACON)) { struct ieee80211_hdr *hdr; u32 min_rate; int ieoffset = offsetof(struct ieee80211_mgmt, u.beacon.variable); struct sk_buff *beacon = ieee80211_beacon_get(wl->hw, vif); u16 tmpl_id; if (!beacon) { ret = -EINVAL; goto out; } wl1271_debug(DEBUG_MASTER, "beacon updated"); ret = wl1271_ssid_set(vif, beacon, ieoffset); if (ret < 0) { dev_kfree_skb(beacon); goto out; } min_rate = wl1271_tx_min_rate_get(wl, wlvif->basic_rate_set); tmpl_id = is_ap ? CMD_TEMPL_AP_BEACON : CMD_TEMPL_BEACON; ret = wl1271_cmd_template_set(wl, wlvif->role_id, tmpl_id, beacon->data, beacon->len, 0, min_rate); if (ret < 0) { dev_kfree_skb(beacon); goto out; } /* * In case we already have a probe-resp beacon set explicitly * by usermode, don't use the beacon data. */ if (test_bit(WLVIF_FLAG_AP_PROBE_RESP_SET, &wlvif->flags)) goto end_bcn; /* remove TIM ie from probe response */ wl12xx_remove_ie(beacon, WLAN_EID_TIM, ieoffset); /* * remove p2p ie from probe response. * the fw reponds to probe requests that don't include * the p2p ie. probe requests with p2p ie will be passed, * and will be responded by the supplicant (the spec * forbids including the p2p ie when responding to probe * requests that didn't include it). */ wl12xx_remove_vendor_ie(beacon, WLAN_OUI_WFA, WLAN_OUI_TYPE_WFA_P2P, ieoffset); hdr = (struct ieee80211_hdr *) beacon->data; hdr->frame_control = cpu_to_le16(IEEE80211_FTYPE_MGMT | IEEE80211_STYPE_PROBE_RESP); if (is_ap) ret = wl1271_ap_set_probe_resp_tmpl_legacy(wl, vif, beacon->data, beacon->len, min_rate); else ret = wl1271_cmd_template_set(wl, wlvif->role_id, CMD_TEMPL_PROBE_RESPONSE, beacon->data, beacon->len, 0, min_rate); end_bcn: dev_kfree_skb(beacon); if (ret < 0) goto out; } out: if (ret != 0) wl1271_error("beacon info change failed: %d", ret); return ret; } /* AP mode changes */ static void wl1271_bss_info_changed_ap(struct wl1271 *wl, struct ieee80211_vif *vif, struct ieee80211_bss_conf *bss_conf, u32 changed) { struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif); int ret = 0; if ((changed & BSS_CHANGED_BASIC_RATES)) { u32 rates = bss_conf->basic_rates; wlvif->basic_rate_set = wl1271_tx_enabled_rates_get(wl, rates, wlvif->band); wlvif->basic_rate = wl1271_tx_min_rate_get(wl, wlvif->basic_rate_set); ret = wl1271_init_ap_rates(wl, wlvif); if (ret < 0) { wl1271_error("AP rate policy change failed %d", ret); goto out; } ret = wl1271_ap_init_templates(wl, vif); if (ret < 0) goto out; } ret = wl1271_bss_beacon_info_changed(wl, vif, bss_conf, changed); if (ret < 0) goto out; if ((changed & BSS_CHANGED_BEACON_ENABLED)) { if (bss_conf->enable_beacon) { if (!test_bit(WLVIF_FLAG_AP_STARTED, &wlvif->flags)) { ret = wl12xx_cmd_role_start_ap(wl, wlvif); if (ret < 0) goto out; ret = wl1271_ap_init_hwenc(wl, wlvif); if (ret < 0) goto out; set_bit(WLVIF_FLAG_AP_STARTED, &wlvif->flags); wl1271_debug(DEBUG_AP, "started AP"); } } else { if (test_bit(WLVIF_FLAG_AP_STARTED, &wlvif->flags)) { ret = wl12xx_cmd_role_stop_ap(wl, wlvif); if (ret < 0) goto out; clear_bit(WLVIF_FLAG_AP_STARTED, &wlvif->flags); clear_bit(WLVIF_FLAG_AP_PROBE_RESP_SET, &wlvif->flags); wl1271_debug(DEBUG_AP, "stopped AP"); } } } ret = wl1271_bss_erp_info_changed(wl, vif, bss_conf, changed); if (ret < 0) goto out; /* Handle HT information change */ if ((changed & BSS_CHANGED_HT) && (bss_conf->channel_type != NL80211_CHAN_NO_HT)) { ret = wl1271_acx_set_ht_information(wl, wlvif, bss_conf->ht_operation_mode); if (ret < 0) { wl1271_warning("Set ht information failed %d", ret); goto out; } } out: return; } /* STA/IBSS mode changes */ static void wl1271_bss_info_changed_sta(struct wl1271 *wl, struct ieee80211_vif *vif, struct ieee80211_bss_conf *bss_conf, u32 changed) { struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif); bool do_join = false, set_assoc = false; bool is_ibss = (wlvif->bss_type == BSS_TYPE_IBSS); bool ibss_joined = false; u32 sta_rate_set = 0; int ret; struct ieee80211_sta *sta; bool sta_exists = false; struct ieee80211_sta_ht_cap sta_ht_cap; if (is_ibss) { ret = wl1271_bss_beacon_info_changed(wl, vif, bss_conf, changed); if (ret < 0) goto out; } if (changed & BSS_CHANGED_IBSS) { if (bss_conf->ibss_joined) { set_bit(WLVIF_FLAG_IBSS_JOINED, &wlvif->flags); ibss_joined = true; } else { if (test_and_clear_bit(WLVIF_FLAG_IBSS_JOINED, &wlvif->flags)) wl1271_unjoin(wl, wlvif); } } if ((changed & BSS_CHANGED_BEACON_INT) && ibss_joined) do_join = true; /* Need to update the SSID (for filtering etc) */ if ((changed & BSS_CHANGED_BEACON) && ibss_joined) do_join = true; if ((changed & BSS_CHANGED_BEACON_ENABLED) && ibss_joined) { wl1271_debug(DEBUG_ADHOC, "ad-hoc beaconing: %s", bss_conf->enable_beacon ? "enabled" : "disabled"); do_join = true; } if (changed & BSS_CHANGED_IDLE && !is_ibss) { ret = wl1271_sta_handle_idle(wl, wlvif, bss_conf->idle); if (ret < 0) wl1271_warning("idle mode change failed %d", ret); } if ((changed & BSS_CHANGED_CQM)) { bool enable = false; if (bss_conf->cqm_rssi_thold) enable = true; ret = wl1271_acx_rssi_snr_trigger(wl, wlvif, enable, bss_conf->cqm_rssi_thold, bss_conf->cqm_rssi_hyst); if (ret < 0) goto out; wlvif->rssi_thold = bss_conf->cqm_rssi_thold; } if (changed & BSS_CHANGED_BSSID && (is_ibss || bss_conf->assoc)) if (!is_zero_ether_addr(bss_conf->bssid)) { ret = wl12xx_cmd_build_null_data(wl, wlvif); if (ret < 0) goto out; ret = wl1271_build_qos_null_data(wl, vif); if (ret < 0) goto out; /* Need to update the BSSID (for filtering etc) */ do_join = true; } if (changed & (BSS_CHANGED_ASSOC | BSS_CHANGED_HT)) { rcu_read_lock(); sta = ieee80211_find_sta(vif, bss_conf->bssid); if (!sta) goto sta_not_found; /* save the supp_rates of the ap */ sta_rate_set = sta->supp_rates[wl->hw->conf.channel->band]; if (sta->ht_cap.ht_supported) sta_rate_set |= (sta->ht_cap.mcs.rx_mask[0] << HW_HT_RATES_OFFSET); sta_ht_cap = sta->ht_cap; sta_exists = true; sta_not_found: rcu_read_unlock(); } if ((changed & BSS_CHANGED_ASSOC)) { if (bss_conf->assoc) { u32 rates; int ieoffset; wlvif->aid = bss_conf->aid; wlvif->beacon_int = bss_conf->beacon_int; set_assoc = true; /* * use basic rates from AP, and determine lowest rate * to use with control frames. */ rates = bss_conf->basic_rates; wlvif->basic_rate_set = wl1271_tx_enabled_rates_get(wl, rates, wlvif->band); wlvif->basic_rate = wl1271_tx_min_rate_get(wl, wlvif->basic_rate_set); if (sta_rate_set) wlvif->rate_set = wl1271_tx_enabled_rates_get(wl, sta_rate_set, wlvif->band); ret = wl1271_acx_sta_rate_policies(wl, wlvif); if (ret < 0) goto out; /* * with wl1271, we don't need to update the * beacon_int and dtim_period, because the firmware * updates it by itself when the first beacon is * received after a join. */ ret = wl1271_cmd_build_ps_poll(wl, wlvif, wlvif->aid); if (ret < 0) goto out; /* * Get a template for hardware connection maintenance */ dev_kfree_skb(wlvif->probereq); wlvif->probereq = wl1271_cmd_build_ap_probe_req(wl, wlvif, NULL); ieoffset = offsetof(struct ieee80211_mgmt, u.probe_req.variable); wl1271_ssid_set(vif, wlvif->probereq, ieoffset); /* enable the connection monitoring feature */ ret = wl1271_acx_conn_monit_params(wl, wlvif, true); if (ret < 0) goto out; } else { /* use defaults when not associated */ bool was_assoc = !!test_and_clear_bit(WLVIF_FLAG_STA_ASSOCIATED, &wlvif->flags); bool was_ifup = !!test_and_clear_bit(WLVIF_FLAG_STA_STATE_SENT, &wlvif->flags); wlvif->aid = 0; /* free probe-request template */ dev_kfree_skb(wlvif->probereq); wlvif->probereq = NULL; /* revert back to minimum rates for the current band */ wl1271_set_band_rate(wl, wlvif); wlvif->basic_rate = wl1271_tx_min_rate_get(wl, wlvif->basic_rate_set); ret = wl1271_acx_sta_rate_policies(wl, wlvif); if (ret < 0) goto out; /* disable connection monitor features */ ret = wl1271_acx_conn_monit_params(wl, wlvif, false); /* Disable the keep-alive feature */ ret = wl1271_acx_keep_alive_mode(wl, wlvif, false); if (ret < 0) goto out; /* restore the bssid filter and go to dummy bssid */ if (was_assoc) { /* * we might have to disable roc, if there was * no IF_OPER_UP notification. */ if (!was_ifup) { ret = wl12xx_croc(wl, wlvif->role_id); if (ret < 0) goto out; } /* * (we also need to disable roc in case of * roaming on the same channel. until we will * have a better flow...) */ if (test_bit(wlvif->dev_role_id, wl->roc_map)) { ret = wl12xx_croc(wl, wlvif->dev_role_id); if (ret < 0) goto out; } wl1271_unjoin(wl, wlvif); if (!bss_conf->idle) wl12xx_start_dev(wl, wlvif); } } } if (changed & BSS_CHANGED_IBSS) { wl1271_debug(DEBUG_ADHOC, "ibss_joined: %d", bss_conf->ibss_joined); if (bss_conf->ibss_joined) { u32 rates = bss_conf->basic_rates; wlvif->basic_rate_set = wl1271_tx_enabled_rates_get(wl, rates, wlvif->band); wlvif->basic_rate = wl1271_tx_min_rate_get(wl, wlvif->basic_rate_set); /* by default, use 11b + OFDM rates */ wlvif->rate_set = CONF_TX_IBSS_DEFAULT_RATES; ret = wl1271_acx_sta_rate_policies(wl, wlvif); if (ret < 0) goto out; } } ret = wl1271_bss_erp_info_changed(wl, vif, bss_conf, changed); if (ret < 0) goto out; if (do_join) { ret = wl1271_join(wl, wlvif, set_assoc); if (ret < 0) { wl1271_warning("cmd join failed %d", ret); goto out; } /* ROC until connected (after EAPOL exchange) */ if (!is_ibss) { ret = wl12xx_roc(wl, wlvif, wlvif->role_id); if (ret < 0) goto out; if (test_bit(WLVIF_FLAG_STA_AUTHORIZED, &wlvif->flags)) wl12xx_set_authorized(wl, wlvif); } /* * stop device role if started (we might already be in * STA/IBSS role). */ if (wl12xx_dev_role_started(wlvif)) { ret = wl12xx_stop_dev(wl, wlvif); if (ret < 0) goto out; } } /* Handle new association with HT. Do this after join. */ if (sta_exists) { if ((changed & BSS_CHANGED_HT) && (bss_conf->channel_type != NL80211_CHAN_NO_HT)) { ret = wl1271_acx_set_ht_capabilities(wl, &sta_ht_cap, true, wlvif->sta.hlid); if (ret < 0) { wl1271_warning("Set ht cap true failed %d", ret); goto out; } } /* handle new association without HT and disassociation */ else if (changed & BSS_CHANGED_ASSOC) { ret = wl1271_acx_set_ht_capabilities(wl, &sta_ht_cap, false, wlvif->sta.hlid); if (ret < 0) { wl1271_warning("Set ht cap false failed %d", ret); goto out; } } } /* Handle HT information change. Done after join. */ if ((changed & BSS_CHANGED_HT) && (bss_conf->channel_type != NL80211_CHAN_NO_HT)) { ret = wl1271_acx_set_ht_information(wl, wlvif, bss_conf->ht_operation_mode); if (ret < 0) { wl1271_warning("Set ht information failed %d", ret); goto out; } } /* Handle arp filtering. Done after join. */ if ((changed & BSS_CHANGED_ARP_FILTER) || (!is_ibss && (changed & BSS_CHANGED_QOS))) { __be32 addr = bss_conf->arp_addr_list[0]; wlvif->sta.qos = bss_conf->qos; WARN_ON(wlvif->bss_type != BSS_TYPE_STA_BSS); if (bss_conf->arp_addr_cnt == 1 && bss_conf->arp_filter_enabled) { wlvif->ip_addr = addr; /* * The template should have been configured only upon * association. however, it seems that the correct ip * isn't being set (when sending), so we have to * reconfigure the template upon every ip change. */ ret = wl1271_cmd_build_arp_rsp(wl, wlvif); if (ret < 0) { wl1271_warning("build arp rsp failed: %d", ret); goto out; } ret = wl1271_acx_arp_ip_filter(wl, wlvif, (ACX_ARP_FILTER_ARP_FILTERING | ACX_ARP_FILTER_AUTO_ARP), addr); } else { wlvif->ip_addr = 0; ret = wl1271_acx_arp_ip_filter(wl, wlvif, 0, addr); } if (ret < 0) goto out; } out: return; } static void wl1271_op_bss_info_changed(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct ieee80211_bss_conf *bss_conf, u32 changed) { struct wl1271 *wl = hw->priv; struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif); bool is_ap = (wlvif->bss_type == BSS_TYPE_AP_BSS); int ret; wl1271_debug(DEBUG_MAC80211, "mac80211 bss info changed 0x%x", (int)changed); mutex_lock(&wl->mutex); if (unlikely(wl->state == WL1271_STATE_OFF)) goto out; if (unlikely(!test_bit(WLVIF_FLAG_INITIALIZED, &wlvif->flags))) goto out; ret = wl1271_ps_elp_wakeup(wl); if (ret < 0) goto out; if (is_ap) wl1271_bss_info_changed_ap(wl, vif, bss_conf, changed); else wl1271_bss_info_changed_sta(wl, vif, bss_conf, changed); wl1271_ps_elp_sleep(wl); out: mutex_unlock(&wl->mutex); } static int wl1271_op_conf_tx(struct ieee80211_hw *hw, struct ieee80211_vif *vif, u16 queue, const struct ieee80211_tx_queue_params *params) { struct wl1271 *wl = hw->priv; struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif); u8 ps_scheme; int ret = 0; mutex_lock(&wl->mutex); wl1271_debug(DEBUG_MAC80211, "mac80211 conf tx %d", queue); if (params->uapsd) ps_scheme = CONF_PS_SCHEME_UPSD_TRIGGER; else ps_scheme = CONF_PS_SCHEME_LEGACY; if (!test_bit(WLVIF_FLAG_INITIALIZED, &wlvif->flags)) goto out; ret = wl1271_ps_elp_wakeup(wl); if (ret < 0) goto out; /* * the txop is confed in units of 32us by the mac80211, * we need us */ ret = wl1271_acx_ac_cfg(wl, wlvif, wl1271_tx_get_queue(queue), params->cw_min, params->cw_max, params->aifs, params->txop << 5); if (ret < 0) goto out_sleep; ret = wl1271_acx_tid_cfg(wl, wlvif, wl1271_tx_get_queue(queue), CONF_CHANNEL_TYPE_EDCF, wl1271_tx_get_queue(queue), ps_scheme, CONF_ACK_POLICY_LEGACY, 0, 0); out_sleep: wl1271_ps_elp_sleep(wl); out: mutex_unlock(&wl->mutex); return ret; } static u64 wl1271_op_get_tsf(struct ieee80211_hw *hw, struct ieee80211_vif *vif) { struct wl1271 *wl = hw->priv; struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif); u64 mactime = ULLONG_MAX; int ret; wl1271_debug(DEBUG_MAC80211, "mac80211 get tsf"); mutex_lock(&wl->mutex); if (unlikely(wl->state == WL1271_STATE_OFF)) goto out; ret = wl1271_ps_elp_wakeup(wl); if (ret < 0) goto out; ret = wl12xx_acx_tsf_info(wl, wlvif, &mactime); if (ret < 0) goto out_sleep; out_sleep: wl1271_ps_elp_sleep(wl); out: mutex_unlock(&wl->mutex); return mactime; } static int wl1271_op_get_survey(struct ieee80211_hw *hw, int idx, struct survey_info *survey) { struct wl1271 *wl = hw->priv; struct ieee80211_conf *conf = &hw->conf; if (idx != 0) return -ENOENT; survey->channel = conf->channel; survey->filled = SURVEY_INFO_NOISE_DBM; survey->noise = wl->noise; return 0; } static int wl1271_allocate_sta(struct wl1271 *wl, struct wl12xx_vif *wlvif, struct ieee80211_sta *sta) { struct wl1271_station *wl_sta; int ret; if (wl->active_sta_count >= AP_MAX_STATIONS) { wl1271_warning("could not allocate HLID - too much stations"); return -EBUSY; } wl_sta = (struct wl1271_station *)sta->drv_priv; ret = wl12xx_allocate_link(wl, wlvif, &wl_sta->hlid); if (ret < 0) { wl1271_warning("could not allocate HLID - too many links"); return -EBUSY; } set_bit(wl_sta->hlid, wlvif->ap.sta_hlid_map); memcpy(wl->links[wl_sta->hlid].addr, sta->addr, ETH_ALEN); wl->active_sta_count++; return 0; } void wl1271_free_sta(struct wl1271 *wl, struct wl12xx_vif *wlvif, u8 hlid) { if (!test_bit(hlid, wlvif->ap.sta_hlid_map)) return; clear_bit(hlid, wlvif->ap.sta_hlid_map); memset(wl->links[hlid].addr, 0, ETH_ALEN); wl->links[hlid].ba_bitmap = 0; __clear_bit(hlid, &wl->ap_ps_map); __clear_bit(hlid, (unsigned long *)&wl->ap_fw_ps_map); wl12xx_free_link(wl, wlvif, &hlid); wl->active_sta_count--; /* * rearm the tx watchdog when the last STA is freed - give the FW a * chance to return STA-buffered packets before complaining. */ if (wl->active_sta_count == 0) wl12xx_rearm_tx_watchdog_locked(wl); } static int wl12xx_sta_add(struct wl1271 *wl, struct wl12xx_vif *wlvif, struct ieee80211_sta *sta) { struct wl1271_station *wl_sta; int ret = 0; u8 hlid; wl1271_debug(DEBUG_MAC80211, "mac80211 add sta %d", (int)sta->aid); ret = wl1271_allocate_sta(wl, wlvif, sta); if (ret < 0) return ret; wl_sta = (struct wl1271_station *)sta->drv_priv; hlid = wl_sta->hlid; ret = wl12xx_cmd_add_peer(wl, wlvif, sta, hlid); if (ret < 0) wl1271_free_sta(wl, wlvif, hlid); return ret; } static int wl12xx_sta_remove(struct wl1271 *wl, struct wl12xx_vif *wlvif, struct ieee80211_sta *sta) { struct wl1271_station *wl_sta; int ret = 0, id; wl1271_debug(DEBUG_MAC80211, "mac80211 remove sta %d", (int)sta->aid); wl_sta = (struct wl1271_station *)sta->drv_priv; id = wl_sta->hlid; if (WARN_ON(!test_bit(id, wlvif->ap.sta_hlid_map))) return -EINVAL; ret = wl12xx_cmd_remove_peer(wl, wl_sta->hlid); if (ret < 0) return ret; wl1271_free_sta(wl, wlvif, wl_sta->hlid); return ret; } static int wl12xx_update_sta_state(struct wl1271 *wl, struct wl12xx_vif *wlvif, struct ieee80211_sta *sta, enum ieee80211_sta_state old_state, enum ieee80211_sta_state new_state) { struct wl1271_station *wl_sta; u8 hlid; bool is_ap = wlvif->bss_type == BSS_TYPE_AP_BSS; bool is_sta = wlvif->bss_type == BSS_TYPE_STA_BSS; int ret; wl_sta = (struct wl1271_station *)sta->drv_priv; hlid = wl_sta->hlid; /* Add station (AP mode) */ if (is_ap && old_state == IEEE80211_STA_NOTEXIST && new_state == IEEE80211_STA_NONE) return wl12xx_sta_add(wl, wlvif, sta); /* Remove station (AP mode) */ if (is_ap && old_state == IEEE80211_STA_NONE && new_state == IEEE80211_STA_NOTEXIST) { /* must not fail */ wl12xx_sta_remove(wl, wlvif, sta); return 0; } /* Authorize station (AP mode) */ if (is_ap && new_state == IEEE80211_STA_AUTHORIZED) { ret = wl12xx_cmd_set_peer_state(wl, hlid); if (ret < 0) return ret; ret = wl1271_acx_set_ht_capabilities(wl, &sta->ht_cap, true, hlid); return ret; } /* Authorize station */ if (is_sta && new_state == IEEE80211_STA_AUTHORIZED) { set_bit(WLVIF_FLAG_STA_AUTHORIZED, &wlvif->flags); return wl12xx_set_authorized(wl, wlvif); } if (is_sta && old_state == IEEE80211_STA_AUTHORIZED && new_state == IEEE80211_STA_ASSOC) { clear_bit(WLVIF_FLAG_STA_AUTHORIZED, &wlvif->flags); return 0; } return 0; } static int wl12xx_op_sta_state(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct ieee80211_sta *sta, enum ieee80211_sta_state old_state, enum ieee80211_sta_state new_state) { struct wl1271 *wl = hw->priv; struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif); int ret; wl1271_debug(DEBUG_MAC80211, "mac80211 sta %d state=%d->%d", sta->aid, old_state, new_state); mutex_lock(&wl->mutex); if (unlikely(wl->state == WL1271_STATE_OFF)) { ret = -EBUSY; goto out; } ret = wl1271_ps_elp_wakeup(wl); if (ret < 0) goto out; ret = wl12xx_update_sta_state(wl, wlvif, sta, old_state, new_state); wl1271_ps_elp_sleep(wl); out: mutex_unlock(&wl->mutex); if (new_state < old_state) return 0; return ret; } static int wl1271_op_ampdu_action(struct ieee80211_hw *hw, struct ieee80211_vif *vif, enum ieee80211_ampdu_mlme_action action, struct ieee80211_sta *sta, u16 tid, u16 *ssn, u8 buf_size) { struct wl1271 *wl = hw->priv; struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif); int ret; u8 hlid, *ba_bitmap; wl1271_debug(DEBUG_MAC80211, "mac80211 ampdu action %d tid %d", action, tid); /* sanity check - the fields in FW are only 8bits wide */ if (WARN_ON(tid > 0xFF)) return -ENOTSUPP; mutex_lock(&wl->mutex); if (unlikely(wl->state == WL1271_STATE_OFF)) { ret = -EAGAIN; goto out; } if (wlvif->bss_type == BSS_TYPE_STA_BSS) { hlid = wlvif->sta.hlid; ba_bitmap = &wlvif->sta.ba_rx_bitmap; } else if (wlvif->bss_type == BSS_TYPE_AP_BSS) { struct wl1271_station *wl_sta; wl_sta = (struct wl1271_station *)sta->drv_priv; hlid = wl_sta->hlid; ba_bitmap = &wl->links[hlid].ba_bitmap; } else { ret = -EINVAL; goto out; } ret = wl1271_ps_elp_wakeup(wl); if (ret < 0) goto out; wl1271_debug(DEBUG_MAC80211, "mac80211 ampdu: Rx tid %d action %d", tid, action); switch (action) { case IEEE80211_AMPDU_RX_START: if (!wlvif->ba_support || !wlvif->ba_allowed) { ret = -ENOTSUPP; break; } if (wl->ba_rx_session_count >= RX_BA_MAX_SESSIONS) { ret = -EBUSY; wl1271_error("exceeded max RX BA sessions"); break; } if (*ba_bitmap & BIT(tid)) { ret = -EINVAL; wl1271_error("cannot enable RX BA session on active " "tid: %d", tid); break; } ret = wl12xx_acx_set_ba_receiver_session(wl, tid, *ssn, true, hlid); if (!ret) { *ba_bitmap |= BIT(tid); wl->ba_rx_session_count++; } break; case IEEE80211_AMPDU_RX_STOP: if (!(*ba_bitmap & BIT(tid))) { ret = -EINVAL; wl1271_error("no active RX BA session on tid: %d", tid); break; } ret = wl12xx_acx_set_ba_receiver_session(wl, tid, 0, false, hlid); if (!ret) { *ba_bitmap &= ~BIT(tid); wl->ba_rx_session_count--; } break; /* * The BA initiator session management in FW independently. * Falling break here on purpose for all TX APDU commands. */ case IEEE80211_AMPDU_TX_START: case IEEE80211_AMPDU_TX_STOP: case IEEE80211_AMPDU_TX_OPERATIONAL: ret = -EINVAL; break; default: wl1271_error("Incorrect ampdu action id=%x\n", action); ret = -EINVAL; } wl1271_ps_elp_sleep(wl); out: mutex_unlock(&wl->mutex); return ret; } static int wl12xx_set_bitrate_mask(struct ieee80211_hw *hw, struct ieee80211_vif *vif, const struct cfg80211_bitrate_mask *mask) { struct wl12xx_vif *wlvif = wl12xx_vif_to_data(vif); struct wl1271 *wl = hw->priv; int i, ret = 0; wl1271_debug(DEBUG_MAC80211, "mac80211 set_bitrate_mask 0x%x 0x%x", mask->control[NL80211_BAND_2GHZ].legacy, mask->control[NL80211_BAND_5GHZ].legacy); mutex_lock(&wl->mutex); for (i = 0; i < IEEE80211_NUM_BANDS; i++) wlvif->bitrate_masks[i] = wl1271_tx_enabled_rates_get(wl, mask->control[i].legacy, i); if (unlikely(wl->state == WL1271_STATE_OFF)) goto out; if (wlvif->bss_type == BSS_TYPE_STA_BSS && !test_bit(WLVIF_FLAG_STA_ASSOCIATED, &wlvif->flags)) { ret = wl1271_ps_elp_wakeup(wl); if (ret < 0) goto out; wl1271_set_band_rate(wl, wlvif); wlvif->basic_rate = wl1271_tx_min_rate_get(wl, wlvif->basic_rate_set); ret = wl1271_acx_sta_rate_policies(wl, wlvif); wl1271_ps_elp_sleep(wl); } out: mutex_unlock(&wl->mutex); return ret; } static void wl12xx_op_channel_switch(struct ieee80211_hw *hw, struct ieee80211_channel_switch *ch_switch) { struct wl1271 *wl = hw->priv; struct wl12xx_vif *wlvif; int ret; wl1271_debug(DEBUG_MAC80211, "mac80211 channel switch"); wl1271_tx_flush(wl); mutex_lock(&wl->mutex); if (unlikely(wl->state == WL1271_STATE_OFF)) { wl12xx_for_each_wlvif_sta(wl, wlvif) { struct ieee80211_vif *vif = wl12xx_wlvif_to_vif(wlvif); ieee80211_chswitch_done(vif, false); } goto out; } ret = wl1271_ps_elp_wakeup(wl); if (ret < 0) goto out; /* TODO: change mac80211 to pass vif as param */ wl12xx_for_each_wlvif_sta(wl, wlvif) { ret = wl12xx_cmd_channel_switch(wl, wlvif, ch_switch); if (!ret) set_bit(WLVIF_FLAG_CS_PROGRESS, &wlvif->flags); } wl1271_ps_elp_sleep(wl); out: mutex_unlock(&wl->mutex); } static bool wl1271_tx_frames_pending(struct ieee80211_hw *hw) { struct wl1271 *wl = hw->priv; bool ret = false; mutex_lock(&wl->mutex); if (unlikely(wl->state == WL1271_STATE_OFF)) goto out; /* packets are considered pending if in the TX queue or the FW */ ret = (wl1271_tx_total_queue_count(wl) > 0) || (wl->tx_frames_cnt > 0); out: mutex_unlock(&wl->mutex); return ret; } /* can't be const, mac80211 writes to this */ static struct ieee80211_rate wl1271_rates[] = { { .bitrate = 10, .hw_value = CONF_HW_BIT_RATE_1MBPS, .hw_value_short = CONF_HW_BIT_RATE_1MBPS, }, { .bitrate = 20, .hw_value = CONF_HW_BIT_RATE_2MBPS, .hw_value_short = CONF_HW_BIT_RATE_2MBPS, .flags = IEEE80211_RATE_SHORT_PREAMBLE }, { .bitrate = 55, .hw_value = CONF_HW_BIT_RATE_5_5MBPS, .hw_value_short = CONF_HW_BIT_RATE_5_5MBPS, .flags = IEEE80211_RATE_SHORT_PREAMBLE }, { .bitrate = 110, .hw_value = CONF_HW_BIT_RATE_11MBPS, .hw_value_short = CONF_HW_BIT_RATE_11MBPS, .flags = IEEE80211_RATE_SHORT_PREAMBLE }, { .bitrate = 60, .hw_value = CONF_HW_BIT_RATE_6MBPS, .hw_value_short = CONF_HW_BIT_RATE_6MBPS, }, { .bitrate = 90, .hw_value = CONF_HW_BIT_RATE_9MBPS, .hw_value_short = CONF_HW_BIT_RATE_9MBPS, }, { .bitrate = 120, .hw_value = CONF_HW_BIT_RATE_12MBPS, .hw_value_short = CONF_HW_BIT_RATE_12MBPS, }, { .bitrate = 180, .hw_value = CONF_HW_BIT_RATE_18MBPS, .hw_value_short = CONF_HW_BIT_RATE_18MBPS, }, { .bitrate = 240, .hw_value = CONF_HW_BIT_RATE_24MBPS, .hw_value_short = CONF_HW_BIT_RATE_24MBPS, }, { .bitrate = 360, .hw_value = CONF_HW_BIT_RATE_36MBPS, .hw_value_short = CONF_HW_BIT_RATE_36MBPS, }, { .bitrate = 480, .hw_value = CONF_HW_BIT_RATE_48MBPS, .hw_value_short = CONF_HW_BIT_RATE_48MBPS, }, { .bitrate = 540, .hw_value = CONF_HW_BIT_RATE_54MBPS, .hw_value_short = CONF_HW_BIT_RATE_54MBPS, }, }; /* can't be const, mac80211 writes to this */ static struct ieee80211_channel wl1271_channels[] = { { .hw_value = 1, .center_freq = 2412, .max_power = 25 }, { .hw_value = 2, .center_freq = 2417, .max_power = 25 }, { .hw_value = 3, .center_freq = 2422, .max_power = 25 }, { .hw_value = 4, .center_freq = 2427, .max_power = 25 }, { .hw_value = 5, .center_freq = 2432, .max_power = 25 }, { .hw_value = 6, .center_freq = 2437, .max_power = 25 }, { .hw_value = 7, .center_freq = 2442, .max_power = 25 }, { .hw_value = 8, .center_freq = 2447, .max_power = 25 }, { .hw_value = 9, .center_freq = 2452, .max_power = 25 }, { .hw_value = 10, .center_freq = 2457, .max_power = 25 }, { .hw_value = 11, .center_freq = 2462, .max_power = 25 }, { .hw_value = 12, .center_freq = 2467, .max_power = 25 }, { .hw_value = 13, .center_freq = 2472, .max_power = 25 }, { .hw_value = 14, .center_freq = 2484, .max_power = 25 }, }; /* mapping to indexes for wl1271_rates */ static const u8 wl1271_rate_to_idx_2ghz[] = { /* MCS rates are used only with 11n */ 7, /* CONF_HW_RXTX_RATE_MCS7_SGI */ 7, /* CONF_HW_RXTX_RATE_MCS7 */ 6, /* CONF_HW_RXTX_RATE_MCS6 */ 5, /* CONF_HW_RXTX_RATE_MCS5 */ 4, /* CONF_HW_RXTX_RATE_MCS4 */ 3, /* CONF_HW_RXTX_RATE_MCS3 */ 2, /* CONF_HW_RXTX_RATE_MCS2 */ 1, /* CONF_HW_RXTX_RATE_MCS1 */ 0, /* CONF_HW_RXTX_RATE_MCS0 */ 11, /* CONF_HW_RXTX_RATE_54 */ 10, /* CONF_HW_RXTX_RATE_48 */ 9, /* CONF_HW_RXTX_RATE_36 */ 8, /* CONF_HW_RXTX_RATE_24 */ /* TI-specific rate */ CONF_HW_RXTX_RATE_UNSUPPORTED, /* CONF_HW_RXTX_RATE_22 */ 7, /* CONF_HW_RXTX_RATE_18 */ 6, /* CONF_HW_RXTX_RATE_12 */ 3, /* CONF_HW_RXTX_RATE_11 */ 5, /* CONF_HW_RXTX_RATE_9 */ 4, /* CONF_HW_RXTX_RATE_6 */ 2, /* CONF_HW_RXTX_RATE_5_5 */ 1, /* CONF_HW_RXTX_RATE_2 */ 0 /* CONF_HW_RXTX_RATE_1 */ }; /* 11n STA capabilities */ #define HW_RX_HIGHEST_RATE 72 #define WL12XX_HT_CAP { \ .cap = IEEE80211_HT_CAP_GRN_FLD | IEEE80211_HT_CAP_SGI_20 | \ (1 << IEEE80211_HT_CAP_RX_STBC_SHIFT), \ .ht_supported = true, \ .ampdu_factor = IEEE80211_HT_MAX_AMPDU_8K, \ .ampdu_density = IEEE80211_HT_MPDU_DENSITY_8, \ .mcs = { \ .rx_mask = { 0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0, }, \ .rx_highest = cpu_to_le16(HW_RX_HIGHEST_RATE), \ .tx_params = IEEE80211_HT_MCS_TX_DEFINED, \ }, \ } /* can't be const, mac80211 writes to this */ static struct ieee80211_supported_band wl1271_band_2ghz = { .channels = wl1271_channels, .n_channels = ARRAY_SIZE(wl1271_channels), .bitrates = wl1271_rates, .n_bitrates = ARRAY_SIZE(wl1271_rates), .ht_cap = WL12XX_HT_CAP, }; /* 5 GHz data rates for WL1273 */ static struct ieee80211_rate wl1271_rates_5ghz[] = { { .bitrate = 60, .hw_value = CONF_HW_BIT_RATE_6MBPS, .hw_value_short = CONF_HW_BIT_RATE_6MBPS, }, { .bitrate = 90, .hw_value = CONF_HW_BIT_RATE_9MBPS, .hw_value_short = CONF_HW_BIT_RATE_9MBPS, }, { .bitrate = 120, .hw_value = CONF_HW_BIT_RATE_12MBPS, .hw_value_short = CONF_HW_BIT_RATE_12MBPS, }, { .bitrate = 180, .hw_value = CONF_HW_BIT_RATE_18MBPS, .hw_value_short = CONF_HW_BIT_RATE_18MBPS, }, { .bitrate = 240, .hw_value = CONF_HW_BIT_RATE_24MBPS, .hw_value_short = CONF_HW_BIT_RATE_24MBPS, }, { .bitrate = 360, .hw_value = CONF_HW_BIT_RATE_36MBPS, .hw_value_short = CONF_HW_BIT_RATE_36MBPS, }, { .bitrate = 480, .hw_value = CONF_HW_BIT_RATE_48MBPS, .hw_value_short = CONF_HW_BIT_RATE_48MBPS, }, { .bitrate = 540, .hw_value = CONF_HW_BIT_RATE_54MBPS, .hw_value_short = CONF_HW_BIT_RATE_54MBPS, }, }; /* 5 GHz band channels for WL1273 */ static struct ieee80211_channel wl1271_channels_5ghz[] = { { .hw_value = 7, .center_freq = 5035, .max_power = 25 }, { .hw_value = 8, .center_freq = 5040, .max_power = 25 }, { .hw_value = 9, .center_freq = 5045, .max_power = 25 }, { .hw_value = 11, .center_freq = 5055, .max_power = 25 }, { .hw_value = 12, .center_freq = 5060, .max_power = 25 }, { .hw_value = 16, .center_freq = 5080, .max_power = 25 }, { .hw_value = 34, .center_freq = 5170, .max_power = 25 }, { .hw_value = 36, .center_freq = 5180, .max_power = 25 }, { .hw_value = 38, .center_freq = 5190, .max_power = 25 }, { .hw_value = 40, .center_freq = 5200, .max_power = 25 }, { .hw_value = 42, .center_freq = 5210, .max_power = 25 }, { .hw_value = 44, .center_freq = 5220, .max_power = 25 }, { .hw_value = 46, .center_freq = 5230, .max_power = 25 }, { .hw_value = 48, .center_freq = 5240, .max_power = 25 }, { .hw_value = 52, .center_freq = 5260, .max_power = 25 }, { .hw_value = 56, .center_freq = 5280, .max_power = 25 }, { .hw_value = 60, .center_freq = 5300, .max_power = 25 }, { .hw_value = 64, .center_freq = 5320, .max_power = 25 }, { .hw_value = 100, .center_freq = 5500, .max_power = 25 }, { .hw_value = 104, .center_freq = 5520, .max_power = 25 }, { .hw_value = 108, .center_freq = 5540, .max_power = 25 }, { .hw_value = 112, .center_freq = 5560, .max_power = 25 }, { .hw_value = 116, .center_freq = 5580, .max_power = 25 }, { .hw_value = 120, .center_freq = 5600, .max_power = 25 }, { .hw_value = 124, .center_freq = 5620, .max_power = 25 }, { .hw_value = 128, .center_freq = 5640, .max_power = 25 }, { .hw_value = 132, .center_freq = 5660, .max_power = 25 }, { .hw_value = 136, .center_freq = 5680, .max_power = 25 }, { .hw_value = 140, .center_freq = 5700, .max_power = 25 }, { .hw_value = 149, .center_freq = 5745, .max_power = 25 }, { .hw_value = 153, .center_freq = 5765, .max_power = 25 }, { .hw_value = 157, .center_freq = 5785, .max_power = 25 }, { .hw_value = 161, .center_freq = 5805, .max_power = 25 }, { .hw_value = 165, .center_freq = 5825, .max_power = 25 }, }; /* mapping to indexes for wl1271_rates_5ghz */ static const u8 wl1271_rate_to_idx_5ghz[] = { /* MCS rates are used only with 11n */ 7, /* CONF_HW_RXTX_RATE_MCS7_SGI */ 7, /* CONF_HW_RXTX_RATE_MCS7 */ 6, /* CONF_HW_RXTX_RATE_MCS6 */ 5, /* CONF_HW_RXTX_RATE_MCS5 */ 4, /* CONF_HW_RXTX_RATE_MCS4 */ 3, /* CONF_HW_RXTX_RATE_MCS3 */ 2, /* CONF_HW_RXTX_RATE_MCS2 */ 1, /* CONF_HW_RXTX_RATE_MCS1 */ 0, /* CONF_HW_RXTX_RATE_MCS0 */ 7, /* CONF_HW_RXTX_RATE_54 */ 6, /* CONF_HW_RXTX_RATE_48 */ 5, /* CONF_HW_RXTX_RATE_36 */ 4, /* CONF_HW_RXTX_RATE_24 */ /* TI-specific rate */ CONF_HW_RXTX_RATE_UNSUPPORTED, /* CONF_HW_RXTX_RATE_22 */ 3, /* CONF_HW_RXTX_RATE_18 */ 2, /* CONF_HW_RXTX_RATE_12 */ CONF_HW_RXTX_RATE_UNSUPPORTED, /* CONF_HW_RXTX_RATE_11 */ 1, /* CONF_HW_RXTX_RATE_9 */ 0, /* CONF_HW_RXTX_RATE_6 */ CONF_HW_RXTX_RATE_UNSUPPORTED, /* CONF_HW_RXTX_RATE_5_5 */ CONF_HW_RXTX_RATE_UNSUPPORTED, /* CONF_HW_RXTX_RATE_2 */ CONF_HW_RXTX_RATE_UNSUPPORTED /* CONF_HW_RXTX_RATE_1 */ }; static struct ieee80211_supported_band wl1271_band_5ghz = { .channels = wl1271_channels_5ghz, .n_channels = ARRAY_SIZE(wl1271_channels_5ghz), .bitrates = wl1271_rates_5ghz, .n_bitrates = ARRAY_SIZE(wl1271_rates_5ghz), .ht_cap = WL12XX_HT_CAP, }; static const u8 *wl1271_band_rate_to_idx[] = { [IEEE80211_BAND_2GHZ] = wl1271_rate_to_idx_2ghz, [IEEE80211_BAND_5GHZ] = wl1271_rate_to_idx_5ghz }; static const struct ieee80211_ops wl1271_ops = { .start = wl1271_op_start, .stop = wl1271_op_stop, .add_interface = wl1271_op_add_interface, .remove_interface = wl1271_op_remove_interface, .change_interface = wl12xx_op_change_interface, #ifdef CONFIG_PM .suspend = wl1271_op_suspend, .resume = wl1271_op_resume, #endif .config = wl1271_op_config, .prepare_multicast = wl1271_op_prepare_multicast, .configure_filter = wl1271_op_configure_filter, .tx = wl1271_op_tx, .set_key = wl1271_op_set_key, .hw_scan = wl1271_op_hw_scan, .cancel_hw_scan = wl1271_op_cancel_hw_scan, .sched_scan_start = wl1271_op_sched_scan_start, .sched_scan_stop = wl1271_op_sched_scan_stop, .bss_info_changed = wl1271_op_bss_info_changed, .set_frag_threshold = wl1271_op_set_frag_threshold, .set_rts_threshold = wl1271_op_set_rts_threshold, .conf_tx = wl1271_op_conf_tx, .get_tsf = wl1271_op_get_tsf, .get_survey = wl1271_op_get_survey, .sta_state = wl12xx_op_sta_state, .ampdu_action = wl1271_op_ampdu_action, .tx_frames_pending = wl1271_tx_frames_pending, .set_bitrate_mask = wl12xx_set_bitrate_mask, .channel_switch = wl12xx_op_channel_switch, CFG80211_TESTMODE_CMD(wl1271_tm_cmd) }; u8 wl1271_rate_to_idx(int rate, enum ieee80211_band band) { u8 idx; BUG_ON(band >= sizeof(wl1271_band_rate_to_idx)/sizeof(u8 *)); if (unlikely(rate >= CONF_HW_RXTX_RATE_MAX)) { wl1271_error("Illegal RX rate from HW: %d", rate); return 0; } idx = wl1271_band_rate_to_idx[band][rate]; if (unlikely(idx == CONF_HW_RXTX_RATE_UNSUPPORTED)) { wl1271_error("Unsupported RX rate from HW: %d", rate); return 0; } return idx; } static ssize_t wl1271_sysfs_show_bt_coex_state(struct device *dev, struct device_attribute *attr, char *buf) { struct wl1271 *wl = dev_get_drvdata(dev); ssize_t len; len = PAGE_SIZE; mutex_lock(&wl->mutex); len = snprintf(buf, len, "%d\n\n0 - off\n1 - on\n", wl->sg_enabled); mutex_unlock(&wl->mutex); return len; } static ssize_t wl1271_sysfs_store_bt_coex_state(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct wl1271 *wl = dev_get_drvdata(dev); unsigned long res; int ret; ret = kstrtoul(buf, 10, &res); if (ret < 0) { wl1271_warning("incorrect value written to bt_coex_mode"); return count; } mutex_lock(&wl->mutex); res = !!res; if (res == wl->sg_enabled) goto out; wl->sg_enabled = res; if (wl->state == WL1271_STATE_OFF) goto out; ret = wl1271_ps_elp_wakeup(wl); if (ret < 0) goto out; wl1271_acx_sg_enable(wl, wl->sg_enabled); wl1271_ps_elp_sleep(wl); out: mutex_unlock(&wl->mutex); return count; } static DEVICE_ATTR(bt_coex_state, S_IRUGO | S_IWUSR, wl1271_sysfs_show_bt_coex_state, wl1271_sysfs_store_bt_coex_state); static ssize_t wl1271_sysfs_show_hw_pg_ver(struct device *dev, struct device_attribute *attr, char *buf) { struct wl1271 *wl = dev_get_drvdata(dev); ssize_t len; len = PAGE_SIZE; mutex_lock(&wl->mutex); if (wl->hw_pg_ver >= 0) len = snprintf(buf, len, "%d\n", wl->hw_pg_ver); else len = snprintf(buf, len, "n/a\n"); mutex_unlock(&wl->mutex); return len; } static DEVICE_ATTR(hw_pg_ver, S_IRUGO, wl1271_sysfs_show_hw_pg_ver, NULL); static ssize_t wl1271_sysfs_read_fwlog(struct file *filp, struct kobject *kobj, struct bin_attribute *bin_attr, char *buffer, loff_t pos, size_t count) { struct device *dev = container_of(kobj, struct device, kobj); struct wl1271 *wl = dev_get_drvdata(dev); ssize_t len; int ret; ret = mutex_lock_interruptible(&wl->mutex); if (ret < 0) return -ERESTARTSYS; /* Let only one thread read the log at a time, blocking others */ while (wl->fwlog_size == 0) { DEFINE_WAIT(wait); prepare_to_wait_exclusive(&wl->fwlog_waitq, &wait, TASK_INTERRUPTIBLE); if (wl->fwlog_size != 0) { finish_wait(&wl->fwlog_waitq, &wait); break; } mutex_unlock(&wl->mutex); schedule(); finish_wait(&wl->fwlog_waitq, &wait); if (signal_pending(current)) return -ERESTARTSYS; ret = mutex_lock_interruptible(&wl->mutex); if (ret < 0) return -ERESTARTSYS; } /* Check if the fwlog is still valid */ if (wl->fwlog_size < 0) { mutex_unlock(&wl->mutex); return 0; } /* Seeking is not supported - old logs are not kept. Disregard pos. */ len = min(count, (size_t)wl->fwlog_size); wl->fwlog_size -= len; memcpy(buffer, wl->fwlog, len); /* Make room for new messages */ memmove(wl->fwlog, wl->fwlog + len, wl->fwlog_size); mutex_unlock(&wl->mutex); return len; } static struct bin_attribute fwlog_attr = { .attr = {.name = "fwlog", .mode = S_IRUSR}, .read = wl1271_sysfs_read_fwlog, }; static bool wl12xx_mac_in_fuse(struct wl1271 *wl) { bool supported = false; u8 major, minor; if (wl->chip.id == CHIP_ID_1283_PG20) { major = WL128X_PG_GET_MAJOR(wl->hw_pg_ver); minor = WL128X_PG_GET_MINOR(wl->hw_pg_ver); /* in wl128x we have the MAC address if the PG is >= (2, 1) */ if (major > 2 || (major == 2 && minor >= 1)) supported = true; } else { major = WL127X_PG_GET_MAJOR(wl->hw_pg_ver); minor = WL127X_PG_GET_MINOR(wl->hw_pg_ver); /* in wl127x we have the MAC address if the PG is >= (3, 1) */ if (major == 3 && minor >= 1) supported = true; } wl1271_debug(DEBUG_PROBE, "PG Ver major = %d minor = %d, MAC %s present", major, minor, supported ? "is" : "is not"); return supported; } static void wl12xx_derive_mac_addresses(struct wl1271 *wl, u32 oui, u32 nic, int n) { int i; wl1271_debug(DEBUG_PROBE, "base address: oui %06x nic %06x, n %d", oui, nic, n); if (nic + n - 1 > 0xffffff) wl1271_warning("NIC part of the MAC address wraps around!"); for (i = 0; i < n; i++) { wl->addresses[i].addr[0] = (u8)(oui >> 16); wl->addresses[i].addr[1] = (u8)(oui >> 8); wl->addresses[i].addr[2] = (u8) oui; wl->addresses[i].addr[3] = (u8)(nic >> 16); wl->addresses[i].addr[4] = (u8)(nic >> 8); wl->addresses[i].addr[5] = (u8) nic; nic++; } wl->hw->wiphy->n_addresses = n; wl->hw->wiphy->addresses = wl->addresses; } static void wl12xx_get_fuse_mac(struct wl1271 *wl) { u32 mac1, mac2; wl1271_set_partition(wl, &wl12xx_part_table[PART_DRPW]); mac1 = wl1271_read32(wl, WL12XX_REG_FUSE_BD_ADDR_1); mac2 = wl1271_read32(wl, WL12XX_REG_FUSE_BD_ADDR_2); /* these are the two parts of the BD_ADDR */ wl->fuse_oui_addr = ((mac2 & 0xffff) << 8) + ((mac1 & 0xff000000) >> 24); wl->fuse_nic_addr = mac1 & 0xffffff; wl1271_set_partition(wl, &wl12xx_part_table[PART_DOWN]); } static int wl12xx_get_hw_info(struct wl1271 *wl) { int ret; u32 die_info; ret = wl12xx_set_power_on(wl); if (ret < 0) goto out; wl->chip.id = wl1271_read32(wl, CHIP_ID_B); if (wl->chip.id == CHIP_ID_1283_PG20) die_info = wl1271_top_reg_read(wl, WL128X_REG_FUSE_DATA_2_1); else die_info = wl1271_top_reg_read(wl, WL127X_REG_FUSE_DATA_2_1); wl->hw_pg_ver = (s8) (die_info & PG_VER_MASK) >> PG_VER_OFFSET; if (!wl12xx_mac_in_fuse(wl)) { wl->fuse_oui_addr = 0; wl->fuse_nic_addr = 0; } else { wl12xx_get_fuse_mac(wl); } wl1271_power_off(wl); out: return ret; } static int wl1271_register_hw(struct wl1271 *wl) { int ret; u32 oui_addr = 0, nic_addr = 0; if (wl->mac80211_registered) return 0; ret = wl12xx_get_hw_info(wl); if (ret < 0) { wl1271_error("couldn't get hw info"); goto out; } ret = wl1271_fetch_nvs(wl); if (ret == 0) { /* NOTE: The wl->nvs->nvs element must be first, in * order to simplify the casting, we assume it is at * the beginning of the wl->nvs structure. */ u8 *nvs_ptr = (u8 *)wl->nvs; oui_addr = (nvs_ptr[11] << 16) + (nvs_ptr[10] << 8) + nvs_ptr[6]; nic_addr = (nvs_ptr[5] << 16) + (nvs_ptr[4] << 8) + nvs_ptr[3]; } /* if the MAC address is zeroed in the NVS derive from fuse */ if (oui_addr == 0 && nic_addr == 0) { oui_addr = wl->fuse_oui_addr; /* fuse has the BD_ADDR, the WLAN addresses are the next two */ nic_addr = wl->fuse_nic_addr + 1; } wl12xx_derive_mac_addresses(wl, oui_addr, nic_addr, 2); ret = ieee80211_register_hw(wl->hw); if (ret < 0) { wl1271_error("unable to register mac80211 hw: %d", ret); goto out; } wl->mac80211_registered = true; wl1271_debugfs_init(wl); wl1271_notice("loaded"); out: return ret; } static void wl1271_unregister_hw(struct wl1271 *wl) { if (wl->plt) wl1271_plt_stop(wl); ieee80211_unregister_hw(wl->hw); wl->mac80211_registered = false; } static int wl1271_init_ieee80211(struct wl1271 *wl) { static const u32 cipher_suites[] = { WLAN_CIPHER_SUITE_WEP40, WLAN_CIPHER_SUITE_WEP104, WLAN_CIPHER_SUITE_TKIP, WLAN_CIPHER_SUITE_CCMP, WL1271_CIPHER_SUITE_GEM, }; /* The tx descriptor buffer and the TKIP space. */ wl->hw->extra_tx_headroom = WL1271_EXTRA_SPACE_TKIP + sizeof(struct wl1271_tx_hw_descr); /* unit us */ /* FIXME: find a proper value */ wl->hw->channel_change_time = 10000; wl->hw->max_listen_interval = wl->conf.conn.max_listen_interval; wl->hw->flags = IEEE80211_HW_SIGNAL_DBM | IEEE80211_HW_SUPPORTS_PS | IEEE80211_HW_SUPPORTS_DYNAMIC_PS | IEEE80211_HW_SUPPORTS_UAPSD | IEEE80211_HW_HAS_RATE_CONTROL | IEEE80211_HW_CONNECTION_MONITOR | IEEE80211_HW_REPORTS_TX_ACK_STATUS | IEEE80211_HW_SPECTRUM_MGMT | IEEE80211_HW_AP_LINK_PS | IEEE80211_HW_AMPDU_AGGREGATION | IEEE80211_HW_TX_AMPDU_SETUP_IN_HW | IEEE80211_HW_SCAN_WHILE_IDLE; wl->hw->wiphy->cipher_suites = cipher_suites; wl->hw->wiphy->n_cipher_suites = ARRAY_SIZE(cipher_suites); wl->hw->wiphy->interface_modes = BIT(NL80211_IFTYPE_STATION) | BIT(NL80211_IFTYPE_ADHOC) | BIT(NL80211_IFTYPE_AP) | BIT(NL80211_IFTYPE_P2P_CLIENT) | BIT(NL80211_IFTYPE_P2P_GO); wl->hw->wiphy->max_scan_ssids = 1; wl->hw->wiphy->max_sched_scan_ssids = 16; wl->hw->wiphy->max_match_sets = 16; /* * Maximum length of elements in scanning probe request templates * should be the maximum length possible for a template, without * the IEEE80211 header of the template */ wl->hw->wiphy->max_scan_ie_len = WL1271_CMD_TEMPL_MAX_SIZE - sizeof(struct ieee80211_header); wl->hw->wiphy->max_sched_scan_ie_len = WL1271_CMD_TEMPL_MAX_SIZE - sizeof(struct ieee80211_header); wl->hw->wiphy->flags |= WIPHY_FLAG_AP_UAPSD; /* make sure all our channels fit in the scanned_ch bitmask */ BUILD_BUG_ON(ARRAY_SIZE(wl1271_channels) + ARRAY_SIZE(wl1271_channels_5ghz) > WL1271_MAX_CHANNELS); /* * We keep local copies of the band structs because we need to * modify them on a per-device basis. */ memcpy(&wl->bands[IEEE80211_BAND_2GHZ], &wl1271_band_2ghz, sizeof(wl1271_band_2ghz)); memcpy(&wl->bands[IEEE80211_BAND_5GHZ], &wl1271_band_5ghz, sizeof(wl1271_band_5ghz)); wl->hw->wiphy->bands[IEEE80211_BAND_2GHZ] = &wl->bands[IEEE80211_BAND_2GHZ]; wl->hw->wiphy->bands[IEEE80211_BAND_5GHZ] = &wl->bands[IEEE80211_BAND_5GHZ]; wl->hw->queues = 4; wl->hw->max_rates = 1; wl->hw->wiphy->reg_notifier = wl1271_reg_notify; /* the FW answers probe-requests in AP-mode */ wl->hw->wiphy->flags |= WIPHY_FLAG_AP_PROBE_RESP_OFFLOAD; wl->hw->wiphy->probe_resp_offload = NL80211_PROBE_RESP_OFFLOAD_SUPPORT_WPS | NL80211_PROBE_RESP_OFFLOAD_SUPPORT_WPS2 | NL80211_PROBE_RESP_OFFLOAD_SUPPORT_P2P; SET_IEEE80211_DEV(wl->hw, wl->dev); wl->hw->sta_data_size = sizeof(struct wl1271_station); wl->hw->vif_data_size = sizeof(struct wl12xx_vif); wl->hw->max_rx_aggregation_subframes = 8; return 0; } #define WL1271_DEFAULT_CHANNEL 0 static struct ieee80211_hw *wl1271_alloc_hw(void) { struct ieee80211_hw *hw; struct wl1271 *wl; int i, j, ret; unsigned int order; BUILD_BUG_ON(AP_MAX_STATIONS > WL12XX_MAX_LINKS); hw = ieee80211_alloc_hw(sizeof(*wl), &wl1271_ops); if (!hw) { wl1271_error("could not alloc ieee80211_hw"); ret = -ENOMEM; goto err_hw_alloc; } wl = hw->priv; memset(wl, 0, sizeof(*wl)); INIT_LIST_HEAD(&wl->wlvif_list); wl->hw = hw; for (i = 0; i < NUM_TX_QUEUES; i++) for (j = 0; j < WL12XX_MAX_LINKS; j++) skb_queue_head_init(&wl->links[j].tx_queue[i]); skb_queue_head_init(&wl->deferred_rx_queue); skb_queue_head_init(&wl->deferred_tx_queue); INIT_DELAYED_WORK(&wl->elp_work, wl1271_elp_work); INIT_WORK(&wl->netstack_work, wl1271_netstack_work); INIT_WORK(&wl->tx_work, wl1271_tx_work); INIT_WORK(&wl->recovery_work, wl1271_recovery_work); INIT_DELAYED_WORK(&wl->scan_complete_work, wl1271_scan_complete_work); INIT_DELAYED_WORK(&wl->tx_watchdog_work, wl12xx_tx_watchdog_work); wl->freezable_wq = create_freezable_workqueue("wl12xx_wq"); if (!wl->freezable_wq) { ret = -ENOMEM; goto err_hw; } wl->channel = WL1271_DEFAULT_CHANNEL; wl->rx_counter = 0; wl->power_level = WL1271_DEFAULT_POWER_LEVEL; wl->band = IEEE80211_BAND_2GHZ; wl->flags = 0; wl->sg_enabled = true; wl->hw_pg_ver = -1; wl->ap_ps_map = 0; wl->ap_fw_ps_map = 0; wl->quirks = 0; wl->platform_quirks = 0; wl->sched_scanning = false; wl->tx_spare_blocks = TX_HW_BLOCK_SPARE_DEFAULT; wl->system_hlid = WL12XX_SYSTEM_HLID; wl->active_sta_count = 0; wl->fwlog_size = 0; init_waitqueue_head(&wl->fwlog_waitq); /* The system link is always allocated */ __set_bit(WL12XX_SYSTEM_HLID, wl->links_map); memset(wl->tx_frames_map, 0, sizeof(wl->tx_frames_map)); for (i = 0; i < ACX_TX_DESCRIPTORS; i++) wl->tx_frames[i] = NULL; spin_lock_init(&wl->wl_lock); wl->state = WL1271_STATE_OFF; wl->fw_type = WL12XX_FW_TYPE_NONE; mutex_init(&wl->mutex); /* Apply default driver configuration. */ wl1271_conf_init(wl); order = get_order(WL1271_AGGR_BUFFER_SIZE); wl->aggr_buf = (u8 *)__get_free_pages(GFP_KERNEL, order); if (!wl->aggr_buf) { ret = -ENOMEM; goto err_wq; } wl->dummy_packet = wl12xx_alloc_dummy_packet(wl); if (!wl->dummy_packet) { ret = -ENOMEM; goto err_aggr; } /* Allocate one page for the FW log */ wl->fwlog = (u8 *)get_zeroed_page(GFP_KERNEL); if (!wl->fwlog) { ret = -ENOMEM; goto err_dummy_packet; } return hw; err_dummy_packet: dev_kfree_skb(wl->dummy_packet); err_aggr: free_pages((unsigned long)wl->aggr_buf, order); err_wq: destroy_workqueue(wl->freezable_wq); err_hw: wl1271_debugfs_exit(wl); ieee80211_free_hw(hw); err_hw_alloc: return ERR_PTR(ret); } static int wl1271_free_hw(struct wl1271 *wl) { /* Unblock any fwlog readers */ mutex_lock(&wl->mutex); wl->fwlog_size = -1; wake_up_interruptible_all(&wl->fwlog_waitq); mutex_unlock(&wl->mutex); device_remove_bin_file(wl->dev, &fwlog_attr); device_remove_file(wl->dev, &dev_attr_hw_pg_ver); device_remove_file(wl->dev, &dev_attr_bt_coex_state); free_page((unsigned long)wl->fwlog); dev_kfree_skb(wl->dummy_packet); free_pages((unsigned long)wl->aggr_buf, get_order(WL1271_AGGR_BUFFER_SIZE)); wl1271_debugfs_exit(wl); vfree(wl->fw); wl->fw = NULL; wl->fw_type = WL12XX_FW_TYPE_NONE; kfree(wl->nvs); wl->nvs = NULL; kfree(wl->fw_status); kfree(wl->tx_res_if); destroy_workqueue(wl->freezable_wq); ieee80211_free_hw(wl->hw); return 0; } static irqreturn_t wl12xx_hardirq(int irq, void *cookie) { struct wl1271 *wl = cookie; unsigned long flags; wl1271_debug(DEBUG_IRQ, "IRQ"); /* complete the ELP completion */ spin_lock_irqsave(&wl->wl_lock, flags); set_bit(WL1271_FLAG_IRQ_RUNNING, &wl->flags); if (wl->elp_compl) { complete(wl->elp_compl); wl->elp_compl = NULL; } if (test_bit(WL1271_FLAG_SUSPENDED, &wl->flags)) { /* don't enqueue a work right now. mark it as pending */ set_bit(WL1271_FLAG_PENDING_WORK, &wl->flags); wl1271_debug(DEBUG_IRQ, "should not enqueue work"); disable_irq_nosync(wl->irq); pm_wakeup_event(wl->dev, 0); spin_unlock_irqrestore(&wl->wl_lock, flags); return IRQ_HANDLED; } spin_unlock_irqrestore(&wl->wl_lock, flags); return IRQ_WAKE_THREAD; } static int __devinit wl12xx_probe(struct platform_device *pdev) { struct wl12xx_platform_data *pdata = pdev->dev.platform_data; struct ieee80211_hw *hw; struct wl1271 *wl; unsigned long irqflags; int ret = -ENODEV; hw = wl1271_alloc_hw(); if (IS_ERR(hw)) { wl1271_error("can't allocate hw"); ret = PTR_ERR(hw); goto out; } wl = hw->priv; wl->irq = platform_get_irq(pdev, 0); wl->ref_clock = pdata->board_ref_clock; wl->tcxo_clock = pdata->board_tcxo_clock; wl->platform_quirks = pdata->platform_quirks; wl->set_power = pdata->set_power; wl->dev = &pdev->dev; wl->if_ops = pdata->ops; platform_set_drvdata(pdev, wl); #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,32) irqflags = IRQF_TRIGGER_RISING; #else if (wl->platform_quirks & WL12XX_PLATFORM_QUIRK_EDGE_IRQ) irqflags = IRQF_TRIGGER_RISING; else irqflags = IRQF_TRIGGER_HIGH | IRQF_ONESHOT; #endif #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,31) ret = compat_request_threaded_irq(&wl->irq_compat, wl->irq, wl12xx_hardirq, wl1271_irq, irqflags, pdev->name, wl); #else ret = request_threaded_irq(wl->irq, wl12xx_hardirq, wl1271_irq, irqflags, pdev->name, wl); #endif if (ret < 0) { wl1271_error("request_irq() failed: %d", ret); goto out_free_hw; } ret = enable_irq_wake(wl->irq); if (!ret) { wl->irq_wake_enabled = true; device_init_wakeup(wl->dev, 1); if (pdata->pwr_in_suspend) hw->wiphy->wowlan.flags = WIPHY_WOWLAN_ANY; } disable_irq(wl->irq); ret = wl1271_init_ieee80211(wl); if (ret) goto out_irq; ret = wl1271_register_hw(wl); if (ret) goto out_irq; /* Create sysfs file to control bt coex state */ ret = device_create_file(wl->dev, &dev_attr_bt_coex_state); if (ret < 0) { wl1271_error("failed to create sysfs file bt_coex_state"); goto out_irq; } /* Create sysfs file to get HW PG version */ ret = device_create_file(wl->dev, &dev_attr_hw_pg_ver); if (ret < 0) { wl1271_error("failed to create sysfs file hw_pg_ver"); goto out_bt_coex_state; } /* Create sysfs file for the FW log */ ret = device_create_bin_file(wl->dev, &fwlog_attr); if (ret < 0) { wl1271_error("failed to create sysfs file fwlog"); goto out_hw_pg_ver; } return 0; out_hw_pg_ver: device_remove_file(wl->dev, &dev_attr_hw_pg_ver); out_bt_coex_state: device_remove_file(wl->dev, &dev_attr_bt_coex_state); out_irq: #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,31) compat_free_threaded_irq(&wl->irq_compat); #else free_irq(wl->irq, wl); #endif out_free_hw: wl1271_free_hw(wl); out: return ret; } static int __devexit wl12xx_remove(struct platform_device *pdev) { struct wl1271 *wl = platform_get_drvdata(pdev); if (wl->irq_wake_enabled) { device_init_wakeup(wl->dev, 0); disable_irq_wake(wl->irq); } wl1271_unregister_hw(wl); #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,31) compat_free_threaded_irq(&wl->irq_compat); compat_destroy_threaded_irq(&wl->irq_compat); #else free_irq(wl->irq, wl); #endif wl1271_free_hw(wl); return 0; } #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,30) static const struct platform_device_id wl12xx_id_table[] __devinitconst = { { "wl12xx", 0 }, { } /* Terminating Entry */ }; MODULE_DEVICE_TABLE(platform, wl12xx_id_table); #endif static struct platform_driver wl12xx_driver = { .probe = wl12xx_probe, .remove = __devexit_p(wl12xx_remove), #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,30) .id_table = wl12xx_id_table, #endif .driver = { .name = "wl12xx_driver", .owner = THIS_MODULE, } }; static int __init wl12xx_init(void) { return platform_driver_register(&wl12xx_driver); } module_init(wl12xx_init); static void __exit wl12xx_exit(void) { platform_driver_unregister(&wl12xx_driver); } module_exit(wl12xx_exit); u32 wl12xx_debug_level = DEBUG_NONE; EXPORT_SYMBOL_GPL(wl12xx_debug_level); module_param_named(debug_level, wl12xx_debug_level, uint, S_IRUSR | S_IWUSR); MODULE_PARM_DESC(debug_level, "wl12xx debugging level"); module_param_named(fwlog, fwlog_param, charp, 0); MODULE_PARM_DESC(fwlog, "FW logger options: continuous, ondemand, dbgpins or disable"); module_param(bug_on_recovery, bool, S_IRUSR | S_IWUSR); MODULE_PARM_DESC(bug_on_recovery, "BUG() on fw recovery"); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Luciano Coelho <coelho@ti.com>"); MODULE_AUTHOR("Juuso Oikarinen <juuso.oikarinen@nokia.com>");
TouchpadCM/compat-wireless-3.4-rc3-1
drivers/net/wireless/wl12xx/main.c
C
gpl-2.0
147,286
/* * CDE - Common Desktop Environment * * Copyright (c) 1993-2012, The Open Group. All rights reserved. * * These libraries and programs are free software; you can * redistribute them and/or modify them under the terms of the GNU * Lesser General Public License as published by the Free Software * Foundation; either version 2 of the License, or (at your option) * any later version. * * These libraries and programs are distributed in the hope that * they 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 these librararies and programs; if not, write * to the Free Software Foundation, Inc., 51 Franklin Street, Fifth * Floor, Boston, MA 02110-1301 USA */ /* * File: Symbolic.c $XConsortium: Symbolic.c /main/5 1996/09/27 19:00:23 drk $ * Language: C * * (c) Copyright 1988, Hewlett-Packard Company, all rights reserved. * * (c) Copyright 1993, 1994 Hewlett-Packard Company * * (c) Copyright 1993, 1994 International Business Machines Corp. * * (c) Copyright 1993, 1994 Sun Microsystems, Inc. * * (c) Copyright 1993, 1994 Novell, Inc. * */ #ifdef __osf__ #define SBSTDINC_H_NO_REDEFINE #endif #include <Dt/UserMsg.h> #include <bms/sbport.h> /* NOTE: sbport.h must be the first include. */ #include <assert.h> #include <bms/bms.h> #include <bms/XeUserMsg.h> #include <bms/MemoryMgr.h> #include <bms/Symbolic.h> #include <codelibs/stringx.h> /* strhash */ #include "DtSvcLock.h" /******************************************************************************/ /* HASHING */ /* This is the default symbol table to use */ /* --------------------------------------- */ #define XE_END_OF_HASH_TABLE (XeSymtabList) -1 static XeSymTable D_sym_table = NULL; typedef struct _unknown_entry_data { XeString name; } *unknown_entry_data; /******************************************************************************/ /* Symbol (hash) Table */ /*------------------------------------------------------------------------+*/ static unsigned int keyhash(XeSymTable t, void *key) /*------------------------------------------------------------------------+*/ { unsigned int hash; if (t->hash_fn) { hash = t->hash_fn( key, t->hashsize ); if (hash >= t->hashsize) _DtSimpleError(XeProgName, XeInternalError, NULL, (XeString) "Symbolic.c: Hash value from user hash function out of range", NULL); /* We don't come back from the error routine */ } else { hash = strhash( (const char *) key ); hash = hash & (t->hashsize - 1); } return hash; } /*------------------------------------------------------------------------+*/ static unsigned int trap_bad_hash_fn(void * UNUSED_PARM(ptr), unsigned int UNUSED_PARM(size)) /*------------------------------------------------------------------------+*/ { _DtSimpleError(XeProgName, XeInternalError, NULL, (XeString) "Symbolic.c: Hash table at must be power of 2", NULL); /* We don't come back from the error routine */ return 1; } /*------------------------------------------------------------------------+*/ XeSymTable Xe_new_symtab(unsigned int hashsize) /*------------------------------------------------------------------------+*/ /* Note, hashsize must be power of 2 if using default hash function */ { int i; XeSymTable t = (XeSymTable) XeMalloc( sizeof (struct _XeSymTable) ); t->hashsize = hashsize; t->list = (XeSymtabList *)XeMalloc( sizeof( XeSymtabList ) * hashsize ); for (i = 0; i < hashsize; i++) t->list[i] = (XeSymtabList)NULL; t->curr_list = XE_END_OF_HASH_TABLE; t->curr_hash = 0; Xe_set_sym_fns(t, (XeSymFn_cmp)NULL, (XeSymFn_init)NULL, (XeSymFn_clean)NULL, (XeSymFn_hash)NULL); /* If not a power of two, user better have a hash function */ /* that handles that. Install hash function trap so that if */ /* he does not install one, we catch it. */ /* --------------------------------------------------------- */ if (hashsize & (hashsize - 1)) t->hash_fn = trap_bad_hash_fn; return t; } /*------------------------------------------------------------------------+*/ XeSymTable Xe_default_symtab(void) /*------------------------------------------------------------------------+*/ { #define D_HASHSIZE 256 _DtSvcProcessLock(); if (D_sym_table) { _DtSvcProcessUnlock(); return D_sym_table; } D_sym_table = Xe_new_symtab(D_HASHSIZE); _DtSvcProcessUnlock(); return(D_sym_table); } /*------------------------------------------------------------------------+*/ static XeSymtabList NukeOneItem(XeSymTable t, XeSymtabList l) /*------------------------------------------------------------------------+*/ { XeSymtabList next; /* For standard XeSymbols: */ /* 1) Free the name */ /* 2) Call free function if configured */ /* 3) Free the XeSymbol entry */ /* ---------------------------------------- */ if (l->data_is_XeSymbol) { XeFree( ((XeSymbol)l->data)->name ); if (t->clean_fn) t->clean_fn( ((XeSymbol)l->data)->value ); XeFree( l->data ); } /* For "anysym" symbols: */ /* 1) Call free function if configured */ /* 2) If we malloced the data, free it */ /* ---------------------------------------- */ else { if (t->clean_fn) t->clean_fn( l->data ); if (l->data_is_malloc_mem) XeFree(l->data); } next = l->rest; XeFree(l); return next; } /*------------------------------------------------------------------------+*/ XeSymTable Xe_set_sym_fns(XeSymTable t, XeSymFn_cmp cmp_fn, XeSymFn_init init_fn, XeSymFn_clean clean_fn, XeSymFn_hash hash_fn) /*------------------------------------------------------------------------+*/ { if (!t) t = Xe_default_symtab(); t->cmp_fn = cmp_fn; t->init_fn = init_fn; t->clean_fn = clean_fn; t->hash_fn = hash_fn; return(t); } /*------------------------------------------------------------------------+*/ static XeSymbol make_sym(XeString name) /*------------------------------------------------------------------------+*/ { XeSymbol sym = Xe_make_struct(_XeSymbol); sym->name = strdup( name ); sym->value = (void*)NULL; return sym; } /*------------------------------------------------------------------------+*/ static void * intern_something(XeSymTable t, void * data, unsigned int size, Boolean is_XeSymbol, Boolean lookup_only, int *bucket) /*------------------------------------------------------------------------+*/ { unsigned int hash; XeSymtabList l; XeSymtabList l0; Boolean match; void * hash_key; /* If no cmp function assume first item of "data" is a string pointer */ /* ------------------------------------------------------------------ */ if (is_XeSymbol) hash_key = data; else hash_key = (t->hash_fn) ? data : ((unknown_entry_data) data)->name; hash = keyhash( t, hash_key ); l = t->list[hash]; if (bucket) *bucket = hash; for (l0 = NULL; l; l0 = l, l = l->rest) { void * cmp_key; void * cmp_key2; if (is_XeSymbol) cmp_key = data; else cmp_key = (t->cmp_fn) ? data : ((unknown_entry_data) data)->name; if (l->data_is_XeSymbol) cmp_key2 = ((XeSymbol) l->data)->name; else cmp_key2 = (t->cmp_fn) ? l->data : ((unknown_entry_data) l->data)->name; /* Use the "compare" function to see if we have a match on our key */ /* --------------------------------------------------------------- */ if (t->cmp_fn) match = (t->cmp_fn( cmp_key, cmp_key2 ) == 0); else match = (strcmp((const char *) cmp_key, (const char *)cmp_key2 ) == 0); if (match) return l->data; } /* If just doing a lookup, don't add a new symbol */ /* ---------------------------------------------- */ if (lookup_only) return (void *) NULL; /* There was no match. We need to create an entry in the hash table. */ /* ------------------------------------------------------------------ */ l = (XeSymtabList) XeMalloc( sizeof(struct _XeSymtabList) ); l->rest = (XeSymtabList)NULL; l->data_is_XeSymbol = is_XeSymbol; l->data_is_malloc_mem = FALSE; if (l0) l0->rest = l; else t->list[hash] = l; /* If we have a standard symbol, make the XeSymbol entry. */ /* -------------------------------------------------------- */ if (is_XeSymbol) { XeSymbol sym = make_sym((XeString)data); l->data = (void*) sym; if (t->init_fn) sym->value = t->init_fn( l->data, size /* will be 0 */ ); } else { /* 1) If "size" != 0, */ /* - malloc "size" bytes, */ /* - copy "data" into malloced space, */ /* - Save pointer to malloc space as user's data pointer */ /* Else */ /* - Save "data" as pointer to user's data */ /* 2) If a "init_fn" is configured, */ /* - call init_fn( user's data pointer, "size" ) */ /* - set user's data pointer to return value of init_fn */ /* ONLY if "size" was zero. */ /* */ /* If size is non zero AND there is a user's malloc function, */ /* beware that the return value from the malloc function is not*/ /* save anywhere by these routines. If size was zero, the */ /* return value of the user's function is kept. */ /* ------------------------------------------------------------------ */ if (size) { l->data = XeMalloc( size ); memcpy(l->data, data, size); l->data_is_malloc_mem = TRUE; } else l->data = data; if (t->init_fn) { void * new_data = t->init_fn( l->data, size ); if (!size) l->data = new_data; } } /* appended to the end of the hash chain (if any). */ /* --------------------------------------------------------------- */ t->curr_list = l; t->curr_hash = hash; #ifdef DEBUG printf("Added data %p in list[%d] @ %p\n", l->data, hash, l); #endif return l->data; } /*------------------------------------------------------------------------+*/ XeSymbol Xe_intern(XeSymTable t, ConstXeString const name) /*------------------------------------------------------------------------+*/ { if (!name) return (XeSymbol)NULL; if (!t) t = Xe_default_symtab(); return (XeSymbol)intern_something(t, (void *)name, 0, TRUE, FALSE, (int*)NULL); } /*------------------------------------------------------------------------+*/ XeSymbol Xe_lookup(XeSymTable t, ConstXeString const name) /*------------------------------------------------------------------------+*/ { if (!name) return (XeSymbol)NULL; if (!t) t = Xe_default_symtab(); return (XeSymbol)intern_something(t, (void *)name, 0, TRUE, TRUE, (int*)NULL); } /******************************************************************************/ /* LISTS */ /*------------------------------------------------------------------------+*/ XeList Xe_make_list(void * data, XeList rest) /*------------------------------------------------------------------------+*/ { XeList temp = Xe_make_struct(_XeList); temp->data = data; temp->rest = rest; return temp; } /******************************************************************************/ /* QUEUES */ /*------------------------------------------------------------------------+*/ XeQueue Xe_init_queue(XeQueue q, void * nullval) /*------------------------------------------------------------------------+*/ { q->head = 0; q->null = nullval; return q; } /*------------------------------------------------------------------------+*/ XeQueue Xe_make_queue(void * nullval) /*------------------------------------------------------------------------+*/ { return Xe_init_queue(Xe_make_struct(_XeQueue), nullval); } /*------------------------------------------------------------------------+*/ void * Xe_pop_queue(XeQueue q) /*------------------------------------------------------------------------+*/ { XeList head = q->head; if (head) { void * val = head->data; q->head = head->rest; XeFree(head); return val; } else return q->null; } /*------------------------------------------------------------------------+*/ void * Xe_delete_queue_element(XeQueue q, void * val) /*------------------------------------------------------------------------+*/ { XeList last = 0, head = q->head; while (head) if (head->data == val) { if (last) last->rest = head->rest; else q->head = head->rest; if (q->tail == head) q->tail = last; XeFree(head); return val; } else last = head, head = head->rest; return q->null; } /*------------------------------------------------------------------------+*/ void Xe_push_queue(XeQueue q, void * val) /*------------------------------------------------------------------------+*/ { XeList new_ptr = Xe_make_list(val, 0); if (q->head) q->tail->rest = new_ptr; else q->head = new_ptr; q->tail = new_ptr; } /*------------------------------------------------------------------------+*/ void Xe_release_queue(XeQueue q) /*------------------------------------------------------------------------+*/ { if (q) { while (q->head) Xe_pop_queue(q); XeFree(q); } }
sTeeLM/MINIME
toolkit/srpm/SOURCES/cde-2.2.4/lib/DtSvc/DtEncap/Symbolic.c
C
gpl-2.0
14,105
/* * Copyright (C) 2011-2014 MediaTek Inc. * * 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. * * This program 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 this program. * If not, see <http://www.gnu.org/licenses/>. */ /* ** Id: //Department/DaVinci/BRANCHES/MT6620_WIFI_DRIVER_V2_3/os/linux/gl_init.c#7 */ /*! \file gl_init.c \brief Main routines of Linux driver This file contains the main routines of Linux driver for MediaTek Inc. 802.11 Wireless LAN Adapters. */ /* ** Log: gl_init.c ** ** 09 03 2013 cp.wu ** add path for reassociation * * 07 17 2012 yuche.tsai * NULL * Fix compile error. * * 07 17 2012 yuche.tsai * NULL * Fix compile error for JB. * * 07 17 2012 yuche.tsai * NULL * Let netdev bring up. * * 07 17 2012 yuche.tsai * NULL * Compile no error before trial run. * * 06 13 2012 yuche.tsai * NULL * Update maintrunk driver. * Add support for driver compose assoc request frame. * * 05 25 2012 yuche.tsai * NULL * Fix reset KE issue. * * 05 11 2012 cp.wu * [WCXRP00001237] [MT6620 Wi-Fi][Driver] Show MAC address and MAC address source for ACS's convenience * show MAC address & source while initiliazation * * 03 02 2012 terry.wu * NULL * EXPORT_SYMBOL(rsnParseCheckForWFAInfoElem);. * * 03 02 2012 terry.wu * NULL * Snc CFG80211 modification for ICS migration from branch 2.2. * * 03 02 2012 terry.wu * NULL * Sync CFG80211 modification from branch 2,2. * * 03 02 2012 terry.wu * NULL * Enable CFG80211 Support. * * 12 22 2011 george.huang * [WCXRP00000905] [MT6628 Wi-Fi][FW] Code refinement for ROM/ RAM module dependency * using global variable instead of stack for setting wlanoidSetNetworkAddress(), due to buffer may be released before * TX thread handling * * 11 18 2011 yuche.tsai * NULL * CONFIG P2P support RSSI query, default turned off. * * 11 14 2011 yuche.tsai * [WCXRP00001107] [Volunteer Patch][Driver] Large Network Type index assert in FW issue. * Fix large network type index assert in FW issue. * * 11 14 2011 cm.chang * NULL * Fix compiling warning * * 11 11 2011 yuche.tsai * NULL * Fix work thread cancel issue. * * 11 10 2011 cp.wu * [WCXRP00001098] [MT6620 Wi-Fi][Driver] Replace printk by DBG LOG macros in linux porting layer * 1. eliminaite direct calls to printk in porting layer. * 2. replaced by DBGLOG, which would be XLOG on ALPS platforms. * * 10 06 2011 eddie.chen * [WCXRP00001027] [MT6628 Wi-Fi][Firmware/Driver] Tx fragmentation * Add rlmDomainGetChnlList symbol. * * 09 22 2011 cm.chang * NULL * Safer writng stype to avoid unitialized regitry structure * * 09 21 2011 cm.chang * [WCXRP00000969] [MT6620 Wi-Fi][Driver][FW] Channel list for 5G band based on country code * Avoid possible structure alignment problem * * 09 20 2011 chinglan.wang * [WCXRP00000989] [WiFi Direct] [Driver] Add a new io control API to start the formation for the sigma test. * . * * 09 08 2011 cm.chang * [WCXRP00000969] [MT6620 Wi-Fi][Driver][FW] Channel list for 5G band based on country code * Use new fields ucChannelListMap and ucChannelListIndex in NVRAM * * 08 31 2011 cm.chang * [WCXRP00000969] [MT6620 Wi-Fi][Driver][FW] Channel list for 5G band based on country code * . * * 08 11 2011 cp.wu * [WCXRP00000830] [MT6620 Wi-Fi][Firmware] Use MDRDY counter to detect empty channel for shortening scan time * expose scnQuerySparseChannel() for P2P-FSM. * * 08 11 2011 cp.wu * [WCXRP00000830] [MT6620 Wi-Fi][Firmware] Use MDRDY counter to detect empty channel for shortening scan time * sparse channel detection: * driver: collect sparse channel information with scan-done event * * 08 02 2011 yuche.tsai * [WCXRP00000896] [Volunteer Patch][WiFi Direct][Driver] GO with multiple client, TX deauth to a disconnecting * device issue. * Fix GO send deauth frame issue. * * 07 07 2011 wh.su * [WCXRP00000839] [MT6620 Wi-Fi][Driver] Add the dumpMemory8 and dumpMemory32 EXPORT_SYMBOL * Add the dumpMemory8 symbol export for debug mode. * * 07 06 2011 terry.wu * [WCXRP00000735] [MT6620 Wi-Fi][BoW][FW/Driver] Protect BoW connection establishment * Improve BoW connection establishment speed. * * 07 05 2011 yuche.tsai * [WCXRP00000821] [Volunteer Patch][WiFi Direct][Driver] WiFi Direct Connection Speed Issue * Export one symbol for enhancement. * * 06 13 2011 eddie.chen * [WCXRP00000779] [MT6620 Wi-Fi][DRV] Add tx rx statistics in linux and use netif_rx_ni * Add tx rx statistics and netif_rx_ni. * * 05 27 2011 cp.wu * [WCXRP00000749] [MT6620 Wi-Fi][Driver] Add band edge tx power control to Wi-Fi NVRAM * invoke CMD_ID_SET_EDGE_TXPWR_LIMIT when there is valid data exist in NVRAM content. * * 05 18 2011 cp.wu * [WCXRP00000734] [MT6620 Wi-Fi][Driver] Pass PHY_PARAM in NVRAM to firmware domain * pass PHY_PARAM in NVRAM from driver to firmware. * * 05 09 2011 jeffrey.chang * [WCXRP00000710] [MT6620 Wi-Fi] Support pattern filter update function on IP address change * support ARP filter through kernel notifier * * 05 03 2011 chinghwa.yu * [WCXRP00000065] Update BoW design and settings * Use kalMemAlloc to allocate event buffer for kalIndicateBOWEvent. * * 04 27 2011 george.huang * [WCXRP00000684] [MT6620 Wi-Fi][Driver] Support P2P setting ARP filter * Support P2P ARP filter setting on early suspend/ late resume * * 04 18 2011 terry.wu * [WCXRP00000660] [MT6620 Wi-Fi][Driver] Remove flag CFG_WIFI_DIRECT_MOVED * Remove flag CFG_WIFI_DIRECT_MOVED. * * 04 15 2011 chinghwa.yu * [WCXRP00000065] Update BoW design and settings * Add BOW short range mode. * * 04 14 2011 yuche.tsai * [WCXRP00000646] [Volunteer Patch][MT6620][FW/Driver] Sigma Test Modification for some test case. * Modify some driver connection flow or behavior to pass Sigma test more easier.. * * 04 12 2011 cm.chang * [WCXRP00000634] [MT6620 Wi-Fi][Driver][FW] 2nd BSS will not support 40MHz bandwidth for concurrency * . * * 04 11 2011 george.huang * [WCXRP00000621] [MT6620 Wi-Fi][Driver] Support P2P supplicant to set power mode * export wlan functions to p2p * * 04 08 2011 pat.lu * [WCXRP00000623] [MT6620 Wi-Fi][Driver] use ARCH define to distinguish PC Linux driver * Use CONFIG_X86 instead of PC_LINUX_DRIVER_USE option to have proper compile setting for PC Linux driver * * 04 08 2011 cp.wu * [WCXRP00000540] [MT5931][Driver] Add eHPI8/eHPI16 support to Linux Glue Layer * glBusFreeIrq() should use the same pvCookie as glBusSetIrq() or request_irq()/free_irq() won't work as a pair. * * 04 08 2011 eddie.chen * [WCXRP00000617] [MT6620 Wi-Fi][DRV/FW] Fix for sigma * Fix for sigma * * 04 06 2011 cp.wu * [WCXRP00000540] [MT5931][Driver] Add eHPI8/eHPI16 support to Linux Glue Layer * 1. do not check for pvData inside wlanNetCreate() due to it is NULL for eHPI port * 2. update perm_addr as well for MAC address * 3. not calling check_mem_region() anymore for eHPI * 4. correct MSC_CS macro for 0-based notation * * 03 29 2011 cp.wu * [WCXRP00000598] [MT6620 Wi-Fi][Driver] Implementation of interface for communicating with user space process for * RESET_START and RESET_END events * fix typo. * * 03 29 2011 cp.wu * [WCXRP00000598] [MT6620 Wi-Fi][Driver] Implementation of interface for communicating with user space process for * RESET_START and RESET_END events * implement kernel-to-userspace communication via generic netlink socket for whole-chip resetting mechanism * * 03 23 2011 cp.wu * [WCXRP00000540] [MT5931][Driver] Add eHPI8/eHPI16 support to Linux Glue Layer * apply multi-queue operation only for linux kernel > 2.6.26 * * 03 22 2011 pat.lu * [WCXRP00000592] [MT6620 Wi-Fi][Driver] Support PC Linux Environment Driver Build * Add a compiler option "PC_LINUX_DRIVER_USE" for building driver in PC Linux environment. * * 03 21 2011 cp.wu * [WCXRP00000540] [MT5931][Driver] Add eHPI8/eHPI16 support to Linux Glue Layer * portability for compatible with linux 2.6.12. * * 03 21 2011 cp.wu * [WCXRP00000540] [MT5931][Driver] Add eHPI8/eHPI16 support to Linux Glue Layer * improve portability for awareness of early version of linux kernel and wireless extension. * * 03 21 2011 cp.wu * [WCXRP00000540] [MT5931][Driver] Add eHPI8/eHPI16 support to Linux Glue Layer * portability improvement * * 03 18 2011 jeffrey.chang * [WCXRP00000512] [MT6620 Wi-Fi][Driver] modify the net device relative functions to support the H/W multiple queue * remove early suspend functions * * 03 17 2011 cp.wu * [WCXRP00000562] [MT6620 Wi-Fi][Driver] I/O buffer pre-allocation to avoid physically continuous memory shortage * after system running for a long period * reverse order to prevent probing racing. * * 03 16 2011 cp.wu * [WCXRP00000562] [MT6620 Wi-Fi][Driver] I/O buffer pre-allocation to avoid physically continuous memory shortage * after system running for a long period * 1. pre-allocate physical continuous buffer while module is being loaded * 2. use pre-allocated physical continuous buffer for TX/RX DMA transfer * * The windows part remained the same as before, but added similar APIs to hide the difference. * * 03 15 2011 jeffrey.chang * [WCXRP00000558] [MT6620 Wi-Fi][MT6620 Wi-Fi][Driver] refine the queue selection algorithm for WMM * refine the queue_select function * * 03 10 2011 cp.wu * [WCXRP00000532] [MT6620 Wi-Fi][Driver] Migrate NVRAM configuration procedures from MT6620 E2 to MT6620 E3 * deprecate configuration used by MT6620 E2 * * 03 10 2011 terry.wu * [WCXRP00000505] [MT6620 Wi-Fi][Driver/FW] WiFi Direct Integration * Remove unnecessary assert and message. * * 03 08 2011 terry.wu * [WCXRP00000505] [MT6620 Wi-Fi][Driver/FW] WiFi Direct Integration * Export nicQmUpdateWmmParms. * * 03 03 2011 jeffrey.chang * [WCXRP00000512] [MT6620 Wi-Fi][Driver] modify the net device relative functions to support the H/W multiple queue * support concurrent network * * 03 03 2011 jeffrey.chang * [WCXRP00000512] [MT6620 Wi-Fi][Driver] modify the net device relative functions to support the H/W multiple queue * modify net device relative functions to support multiple H/W queues * * 02 24 2011 george.huang * [WCXRP00000495] [MT6620 Wi-Fi][FW] Support pattern filter for unwanted ARP frames * Support ARP filter during suspended * * 02 21 2011 cp.wu * [WCXRP00000482] [MT6620 Wi-Fi][Driver] Simplify logic for checking NVRAM existence in driver domain * simplify logic for checking NVRAM existence only once. * * 02 17 2011 terry.wu * [WCXRP00000459] [MT6620 Wi-Fi][Driver] Fix deference null pointer problem in wlanRemove * Fix deference a null pointer problem in wlanRemove. * * 02 16 2011 jeffrey.chang * NULL * fix compilig error * * 02 16 2011 jeffrey.chang * NULL * Add query ipv4 and ipv6 address during early suspend and late resume * * 02 15 2011 jeffrey.chang * NULL * to support early suspend in android * * 02 11 2011 yuche.tsai * [WCXRP00000431] [Volunteer Patch][MT6620][Driver] Add MLME support for deauthentication under AP(Hot-Spot) mode. * Add one more export symbol. * * 02 10 2011 yuche.tsai * [WCXRP00000431] [Volunteer Patch][MT6620][Driver] Add MLME support for deauthentication under AP(Hot-Spot) mode. * Add RX deauthentication & disassociation process under Hot-Spot mode. * * 02 09 2011 terry.wu * [WCXRP00000383] [MT6620 Wi-Fi][Driver] Separate WiFi and P2P driver into two modules * Halt p2p module init and exit until TxThread finished p2p register and unregister. * * 02 08 2011 george.huang * [WCXRP00000422] [MT6620 Wi-Fi][Driver] support query power mode OID handler * Support querying power mode OID. * * 02 08 2011 yuche.tsai * [WCXRP00000421] [Volunteer Patch][MT6620][Driver] Fix incorrect SSID length Issue * Export Deactivation Network. * * 02 01 2011 jeffrey.chang * [WCXRP00000414] KAL Timer is not unregistered when driver not loaded * Unregister the KAL timer during driver unloading * * 01 26 2011 cm.chang * [WCXRP00000395] [MT6620 Wi-Fi][Driver][FW] Search STA_REC with additional net type index argument * Allocate system RAM if fixed message or mgmt buffer is not available * * 01 19 2011 cp.wu * [WCXRP00000371] [MT6620 Wi-Fi][Driver] make linux glue layer portable for Android 2.3.1 with Linux 2.6.35.7 * add compile option to check linux version 2.6.35 for different usage of system API to improve portability * * 01 12 2011 cp.wu * [WCXRP00000357] [MT6620 Wi-Fi][Driver][Bluetooth over Wi-Fi] add another net device interface for BT AMP * implementation of separate BT_OVER_WIFI data path. * * 01 10 2011 cp.wu * [WCXRP00000349] [MT6620 Wi-Fi][Driver] make kalIoctl() of linux port as a thread safe API to avoid potential issues * due to multiple access * use mutex to protect kalIoctl() for thread safe. * * 01 04 2011 cp.wu * [WCXRP00000338] [MT6620 Wi-Fi][Driver] Separate kalMemAlloc into kmalloc and vmalloc implementations to ease * physically continuous memory demands * separate kalMemAlloc() into virtually-continuous and physically-continuous type to ease slab system pressure * * 12 15 2010 cp.wu * [WCXRP00000265] [MT6620 Wi-Fi][Driver] Remove set_mac_address routine from legacy Wi-Fi Android driver * remove set MAC address. MAC address is always loaded from NVRAM instead. * * 12 10 2010 kevin.huang * [WCXRP00000128] [MT6620 Wi-Fi][Driver] Add proc support to Android Driver for debug and driver status check * Add Linux Proc Support * * 11 01 2010 yarco.yang * [WCXRP00000149] [MT6620 WI-Fi][Driver]Fine tune performance on MT6516 platform * Add GPIO debug function * * 11 01 2010 cp.wu * [WCXRP00000056] [MT6620 Wi-Fi][Driver] NVRAM implementation with Version Check[WCXRP00000150] [MT6620 Wi-Fi][Driver] * Add implementation for querying current TX rate from firmware auto rate module * 1) Query link speed (TX rate) from firmware directly with buffering mechanism to reduce overhead * 2) Remove CNM CH-RECOVER event handling * 3) cfg read/write API renamed with kal prefix for unified naming rules. * * 10 26 2010 cp.wu * [WCXRP00000056] [MT6620 Wi-Fi][Driver] NVRAM implementation with Version Check[WCXRP00000137] [MT6620 Wi-Fi] [FW] * Support NIC capability query command * 1) update NVRAM content template to ver 1.02 * 2) add compile option for querying NIC capability (default: off) * 3) modify AIS 5GHz support to run-time option, which could be turned on by registry or NVRAM setting * 4) correct auto-rate compiler error under linux (treat warning as error) * 5) simplify usage of NVRAM and REG_INFO_T * 6) add version checking between driver and firmware * * 10 21 2010 chinghwa.yu * [WCXRP00000065] Update BoW design and settings * . * * 10 19 2010 jeffrey.chang * [WCXRP00000120] [MT6620 Wi-Fi][Driver] Refine linux kernel module to the license of MTK propietary and enable MTK * HIF by default * Refine linux kernel module to the license of MTK and enable MTK HIF * * 10 18 2010 jeffrey.chang * [WCXRP00000106] [MT6620 Wi-Fi][Driver] Enable setting multicast callback in Android * . * * 10 18 2010 cp.wu * [WCXRP00000056] [MT6620 Wi-Fi][Driver] NVRAM implementation with Version Check[WCXRP00000086] [MT6620 Wi-Fi][Driver] * The mac address is all zero at android * complete implementation of Android NVRAM access * * 09 27 2010 chinghwa.yu * [WCXRP00000063] Update BCM CoEx design and settings[WCXRP00000065] Update BoW design and settings * Update BCM/BoW design and settings. * * 09 23 2010 cp.wu * [WCXRP00000051] [MT6620 Wi-Fi][Driver] WHQL test fail in MAC address changed item * use firmware reported mac address right after wlanAdapterStart() as permanent address * * 09 21 2010 kevin.huang * [WCXRP00000052] [MT6620 Wi-Fi][Driver] Eliminate Linux Compile Warning * Eliminate Linux Compile Warning * * 09 03 2010 kevin.huang * NULL * Refine #include sequence and solve recursive/nested #include issue * * 09 01 2010 wh.su * NULL * adding the wapi support for integration test. * * 08 18 2010 yarco.yang * NULL * 1. Fixed HW checksum offload function not work under Linux issue. * 2. Add debug message. * * 08 16 2010 yarco.yang * NULL * Support Linux x86 * * 08 02 2010 jeffrey.chang * NULL * 1) modify tx service thread to avoid busy looping * 2) add spin lock declartion for linux build * * 07 29 2010 jeffrey.chang * NULL * fix memory leak for module unloading * * 07 28 2010 jeffrey.chang * NULL * 1) remove unused spinlocks * 2) enable encyption ioctls * 3) fix scan ioctl which may cause supplicant to hang * * 07 23 2010 jeffrey.chang * * bug fix: allocate regInfo when disabling firmware download * * 07 23 2010 jeffrey.chang * * use glue layer api to decrease or increase counter atomically * * 07 22 2010 jeffrey.chang * * add new spinlock * * 07 19 2010 jeffrey.chang * * modify cmd/data path for new design * * 07 08 2010 cp.wu * * [WPD00003833] [MT6620 and MT5931] Driver migration - move to new repository. * * 06 06 2010 kevin.huang * [WPD00003832][MT6620 5931] Create driver base * [MT6620 5931] Create driver base * * 05 26 2010 jeffrey.chang * [WPD00003826]Initial import for Linux port * 1) Modify set mac address code * 2) remove power management macro * * 05 10 2010 cp.wu * [WPD00003831][MT6620 Wi-Fi] Add framework for Wi-Fi Direct support * implement basic wi-fi direct framework * * 05 07 2010 jeffrey.chang * [WPD00003826]Initial import for Linux port * prevent supplicant accessing driver during resume * * 05 07 2010 cp.wu * [WPD00003831][MT6620 Wi-Fi] Add framework for Wi-Fi Direct support * add basic framework for implementating P2P driver hook. * * 04 27 2010 jeffrey.chang * [WPD00003826]Initial import for Linux port * 1) fix firmware download bug * 2) remove query statistics for acelerating firmware download * * 04 27 2010 jeffrey.chang * [WPD00003826]Initial import for Linux port * follow Linux's firmware framework, and remove unused kal API * * 04 21 2010 jeffrey.chang * [WPD00003826]Initial import for Linux port * add for private ioctl support * * 04 19 2010 jeffrey.chang * [WPD00003826]Initial import for Linux port * Query statistics from firmware * * 04 19 2010 jeffrey.chang * [WPD00003826]Initial import for Linux port * modify tcp/ip checksum offload flags * * 04 16 2010 jeffrey.chang * [WPD00003826]Initial import for Linux port * fix tcp/ip checksum offload bug * * 04 13 2010 cp.wu * [WPD00003823][MT6620 Wi-Fi] Add Bluetooth-over-Wi-Fi support * add framework for BT-over-Wi-Fi support. * * * * * * * * * * * * * * * * * 1) prPendingCmdInfo is replaced by queue for multiple handler * * * * * * * * * * * * * * * * * capability * * * * * * * * * * * * * * * * * 2) command sequence number is now increased atomically * * * * * * * * * * * * * * * * * 3) private data could be hold and taken use for other purpose * * 04 09 2010 jeffrey.chang * [WPD00003826]Initial import for Linux port * fix spinlock usage * * 04 07 2010 jeffrey.chang * [WPD00003826]Initial import for Linux port * Set MAC address from firmware * * 04 07 2010 cp.wu * [WPD00001943]Create WiFi test driver framework on WinXP * rWlanInfo should be placed at adapter rather than glue due to most operations * * * * * * are done in adapter layer. * * 04 07 2010 jeffrey.chang * [WPD00003826]Initial import for Linux port * (1)improve none-glue code portability * * (2) disable set Multicast address during atomic context * * 04 06 2010 jeffrey.chang * [WPD00003826]Initial import for Linux port * adding debug module * * 03 31 2010 wh.su * [WPD00003816][MT6620 Wi-Fi] Adding the security support * modify the wapi related code for new driver's design. * * 03 30 2010 jeffrey.chang * [WPD00003826]Initial import for Linux port * emulate NDIS Pending OID facility * * 03 26 2010 jeffrey.chang * [WPD00003826]Initial import for Linux port * fix f/w download start and load address by using config.h * * 03 26 2010 jeffrey.chang * [WPD00003826]Initial import for Linux port * [WPD00003826] Initial import for Linux port * adding firmware download support * * 03 24 2010 jeffrey.chang * [WPD00003826]Initial import for Linux port * initial import for Linux port ** \main\maintrunk.MT5921\52 2009-10-27 22:49:59 GMT mtk01090 ** Fix compile error for Linux EHPI driver ** \main\maintrunk.MT5921\51 2009-10-20 17:38:22 GMT mtk01090 ** Refine driver unloading and clean up procedure. Block requests, stop main thread and clean up queued requests, ** and then stop hw. ** \main\maintrunk.MT5921\50 2009-10-08 10:33:11 GMT mtk01090 ** Avoid accessing private data of net_device directly. Replace with netdev_priv(). Add more checking for input ** parameters and pointers. ** \main\maintrunk.MT5921\49 2009-09-28 20:19:05 GMT mtk01090 ** Add private ioctl to carry OID structures. Restructure public/private ioctl interfaces to Linux kernel. ** \main\maintrunk.MT5921\48 2009-09-03 13:58:46 GMT mtk01088 ** remove non-used code ** \main\maintrunk.MT5921\47 2009-09-03 11:40:25 GMT mtk01088 ** adding the module parameter for wapi ** \main\maintrunk.MT5921\46 2009-08-18 22:56:41 GMT mtk01090 ** Add Linux SDIO (with mmc core) support. ** Add Linux 2.6.21, 2.6.25, 2.6.26. ** Fix compile warning in Linux. ** \main\maintrunk.MT5921\45 2009-07-06 20:53:00 GMT mtk01088 ** adding the code to check the wapi 1x frame ** \main\maintrunk.MT5921\44 2009-06-23 23:18:55 GMT mtk01090 ** Add build option BUILD_USE_EEPROM and compile option CFG_SUPPORT_EXT_CONFIG for NVRAM support ** \main\maintrunk.MT5921\43 2009-02-16 23:46:51 GMT mtk01461 ** Revise the order of increasing u4TxPendingFrameNum because of CFG_TX_RET_TX_CTRL_EARLY ** \main\maintrunk.MT5921\42 2009-01-22 13:11:59 GMT mtk01088 ** set the tid and 1x value at same packet reserved field ** \main\maintrunk.MT5921\41 2008-10-20 22:43:53 GMT mtk01104 ** Fix wrong variable name "prDev" in wlanStop() ** \main\maintrunk.MT5921\40 2008-10-16 15:37:10 GMT mtk01461 ** add handle WLAN_STATUS_SUCCESS in wlanHardStartXmit() for CFG_TX_RET_TX_CTRL_EARLY ** \main\maintrunk.MT5921\39 2008-09-25 15:56:21 GMT mtk01461 ** Update driver for Code review ** \main\maintrunk.MT5921\38 2008-09-05 17:25:07 GMT mtk01461 ** Update Driver for Code Review ** \main\maintrunk.MT5921\37 2008-09-02 10:57:06 GMT mtk01461 ** Update driver for code review ** \main\maintrunk.MT5921\36 2008-08-05 01:53:28 GMT mtk01461 ** Add support for linux statistics ** \main\maintrunk.MT5921\35 2008-08-04 16:52:58 GMT mtk01461 ** Fix ASSERT if removing module in BG_SSID_SCAN state ** \main\maintrunk.MT5921\34 2008-06-13 22:52:24 GMT mtk01461 ** Revise status code handling in wlanHardStartXmit() for WLAN_STATUS_SUCCESS ** \main\maintrunk.MT5921\33 2008-05-30 18:56:53 GMT mtk01461 ** Not use wlanoidSetCurrentAddrForLinux() ** \main\maintrunk.MT5921\32 2008-05-30 14:39:40 GMT mtk01461 ** Remove WMM Assoc Flag ** \main\maintrunk.MT5921\31 2008-05-23 10:26:40 GMT mtk01084 ** modify wlanISR interface ** \main\maintrunk.MT5921\30 2008-05-03 18:52:36 GMT mtk01461 ** Fix Unset Broadcast filter when setMulticast ** \main\maintrunk.MT5921\29 2008-05-03 15:17:26 GMT mtk01461 ** Move Query Media Status to GLUE ** \main\maintrunk.MT5921\28 2008-04-24 22:48:21 GMT mtk01461 ** Revise set multicast function by using windows oid style for LP own back ** \main\maintrunk.MT5921\27 2008-04-24 12:00:08 GMT mtk01461 ** Fix multicast setting in Linux and add comment ** \main\maintrunk.MT5921\26 2008-03-28 10:40:22 GMT mtk01461 ** Fix set mac address func in Linux ** \main\maintrunk.MT5921\25 2008-03-26 15:37:26 GMT mtk01461 ** Add set MAC Address ** \main\maintrunk.MT5921\24 2008-03-26 14:24:53 GMT mtk01461 ** For Linux, set net_device has feature with checksum offload by default ** \main\maintrunk.MT5921\23 2008-03-11 14:50:52 GMT mtk01461 ** Fix typo ** \main\maintrunk.MT5921\22 2008-02-29 15:35:20 GMT mtk01088 ** add 1x decide code for sw port control ** \main\maintrunk.MT5921\21 2008-02-21 15:01:54 GMT mtk01461 ** Rearrange the set off place of GLUE spin lock in HardStartXmit ** \main\maintrunk.MT5921\20 2008-02-12 23:26:50 GMT mtk01461 ** Add debug option - Packet Order for Linux and add debug level - Event ** \main\maintrunk.MT5921\19 2007-12-11 00:11:12 GMT mtk01461 ** Fix SPIN_LOCK protection ** \main\maintrunk.MT5921\18 2007-11-30 17:02:25 GMT mtk01425 ** 1. Set Rx multicast packets mode before setting the address list ** \main\maintrunk.MT5921\17 2007-11-26 19:44:24 GMT mtk01461 ** Add OS_TIMESTAMP to packet ** \main\maintrunk.MT5921\16 2007-11-21 15:47:20 GMT mtk01088 ** fixed the unload module issue ** \main\maintrunk.MT5921\15 2007-11-07 18:37:38 GMT mtk01461 ** Fix compile warnning ** \main\maintrunk.MT5921\14 2007-11-02 01:03:19 GMT mtk01461 ** Unify TX Path for Normal and IBSS Power Save + IBSS neighbor learning ** \main\maintrunk.MT5921\13 2007-10-30 10:42:33 GMT mtk01425 ** 1. Refine for multicast list ** \main\maintrunk.MT5921\12 2007-10-25 18:08:13 GMT mtk01461 ** Add VOIP SCAN Support & Refine Roaming ** Revision 1.4 2007/07/05 07:25:33 MTK01461 ** Add Linux initial code, modify doc, add 11BB, RF init code ** ** Revision 1.3 2007/06/27 02:18:50 MTK01461 ** Update SCAN_FSM, Initial(Can Load Module), Proc(Can do Reg R/W), TX API ** ** Revision 1.2 2007/06/25 06:16:24 MTK01461 ** Update illustrations, gl_init.c, gl_kal.c, gl_kal.h, gl_os.h and RX API ** */ /******************************************************************************* * C O M P I L E R F L A G S ******************************************************************************** */ /******************************************************************************* * E X T E R N A L R E F E R E N C E S ******************************************************************************** */ #include "gl_os.h" #include "debug.h" #include "wlan_lib.h" #include "gl_wext.h" #include "gl_cfg80211.h" #include "precomp.h" #if CFG_SUPPORT_AGPS_ASSIST #include "gl_kal.h" #endif #if defined(CONFIG_MTK_TC1_FEATURE) #include <tc1_partition.h> #endif #include "gl_vendor.h" /******************************************************************************* * C O N S T A N T S ******************************************************************************** */ /* #define MAX_IOREQ_NUM 10 */ BOOLEAN fgIsUnderSuspend = false; struct semaphore g_halt_sem; int g_u4HaltFlag = 1; #if CFG_ENABLE_WIFI_DIRECT spinlock_t g_p2p_lock; int g_u4P2PEnding = 0; int g_u4P2POnOffing = 0; #endif /******************************************************************************* * D A T A T Y P E S ******************************************************************************** */ /* Tasklet mechanism is like buttom-half in Linux. We just want to * send a signal to OS for interrupt defer processing. All resources * are NOT allowed reentry, so txPacket, ISR-DPC and ioctl must avoid preempty. */ typedef struct _WLANDEV_INFO_T { struct net_device *prDev; } WLANDEV_INFO_T, *P_WLANDEV_INFO_T; /******************************************************************************* * P U B L I C D A T A ******************************************************************************** */ MODULE_AUTHOR(NIC_AUTHOR); MODULE_DESCRIPTION(NIC_DESC); MODULE_SUPPORTED_DEVICE(NIC_NAME); MODULE_LICENSE("GPL"); #define NIC_INF_NAME "wlan%d" /* interface name */ #if CFG_TC1_FEATURE #define NIC_INF_NAME_IN_AP_MODE "legacy%d" #endif /* support to change debug module info dynamically */ UINT_8 aucDebugModule[DBG_MODULE_NUM]; UINT_32 u4DebugModule = 0; /* 4 2007/06/26, mikewu, now we don't use this, we just fix the number of wlan device to 1 */ static WLANDEV_INFO_T arWlanDevInfo[CFG_MAX_WLAN_DEVICES] = { {0} }; static UINT_32 u4WlanDevNum; /* How many NICs coexist now */ /**20150205 added work queue for sched_scan to avoid cfg80211 stop schedule scan dead loack**/ struct delayed_work sched_workq; /******************************************************************************* * P R I V A T E D A T A ******************************************************************************** */ #if CFG_ENABLE_WIFI_DIRECT static SUB_MODULE_HANDLER rSubModHandler[SUB_MODULE_NUM] = { {NULL} }; #endif #define CHAN2G(_channel, _freq, _flags) \ { \ .band = IEEE80211_BAND_2GHZ, \ .center_freq = (_freq), \ .hw_value = (_channel), \ .flags = (_flags), \ .max_antenna_gain = 0, \ .max_power = 30, \ } static struct ieee80211_channel mtk_2ghz_channels[] = { CHAN2G(1, 2412, 0), CHAN2G(2, 2417, 0), CHAN2G(3, 2422, 0), CHAN2G(4, 2427, 0), CHAN2G(5, 2432, 0), CHAN2G(6, 2437, 0), CHAN2G(7, 2442, 0), CHAN2G(8, 2447, 0), CHAN2G(9, 2452, 0), CHAN2G(10, 2457, 0), CHAN2G(11, 2462, 0), CHAN2G(12, 2467, 0), CHAN2G(13, 2472, 0), CHAN2G(14, 2484, 0), }; #define CHAN5G(_channel, _flags) \ { \ .band = IEEE80211_BAND_5GHZ, \ .center_freq = 5000 + (5 * (_channel)), \ .hw_value = (_channel), \ .flags = (_flags), \ .max_antenna_gain = 0, \ .max_power = 30, \ } static struct ieee80211_channel mtk_5ghz_channels[] = { CHAN5G(34, 0), CHAN5G(36, 0), CHAN5G(38, 0), CHAN5G(40, 0), CHAN5G(42, 0), CHAN5G(44, 0), CHAN5G(46, 0), CHAN5G(48, 0), CHAN5G(52, 0), CHAN5G(56, 0), CHAN5G(60, 0), CHAN5G(64, 0), CHAN5G(100, 0), CHAN5G(104, 0), CHAN5G(108, 0), CHAN5G(112, 0), CHAN5G(116, 0), CHAN5G(120, 0), CHAN5G(124, 0), CHAN5G(128, 0), CHAN5G(132, 0), CHAN5G(136, 0), CHAN5G(140, 0), CHAN5G(149, 0), CHAN5G(153, 0), CHAN5G(157, 0), CHAN5G(161, 0), CHAN5G(165, 0), CHAN5G(169, 0), CHAN5G(173, 0), CHAN5G(184, 0), CHAN5G(188, 0), CHAN5G(192, 0), CHAN5G(196, 0), CHAN5G(200, 0), CHAN5G(204, 0), CHAN5G(208, 0), CHAN5G(212, 0), CHAN5G(216, 0), }; /* for cfg80211 - rate table */ static struct ieee80211_rate mtk_rates[] = { RATETAB_ENT(10, 0x1000, 0), RATETAB_ENT(20, 0x1001, 0), RATETAB_ENT(55, 0x1002, 0), RATETAB_ENT(110, 0x1003, 0), /* 802.11b */ RATETAB_ENT(60, 0x2000, 0), RATETAB_ENT(90, 0x2001, 0), RATETAB_ENT(120, 0x2002, 0), RATETAB_ENT(180, 0x2003, 0), RATETAB_ENT(240, 0x2004, 0), RATETAB_ENT(360, 0x2005, 0), RATETAB_ENT(480, 0x2006, 0), RATETAB_ENT(540, 0x2007, 0), /* 802.11a/g */ }; #define mtk_a_rates (mtk_rates + 4) #define mtk_a_rates_size (sizeof(mtk_rates) / sizeof(mtk_rates[0]) - 4) #define mtk_g_rates (mtk_rates + 0) #define mtk_g_rates_size (sizeof(mtk_rates) / sizeof(mtk_rates[0]) - 0) #define MT6620_MCS_INFO \ { \ .rx_mask = {0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0},\ .rx_highest = 0, \ .tx_params = IEEE80211_HT_MCS_TX_DEFINED, \ } #define MT6620_HT_CAP \ { \ .ht_supported = true, \ .cap = IEEE80211_HT_CAP_SUP_WIDTH_20_40 \ | IEEE80211_HT_CAP_SM_PS \ | IEEE80211_HT_CAP_GRN_FLD \ | IEEE80211_HT_CAP_SGI_20 \ | IEEE80211_HT_CAP_SGI_40, \ .ampdu_factor = IEEE80211_HT_MAX_AMPDU_64K, \ .ampdu_density = IEEE80211_HT_MPDU_DENSITY_NONE, \ .mcs = MT6620_MCS_INFO, \ } /* public for both Legacy Wi-Fi / P2P access */ struct ieee80211_supported_band mtk_band_2ghz = { .band = IEEE80211_BAND_2GHZ, .channels = mtk_2ghz_channels, .n_channels = ARRAY_SIZE(mtk_2ghz_channels), .bitrates = mtk_g_rates, .n_bitrates = mtk_g_rates_size, .ht_cap = MT6620_HT_CAP, }; /* public for both Legacy Wi-Fi / P2P access */ struct ieee80211_supported_band mtk_band_5ghz = { .band = IEEE80211_BAND_5GHZ, .channels = mtk_5ghz_channels, .n_channels = ARRAY_SIZE(mtk_5ghz_channels), .bitrates = mtk_a_rates, .n_bitrates = mtk_a_rates_size, .ht_cap = MT6620_HT_CAP, }; static const UINT_32 mtk_cipher_suites[] = { /* keep WEP first, it may be removed below */ WLAN_CIPHER_SUITE_WEP40, WLAN_CIPHER_SUITE_WEP104, WLAN_CIPHER_SUITE_TKIP, WLAN_CIPHER_SUITE_CCMP, /* keep last -- depends on hw flags! */ WLAN_CIPHER_SUITE_AES_CMAC }; static struct cfg80211_ops mtk_wlan_ops = { .suspend = mtk_cfg80211_suspend, .resume = mtk_cfg80211_resume, .change_virtual_intf = mtk_cfg80211_change_iface, .add_key = mtk_cfg80211_add_key, .get_key = mtk_cfg80211_get_key, .del_key = mtk_cfg80211_del_key, .set_default_key = mtk_cfg80211_set_default_key, .set_default_mgmt_key = mtk_cfg80211_set_default_mgmt_key, .get_station = mtk_cfg80211_get_station, .change_station = mtk_cfg80211_change_station, .add_station = mtk_cfg80211_add_station, .del_station = mtk_cfg80211_del_station, .scan = mtk_cfg80211_scan, .connect = mtk_cfg80211_connect, .disconnect = mtk_cfg80211_disconnect, .join_ibss = mtk_cfg80211_join_ibss, .leave_ibss = mtk_cfg80211_leave_ibss, .set_power_mgmt = mtk_cfg80211_set_power_mgmt, .set_pmksa = mtk_cfg80211_set_pmksa, .del_pmksa = mtk_cfg80211_del_pmksa, .flush_pmksa = mtk_cfg80211_flush_pmksa, .assoc = mtk_cfg80211_assoc, /* Action Frame TX/RX */ .remain_on_channel = mtk_cfg80211_remain_on_channel, .cancel_remain_on_channel = mtk_cfg80211_cancel_remain_on_channel, .mgmt_tx = mtk_cfg80211_mgmt_tx, /* .mgmt_tx_cancel_wait = mtk_cfg80211_mgmt_tx_cancel_wait, */ .mgmt_frame_register = mtk_cfg80211_mgmt_frame_register, #ifdef CONFIG_NL80211_TESTMODE .testmode_cmd = mtk_cfg80211_testmode_cmd, #endif #if (CFG_SUPPORT_TDLS == 1) .tdls_mgmt = TdlsexCfg80211TdlsMgmt, .tdls_oper = TdlsexCfg80211TdlsOper, #endif /* CFG_SUPPORT_TDLS */ #if 1 /* Remove schedule_scan because we need more verification for NLO */ .sched_scan_start = mtk_cfg80211_sched_scan_start, .sched_scan_stop = mtk_cfg80211_sched_scan_stop, #endif }; static const struct wiphy_vendor_command mtk_wlan_vendor_ops[] = { { { .vendor_id = GOOGLE_OUI, .subcmd = GSCAN_SUBCMD_GET_CAPABILITIES}, .flags = WIPHY_VENDOR_CMD_NEED_WDEV | WIPHY_VENDOR_CMD_NEED_NETDEV, .doit = mtk_cfg80211_vendor_get_gscan_capabilities}, { { .vendor_id = GOOGLE_OUI, .subcmd = GSCAN_SUBCMD_SET_CONFIG}, .flags = WIPHY_VENDOR_CMD_NEED_WDEV | WIPHY_VENDOR_CMD_NEED_NETDEV, .doit = mtk_cfg80211_vendor_set_config}, { { .vendor_id = GOOGLE_OUI, .subcmd = GSCAN_SUBCMD_SET_SCAN_CONFIG}, .flags = WIPHY_VENDOR_CMD_NEED_WDEV, .doit = mtk_cfg80211_vendor_set_scan_config}, { { .vendor_id = GOOGLE_OUI, .subcmd = GSCAN_SUBCMD_ENABLE_GSCAN}, .flags = WIPHY_VENDOR_CMD_NEED_WDEV | WIPHY_VENDOR_CMD_NEED_NETDEV, .doit = mtk_cfg80211_vendor_enable_scan}, { { .vendor_id = GOOGLE_OUI, .subcmd = GSCAN_SUBCMD_ENABLE_FULL_SCAN_RESULTS}, .flags = WIPHY_VENDOR_CMD_NEED_WDEV | WIPHY_VENDOR_CMD_NEED_NETDEV, .doit = mtk_cfg80211_vendor_enable_full_scan_results}, { { .vendor_id = GOOGLE_OUI, .subcmd = GSCAN_SUBCMD_GET_SCAN_RESULTS}, .flags = WIPHY_VENDOR_CMD_NEED_WDEV | WIPHY_VENDOR_CMD_NEED_NETDEV, .doit = mtk_cfg80211_vendor_get_scan_results}, { { .vendor_id = GOOGLE_OUI, .subcmd = GSCAN_SUBCMD_GET_CHANNEL_LIST}, .flags = WIPHY_VENDOR_CMD_NEED_WDEV | WIPHY_VENDOR_CMD_NEED_NETDEV, .doit = mtk_cfg80211_vendor_get_channel_list}, { { .vendor_id = GOOGLE_OUI, .subcmd = GSCAN_SUBCMD_SET_SIGNIFICANT_CHANGE_CONFIG}, .flags = WIPHY_VENDOR_CMD_NEED_WDEV | WIPHY_VENDOR_CMD_NEED_NETDEV, .doit = mtk_cfg80211_vendor_set_significant_change}, { { .vendor_id = GOOGLE_OUI, .subcmd = GSCAN_SUBCMD_SET_HOTLIST}, .flags = WIPHY_VENDOR_CMD_NEED_WDEV | WIPHY_VENDOR_CMD_NEED_NETDEV, .doit = mtk_cfg80211_vendor_set_hotlist}, /*Link Layer Statistics */ { { .vendor_id = GOOGLE_OUI, .subcmd = LSTATS_SUBCMD_GET_INFO}, .flags = WIPHY_VENDOR_CMD_NEED_WDEV | WIPHY_VENDOR_CMD_NEED_NETDEV, .doit = mtk_cfg80211_vendor_llstats_get_info}, { { .vendor_id = GOOGLE_OUI, .subcmd = RTT_SUBCMD_GETCAPABILITY}, .flags = WIPHY_VENDOR_CMD_NEED_WDEV | WIPHY_VENDOR_CMD_NEED_NETDEV, .doit = mtk_cfg80211_vendor_get_rtt_capabilities}, }; static const struct nl80211_vendor_cmd_info mtk_wlan_vendor_events[] = { { .vendor_id = GOOGLE_OUI, .subcmd = GSCAN_EVENT_SIGNIFICANT_CHANGE_RESULTS}, { .vendor_id = GOOGLE_OUI, .subcmd = GSCAN_EVENT_HOTLIST_RESULTS_FOUND}, { .vendor_id = GOOGLE_OUI, .subcmd = GSCAN_EVENT_SCAN_RESULTS_AVAILABLE}, { .vendor_id = GOOGLE_OUI, .subcmd = GSCAN_EVENT_FULL_SCAN_RESULTS}, { .vendor_id = GOOGLE_OUI, .subcmd = RTT_EVENT_COMPLETE}, { .vendor_id = GOOGLE_OUI, .subcmd = GSCAN_EVENT_COMPLETE_SCAN}, { .vendor_id = GOOGLE_OUI, .subcmd = GSCAN_EVENT_HOTLIST_RESULTS_LOST}, }; /* There isn't a lot of sense in it, but you can transmit anything you like */ static const struct ieee80211_txrx_stypes mtk_cfg80211_ais_default_mgmt_stypes[NUM_NL80211_IFTYPES] = { [NL80211_IFTYPE_ADHOC] = { .tx = 0xffff, .rx = BIT(IEEE80211_STYPE_ACTION >> 4) }, [NL80211_IFTYPE_STATION] = { .tx = 0xffff, .rx = BIT(IEEE80211_STYPE_ACTION >> 4) | BIT(IEEE80211_STYPE_PROBE_REQ >> 4) }, [NL80211_IFTYPE_AP] = { .tx = 0xffff, .rx = BIT(IEEE80211_STYPE_PROBE_REQ >> 4) | BIT(IEEE80211_STYPE_ACTION >> 4) }, [NL80211_IFTYPE_AP_VLAN] = { /* copy AP */ .tx = 0xffff, .rx = BIT(IEEE80211_STYPE_ASSOC_REQ >> 4) | BIT(IEEE80211_STYPE_REASSOC_REQ >> 4) | BIT(IEEE80211_STYPE_PROBE_REQ >> 4) | BIT(IEEE80211_STYPE_DISASSOC >> 4) | BIT(IEEE80211_STYPE_AUTH >> 4) | BIT(IEEE80211_STYPE_DEAUTH >> 4) | BIT(IEEE80211_STYPE_ACTION >> 4) }, [NL80211_IFTYPE_P2P_CLIENT] = { .tx = 0xffff, .rx = BIT(IEEE80211_STYPE_ACTION >> 4) | BIT(IEEE80211_STYPE_PROBE_REQ >> 4) }, [NL80211_IFTYPE_P2P_GO] = { .tx = 0xffff, .rx = BIT(IEEE80211_STYPE_PROBE_REQ >> 4) | BIT(IEEE80211_STYPE_ACTION >> 4) } }; /******************************************************************************* * M A C R O S ******************************************************************************** */ /******************************************************************************* * F U N C T I O N D E C L A R A T I O N S ******************************************************************************** */ /******************************************************************************* * F U N C T I O N S ******************************************************************************** */ /*----------------------------------------------------------------------------*/ /*! * \brief Override the implementation of select queue * * \param[in] dev Pointer to struct net_device * \param[in] skb Pointer to struct skb_buff * * \return (none) */ /*----------------------------------------------------------------------------*/ unsigned int _cfg80211_classify8021d(struct sk_buff *skb) { unsigned int dscp = 0; /* skb->priority values from 256->263 are magic values * directly indicate a specific 802.1d priority. This is * to allow 802.1d priority to be passed directly in from * tags */ if (skb->priority >= 256 && skb->priority <= 263) return skb->priority - 256; switch (skb->protocol) { case htons(ETH_P_IP): dscp = ip_hdr(skb)->tos & 0xfc; break; } return dscp >> 5; } static const UINT_16 au16Wlan1dToQueueIdx[8] = { 1, 0, 0, 1, 2, 2, 3, 3 }; static UINT_16 wlanSelectQueue(struct net_device *dev, struct sk_buff *skb, void *accel_priv, select_queue_fallback_t fallback) { skb->priority = _cfg80211_classify8021d(skb); return au16Wlan1dToQueueIdx[skb->priority]; } /*----------------------------------------------------------------------------*/ /*! * \brief Load NVRAM data and translate it into REG_INFO_T * * \param[in] prGlueInfo Pointer to struct GLUE_INFO_T * \param[out] prRegInfo Pointer to struct REG_INFO_T * * \return (none) */ /*----------------------------------------------------------------------------*/ static void glLoadNvram(IN P_GLUE_INFO_T prGlueInfo, OUT P_REG_INFO_T prRegInfo) { UINT_32 i, j; UINT_8 aucTmp[2]; PUINT_8 pucDest; ASSERT(prGlueInfo); ASSERT(prRegInfo); if ((!prGlueInfo) || (!prRegInfo)) return; if (kalCfgDataRead16(prGlueInfo, sizeof(WIFI_CFG_PARAM_STRUCT) - sizeof(UINT_16), (PUINT_16) aucTmp) == TRUE) { prGlueInfo->fgNvramAvailable = TRUE; /* load MAC Address */ #if !defined(CONFIG_MTK_TC1_FEATURE) for (i = 0; i < PARAM_MAC_ADDR_LEN; i += sizeof(UINT_16)) { kalCfgDataRead16(prGlueInfo, OFFSET_OF(WIFI_CFG_PARAM_STRUCT, aucMacAddress) + i, (PUINT_16) (((PUINT_8) prRegInfo->aucMacAddr) + i)); } #else TC1_FAC_NAME(FacReadWifiMacAddr) ((unsigned char *)prRegInfo->aucMacAddr); #endif /* load country code */ kalCfgDataRead16(prGlueInfo, OFFSET_OF(WIFI_CFG_PARAM_STRUCT, aucCountryCode[0]), (PUINT_16) aucTmp); /* cast to wide characters */ prRegInfo->au2CountryCode[0] = (UINT_16) aucTmp[0]; prRegInfo->au2CountryCode[1] = (UINT_16) aucTmp[1]; /* load default normal TX power */ for (i = 0; i < sizeof(TX_PWR_PARAM_T); i += sizeof(UINT_16)) { kalCfgDataRead16(prGlueInfo, OFFSET_OF(WIFI_CFG_PARAM_STRUCT, rTxPwr) + i, (PUINT_16) (((PUINT_8) &(prRegInfo->rTxPwr)) + i)); } /* load feature flags */ kalCfgDataRead16(prGlueInfo, OFFSET_OF(WIFI_CFG_PARAM_STRUCT, ucTxPwrValid), (PUINT_16) aucTmp); prRegInfo->ucTxPwrValid = aucTmp[0]; prRegInfo->ucSupport5GBand = aucTmp[1]; kalCfgDataRead16(prGlueInfo, OFFSET_OF(WIFI_CFG_PARAM_STRUCT, uc2G4BwFixed20M), (PUINT_16) aucTmp); prRegInfo->uc2G4BwFixed20M = aucTmp[0]; prRegInfo->uc5GBwFixed20M = aucTmp[1]; kalCfgDataRead16(prGlueInfo, OFFSET_OF(WIFI_CFG_PARAM_STRUCT, ucEnable5GBand), (PUINT_16) aucTmp); prRegInfo->ucEnable5GBand = aucTmp[0]; /* load EFUSE overriding part */ for (i = 0; i < sizeof(prRegInfo->aucEFUSE); i += sizeof(UINT_16)) { kalCfgDataRead16(prGlueInfo, OFFSET_OF(WIFI_CFG_PARAM_STRUCT, aucEFUSE) + i, (PUINT_16) (((PUINT_8) &(prRegInfo->aucEFUSE)) + i)); } /* load band edge tx power control */ kalCfgDataRead16(prGlueInfo, OFFSET_OF(WIFI_CFG_PARAM_STRUCT, fg2G4BandEdgePwrUsed), (PUINT_16) aucTmp); prRegInfo->fg2G4BandEdgePwrUsed = (BOOLEAN) aucTmp[0]; if (aucTmp[0]) { prRegInfo->cBandEdgeMaxPwrCCK = (INT_8) aucTmp[1]; kalCfgDataRead16(prGlueInfo, OFFSET_OF(WIFI_CFG_PARAM_STRUCT, cBandEdgeMaxPwrOFDM20), (PUINT_16) aucTmp); prRegInfo->cBandEdgeMaxPwrOFDM20 = (INT_8) aucTmp[0]; prRegInfo->cBandEdgeMaxPwrOFDM40 = (INT_8) aucTmp[1]; } /* load regulation subbands */ kalCfgDataRead16(prGlueInfo, OFFSET_OF(WIFI_CFG_PARAM_STRUCT, ucRegChannelListMap), (PUINT_16) aucTmp); prRegInfo->eRegChannelListMap = (ENUM_REG_CH_MAP_T) aucTmp[0]; prRegInfo->ucRegChannelListIndex = aucTmp[1]; if (prRegInfo->eRegChannelListMap == REG_CH_MAP_CUSTOMIZED) { for (i = 0; i < MAX_SUBBAND_NUM; i++) { pucDest = (PUINT_8) &prRegInfo->rDomainInfo.rSubBand[i]; for (j = 0; j < 6; j += sizeof(UINT_16)) { kalCfgDataRead16(prGlueInfo, OFFSET_OF(WIFI_CFG_PARAM_STRUCT, aucRegSubbandInfo) + (i * 6 + j), (PUINT_16) aucTmp); *pucDest++ = aucTmp[0]; *pucDest++ = aucTmp[1]; } } } /* load RSSI compensation */ kalCfgDataRead16(prGlueInfo, OFFSET_OF(WIFI_CFG_PARAM_STRUCT, uc2GRssiCompensation), (PUINT_16) aucTmp); prRegInfo->uc2GRssiCompensation = aucTmp[0]; prRegInfo->uc5GRssiCompensation = aucTmp[1]; kalCfgDataRead16(prGlueInfo, OFFSET_OF(WIFI_CFG_PARAM_STRUCT, fgRssiCompensationValidbit), (PUINT_16) aucTmp); prRegInfo->fgRssiCompensationValidbit = aucTmp[0]; prRegInfo->ucRxAntennanumber = aucTmp[1]; } else { prGlueInfo->fgNvramAvailable = FALSE; } } #if CFG_ENABLE_WIFI_DIRECT /*----------------------------------------------------------------------------*/ /*! * \brief called by txthread, run sub module init function * * \param[in] prGlueInfo Pointer to struct GLUE_INFO_T * * \return (none) */ /*----------------------------------------------------------------------------*/ VOID wlanSubModRunInit(P_GLUE_INFO_T prGlueInfo) { /*now, we only have p2p module */ if (rSubModHandler[P2P_MODULE].fgIsInited == FALSE) { rSubModHandler[P2P_MODULE].subModInit(prGlueInfo); rSubModHandler[P2P_MODULE].fgIsInited = TRUE; } } /*----------------------------------------------------------------------------*/ /*! * \brief called by txthread, run sub module exit function * * \param[in] prGlueInfo Pointer to struct GLUE_INFO_T * * \return (none) */ /*----------------------------------------------------------------------------*/ VOID wlanSubModRunExit(P_GLUE_INFO_T prGlueInfo) { /*now, we only have p2p module */ if (rSubModHandler[P2P_MODULE].fgIsInited == TRUE) { rSubModHandler[P2P_MODULE].subModExit(prGlueInfo); rSubModHandler[P2P_MODULE].fgIsInited = FALSE; } } /*----------------------------------------------------------------------------*/ /*! * \brief set sub module init flag, force TxThread to run sub modle init * * \param[in] prGlueInfo Pointer to struct GLUE_INFO_T * * \return (none) */ /*----------------------------------------------------------------------------*/ BOOLEAN wlanSubModInit(P_GLUE_INFO_T prGlueInfo) { /* 4 Mark HALT, notify main thread to finish current job */ prGlueInfo->ulFlag |= GLUE_FLAG_SUB_MOD_INIT; /* wake up main thread */ wake_up_interruptible(&prGlueInfo->waitq); /* wait main thread finish sub module INIT */ wait_for_completion_interruptible(&prGlueInfo->rSubModComp); #if 0 if (prGlueInfo->prAdapter->fgIsP2PRegistered) p2pNetRegister(prGlueInfo); #endif return TRUE; } /*----------------------------------------------------------------------------*/ /*! * \brief set sub module exit flag, force TxThread to run sub modle exit * * \param[in] prGlueInfo Pointer to struct GLUE_INFO_T * * \return (none) */ /*----------------------------------------------------------------------------*/ BOOLEAN wlanSubModExit(P_GLUE_INFO_T prGlueInfo) { #if 0 if (prGlueInfo->prAdapter->fgIsP2PRegistered) p2pNetUnregister(prGlueInfo); #endif /* 4 Mark HALT, notify main thread to finish current job */ prGlueInfo->ulFlag |= GLUE_FLAG_SUB_MOD_EXIT; /* wake up main thread */ wake_up_interruptible(&prGlueInfo->waitq); /* wait main thread finish sub module EXIT */ wait_for_completion_interruptible(&prGlueInfo->rSubModComp); return TRUE; } /*----------------------------------------------------------------------------*/ /*! * \brief set by sub module, indicate sub module is already inserted * * \param[in] rSubModInit, function pointer point to sub module init function * \param[in] rSubModExit, function pointer point to sub module exit function * \param[in] eSubModIdx, sub module index * * \return (none) */ /*----------------------------------------------------------------------------*/ VOID wlanSubModRegisterInitExit(SUB_MODULE_INIT rSubModInit, SUB_MODULE_EXIT rSubModExit, ENUM_SUB_MODULE_IDX_T eSubModIdx) { rSubModHandler[eSubModIdx].subModInit = rSubModInit; rSubModHandler[eSubModIdx].subModExit = rSubModExit; rSubModHandler[eSubModIdx].fgIsInited = FALSE; } #if 0 /*----------------------------------------------------------------------------*/ /*! * \brief check wlan is launched or not * * \param[in] (none) * * \return TRUE, wlan is already started * FALSE, wlan is not started yet */ /*----------------------------------------------------------------------------*/ BOOLEAN wlanIsLaunched(VOID) { struct net_device *prDev = NULL; P_GLUE_INFO_T prGlueInfo = NULL; /* 4 <0> Sanity check */ ASSERT(u4WlanDevNum <= CFG_MAX_WLAN_DEVICES); if (0 == u4WlanDevNum) return FALSE; prDev = arWlanDevInfo[u4WlanDevNum - 1].prDev; ASSERT(prDev); if (NULL == prDev) return FALSE; prGlueInfo = *((P_GLUE_INFO_T *) netdev_priv(prDev)); ASSERT(prGlueInfo); if (NULL == prGlueInfo) return FALSE; return prGlueInfo->prAdapter->fgIsWlanLaunched; } #endif /*----------------------------------------------------------------------------*/ /*! * \brief Export wlan GLUE_INFO_T pointer to p2p module * * \param[in] prGlueInfo Pointer to struct GLUE_INFO_T * * \return TRUE: get GlueInfo pointer successfully * FALSE: wlan is not started yet */ /*---------------------------------------------------------------------------*/ BOOLEAN wlanExportGlueInfo(P_GLUE_INFO_T *prGlueInfoExpAddr) { struct net_device *prDev = NULL; P_GLUE_INFO_T prGlueInfo = NULL; if (0 == u4WlanDevNum) return FALSE; prDev = arWlanDevInfo[u4WlanDevNum - 1].prDev; if (NULL == prDev) return FALSE; prGlueInfo = *((P_GLUE_INFO_T *) netdev_priv(prDev)); if (NULL == prGlueInfo) return FALSE; if (FALSE == prGlueInfo->prAdapter->fgIsWlanLaunched) return FALSE; *prGlueInfoExpAddr = prGlueInfo; return TRUE; } #endif /*----------------------------------------------------------------------------*/ /*! * \brief Release prDev from wlandev_array and free tasklet object related to it. * * \param[in] prDev Pointer to struct net_device * * \return (none) */ /*----------------------------------------------------------------------------*/ static void wlanClearDevIdx(struct net_device *prDev) { int i; ASSERT(prDev); for (i = 0; i < CFG_MAX_WLAN_DEVICES; i++) { if (arWlanDevInfo[i].prDev == prDev) { arWlanDevInfo[i].prDev = NULL; u4WlanDevNum--; } } } /* end of wlanClearDevIdx() */ /*----------------------------------------------------------------------------*/ /*! * \brief Allocate an unique interface index, net_device::ifindex member for this * wlan device. Store the net_device in wlandev_array, and initialize * tasklet object related to it. * * \param[in] prDev Pointer to struct net_device * * \retval >= 0 The device number. * \retval -1 Fail to get index. */ /*----------------------------------------------------------------------------*/ static int wlanGetDevIdx(struct net_device *prDev) { int i; ASSERT(prDev); for (i = 0; i < CFG_MAX_WLAN_DEVICES; i++) { if (arWlanDevInfo[i].prDev == (struct net_device *)NULL) { /* Reserve 2 bytes space to store one digit of * device number and NULL terminator. */ arWlanDevInfo[i].prDev = prDev; u4WlanDevNum++; return i; } } return -1; } /* end of wlanGetDevIdx() */ /*----------------------------------------------------------------------------*/ /*! * \brief A method of struct net_device, a primary SOCKET interface to configure * the interface lively. Handle an ioctl call on one of our devices. * Everything Linux ioctl specific is done here. Then we pass the contents * of the ifr->data to the request message handler. * * \param[in] prDev Linux kernel netdevice * * \param[in] prIFReq Our private ioctl request structure, typed for the generic * struct ifreq so we can use ptr to function * * \param[in] cmd Command ID * * \retval WLAN_STATUS_SUCCESS The IOCTL command is executed successfully. * \retval OTHER The execution of IOCTL command is failed. */ /*----------------------------------------------------------------------------*/ int wlanDoIOCTL(struct net_device *prDev, struct ifreq *prIFReq, int i4Cmd) { P_GLUE_INFO_T prGlueInfo = NULL; int ret = 0; /* Verify input parameters for the following functions */ ASSERT(prDev && prIFReq); if (!prDev || !prIFReq) { DBGLOG(INIT, WARN, "%s Invalid input data\n", __func__); return -EINVAL; } prGlueInfo = *((P_GLUE_INFO_T *) netdev_priv(prDev)); ASSERT(prGlueInfo); if (!prGlueInfo) { DBGLOG(INIT, WARN, "%s No glue info\n", __func__); return -EFAULT; } if (prGlueInfo->u4ReadyFlag == 0) return -EINVAL; /* printk ("ioctl %x\n", i4Cmd); */ if (i4Cmd == SIOCGIWPRIV) { /* 0x8B0D, get private ioctl table */ ret = wext_get_priv(prDev, prIFReq); } else if ((i4Cmd >= SIOCIWFIRST) && (i4Cmd < SIOCIWFIRSTPRIV)) { /* 0x8B00 ~ 0x8BDF, wireless extension region */ ret = wext_support_ioctl(prDev, prIFReq, i4Cmd); } else if ((i4Cmd >= SIOCIWFIRSTPRIV) && (i4Cmd < SIOCIWLASTPRIV)) { /* 0x8BE0 ~ 0x8BFF, private ioctl region */ ret = priv_support_ioctl(prDev, prIFReq, i4Cmd); } else if (i4Cmd == SIOCDEVPRIVATE + 1) { ret = priv_support_driver_cmd(prDev, prIFReq, i4Cmd); } else { DBGLOG(INIT, WARN, "Unexpected ioctl command: 0x%04x\n", i4Cmd); /* return 0 for safe? */ } return ret; } /* end of wlanDoIOCTL() */ /*----------------------------------------------------------------------------*/ /*! * \brief This function is to set multicast list and set rx mode. * * \param[in] prDev Pointer to struct net_device * * \return (none) */ /*----------------------------------------------------------------------------*/ static struct delayed_work workq; static struct net_device *gPrDev; static BOOLEAN fgIsWorkMcStart = FALSE; static BOOLEAN fgIsWorkMcEverInit = FALSE; static struct wireless_dev *gprWdev; #ifdef CONFIG_PM static const struct wiphy_wowlan_support wlan_wowlan_support = { .flags = WIPHY_WOWLAN_DISCONNECT | WIPHY_WOWLAN_ANY, }; #endif static void createWirelessDevice(void) { struct wiphy *prWiphy = NULL; struct wireless_dev *prWdev = NULL; #if CFG_SUPPORT_PERSIST_NETDEV struct net_device *prNetDev = NULL; #endif /* <1.1> Create wireless_dev */ prWdev = kzalloc(sizeof(struct wireless_dev), GFP_KERNEL); if (!prWdev) { DBGLOG(INIT, ERROR, "Allocating memory to wireless_dev context failed\n"); return; } /* initialize semaphore for ioctl */ sema_init(&g_halt_sem, 1); g_u4HaltFlag = 1; /* <1.2> Create wiphy */ prWiphy = wiphy_new(&mtk_wlan_ops, sizeof(GLUE_INFO_T)); if (!prWiphy) { DBGLOG(INIT, ERROR, "Allocating memory to wiphy device failed\n"); goto free_wdev; } /* <1.3> configure wireless_dev & wiphy */ prWdev->iftype = NL80211_IFTYPE_STATION; prWiphy->max_scan_ssids = 1; /* FIXME: for combo scan */ prWiphy->max_scan_ie_len = 512; prWiphy->max_sched_scan_ssids = CFG_SCAN_SSID_MAX_NUM; prWiphy->max_match_sets = CFG_SCAN_SSID_MATCH_MAX_NUM; prWiphy->max_sched_scan_ie_len = CFG_CFG80211_IE_BUF_LEN; prWiphy->interface_modes = BIT(NL80211_IFTYPE_STATION) | BIT(NL80211_IFTYPE_ADHOC); prWiphy->bands[IEEE80211_BAND_2GHZ] = &mtk_band_2ghz; /* always assign 5Ghz bands here, if the chip is not support 5Ghz, bands[IEEE80211_BAND_5GHZ] will be assign to NULL */ prWiphy->bands[IEEE80211_BAND_5GHZ] = &mtk_band_5ghz; prWiphy->signal_type = CFG80211_SIGNAL_TYPE_MBM; prWiphy->cipher_suites = (const u32 *)mtk_cipher_suites; prWiphy->n_cipher_suites = ARRAY_SIZE(mtk_cipher_suites); prWiphy->flags = WIPHY_FLAG_SUPPORTS_FW_ROAM | WIPHY_FLAG_HAS_REMAIN_ON_CHANNEL | WIPHY_FLAG_SUPPORTS_SCHED_SCAN; prWiphy->regulatory_flags = REGULATORY_CUSTOM_REG; #if (CFG_SUPPORT_TDLS == 1) TDLSEX_WIPHY_FLAGS_INIT(prWiphy->flags); #endif /* CFG_SUPPORT_TDLS */ prWiphy->max_remain_on_channel_duration = 5000; prWiphy->mgmt_stypes = mtk_cfg80211_ais_default_mgmt_stypes; prWiphy->vendor_commands = mtk_wlan_vendor_ops; prWiphy->n_vendor_commands = sizeof(mtk_wlan_vendor_ops) / sizeof(struct wiphy_vendor_command); prWiphy->vendor_events = mtk_wlan_vendor_events; prWiphy->n_vendor_events = ARRAY_SIZE(mtk_wlan_vendor_events); /* <1.4> wowlan support */ #ifdef CONFIG_PM prWiphy->wowlan = &wlan_wowlan_support; #endif #ifdef CONFIG_CFG80211_WEXT /* <1.5> Use wireless extension to replace IOCTL */ prWiphy->wext = &wext_handler_def; #endif if (wiphy_register(prWiphy) < 0) { DBGLOG(INIT, ERROR, "wiphy_register error\n"); goto free_wiphy; } prWdev->wiphy = prWiphy; #if CFG_SUPPORT_PERSIST_NETDEV /* <2> allocate and register net_device */ #if CFG_TC1_FEATURE if (wlan_if_changed) prNetDev = alloc_netdev_mq(sizeof(P_GLUE_INFO_T), NIC_INF_NAME_IN_AP_MODE, NET_NAME_PREDICTABLE, ether_setup, CFG_MAX_TXQ_NUM); else #else prNetDev = alloc_netdev_mq(sizeof(P_GLUE_INFO_T), NIC_INF_NAME, NET_NAME_PREDICTABLE, ether_setup, CFG_MAX_TXQ_NUM); #endif if (!prNetDev) { DBGLOG(INIT, ERROR, "Allocating memory to net_device context failed\n"); goto unregister_wiphy; } *((P_GLUE_INFO_T *) netdev_priv(prNetDev)) = (P_GLUE_INFO_T) wiphy_priv(prWiphy); prNetDev->netdev_ops = &wlan_netdev_ops; #ifdef CONFIG_WIRELESS_EXT prNetDev->wireless_handlers = &wext_handler_def; #endif netif_carrier_off(prNetDev); netif_tx_stop_all_queues(prNetDev); /* <2.1> co-relate with wireless_dev bi-directionally */ prNetDev->ieee80211_ptr = prWdev; prWdev->netdev = prNetDev; #if CFG_TCP_IP_CHKSUM_OFFLOAD prNetDev->features = NETIF_F_HW_CSUM; #endif /* <2.2> co-relate net device & device tree */ SET_NETDEV_DEV(prNetDev, wiphy_dev(prWiphy)); /* <2.3> register net_device */ if (register_netdev(prWdev->netdev) < 0) { DBGLOG(INIT, ERROR, "wlanNetRegister: net_device context is not registered.\n"); goto unregister_wiphy; } #endif /* CFG_SUPPORT_PERSIST_NETDEV */ gprWdev = prWdev; DBGLOG(INIT, INFO, "create wireless device success\n"); return; #if CFG_SUPPORT_PERSIST_NETDEV unregister_wiphy: wiphy_unregister(prWiphy); #endif free_wiphy: wiphy_free(prWiphy); free_wdev: kfree(prWdev); } static void destroyWirelessDevice(void) { #if CFG_SUPPORT_PERSIST_NETDEV unregister_netdev(gprWdev->netdev); free_netdev(gprWdev->netdev); #endif wiphy_unregister(gprWdev->wiphy); wiphy_free(gprWdev->wiphy); kfree(gprWdev); gprWdev = NULL; } static void wlanSetMulticastList(struct net_device *prDev) { gPrDev = prDev; schedule_delayed_work(&workq, 0); } /* FIXME: Since we cannot sleep in the wlanSetMulticastList, we arrange * another workqueue for sleeping. We don't want to block * tx_thread, so we can't let tx_thread to do this */ static void wlanSetMulticastListWorkQueue(struct work_struct *work) { P_GLUE_INFO_T prGlueInfo = NULL; UINT_32 u4PacketFilter = 0; UINT_32 u4SetInfoLen; struct net_device *prDev = gPrDev; fgIsWorkMcStart = TRUE; DBGLOG(INIT, INFO, "wlanSetMulticastListWorkQueue start...\n"); down(&g_halt_sem); if (g_u4HaltFlag) { fgIsWorkMcStart = FALSE; up(&g_halt_sem); return; } prGlueInfo = (NULL != prDev) ? *((P_GLUE_INFO_T *) netdev_priv(prDev)) : NULL; ASSERT(prDev); ASSERT(prGlueInfo); if (!prDev || !prGlueInfo) { DBGLOG(INIT, WARN, "abnormal dev or skb: prDev(0x%p), prGlueInfo(0x%p)\n", prDev, prGlueInfo); fgIsWorkMcStart = FALSE; up(&g_halt_sem); return; } if (prDev->flags & IFF_PROMISC) u4PacketFilter |= PARAM_PACKET_FILTER_PROMISCUOUS; if (prDev->flags & IFF_BROADCAST) u4PacketFilter |= PARAM_PACKET_FILTER_BROADCAST; if (prDev->flags & IFF_MULTICAST) { if ((prDev->flags & IFF_ALLMULTI) || (netdev_mc_count(prDev) > MAX_NUM_GROUP_ADDR)) { u4PacketFilter |= PARAM_PACKET_FILTER_ALL_MULTICAST; } else { u4PacketFilter |= PARAM_PACKET_FILTER_MULTICAST; } } up(&g_halt_sem); if (kalIoctl(prGlueInfo, wlanoidSetCurrentPacketFilter, &u4PacketFilter, sizeof(u4PacketFilter), FALSE, FALSE, TRUE, FALSE, &u4SetInfoLen) != WLAN_STATUS_SUCCESS) { fgIsWorkMcStart = FALSE; return; } if (u4PacketFilter & PARAM_PACKET_FILTER_MULTICAST) { /* Prepare multicast address list */ struct netdev_hw_addr *ha; PUINT_8 prMCAddrList = NULL; UINT_32 i = 0; down(&g_halt_sem); if (g_u4HaltFlag) { fgIsWorkMcStart = FALSE; up(&g_halt_sem); return; } prMCAddrList = kalMemAlloc(MAX_NUM_GROUP_ADDR * ETH_ALEN, VIR_MEM_TYPE); netdev_for_each_mc_addr(ha, prDev) { if (i < MAX_NUM_GROUP_ADDR) { memcpy((prMCAddrList + i * ETH_ALEN), ha->addr, ETH_ALEN); i++; } } up(&g_halt_sem); kalIoctl(prGlueInfo, wlanoidSetMulticastList, prMCAddrList, (i * ETH_ALEN), FALSE, FALSE, TRUE, FALSE, &u4SetInfoLen); kalMemFree(prMCAddrList, VIR_MEM_TYPE, MAX_NUM_GROUP_ADDR * ETH_ALEN); } fgIsWorkMcStart = FALSE; DBGLOG(INIT, INFO, "wlanSetMulticastListWorkQueue end\n"); } /* end of wlanSetMulticastList() */ /*----------------------------------------------------------------------------*/ /*! * \brief To indicate scheduled scan has been stopped * * \param[in] * prGlueInfo * * \return * None */ /*----------------------------------------------------------------------------*/ VOID wlanSchedScanStoppedWorkQueue(struct work_struct *work) { P_GLUE_INFO_T prGlueInfo = NULL; struct net_device *prDev = gPrDev; prGlueInfo = (NULL != prDev) ? *((P_GLUE_INFO_T *) netdev_priv(prDev)) : NULL; if (!prGlueInfo) { DBGLOG(SCN, ERROR, "prGlueInfo == NULL unexpected\n"); return; } /* 2. indication to cfg80211 */ /* 20150205 change cfg80211_sched_scan_stopped to work queue due to sched_scan_mtx dead lock issue */ cfg80211_sched_scan_stopped(priv_to_wiphy(prGlueInfo)); DBGLOG(SCN, INFO, "cfg80211_sched_scan_stopped event send done\n"); } /* FIXME: Since we cannot sleep in the wlanSetMulticastList, we arrange * another workqueue for sleeping. We don't want to block * tx_thread, so we can't let tx_thread to do this */ void p2pSetMulticastListWorkQueueWrapper(P_GLUE_INFO_T prGlueInfo) { ASSERT(prGlueInfo); if (!prGlueInfo) { DBGLOG(INIT, WARN, "abnormal dev or skb: prGlueInfo(0x%p)\n", prGlueInfo); return; } #if CFG_ENABLE_WIFI_DIRECT if (prGlueInfo->prAdapter->fgIsP2PRegistered) mtk_p2p_wext_set_Multicastlist(prGlueInfo); #endif } /* end of p2pSetMulticastListWorkQueueWrapper() */ /*----------------------------------------------------------------------------*/ /*! * \brief This function is TX entry point of NET DEVICE. * * \param[in] prSkb Pointer of the sk_buff to be sent * \param[in] prDev Pointer to struct net_device * * \retval NETDEV_TX_OK - on success. * \retval NETDEV_TX_BUSY - on failure, packet will be discarded by upper layer. */ /*----------------------------------------------------------------------------*/ int wlanHardStartXmit(struct sk_buff *prSkb, struct net_device *prDev) { P_GLUE_INFO_T prGlueInfo = *((P_GLUE_INFO_T *) netdev_priv(prDev)); P_QUE_ENTRY_T prQueueEntry = NULL; P_QUE_T prTxQueue = NULL; UINT_16 u2QueueIdx = 0; #if (CFG_SUPPORT_TDLS_DBG == 1) UINT16 u2Identifier = 0; #endif #if CFG_BOW_TEST UINT_32 i; #endif GLUE_SPIN_LOCK_DECLARATION(); ASSERT(prSkb); ASSERT(prDev); ASSERT(prGlueInfo); #if (CFG_SUPPORT_TDLS_DBG == 1) { UINT8 *pkt = prSkb->data; if ((*(pkt + 12) == 0x08) && (*(pkt + 13) == 0x00)) { /* ip */ u2Identifier = ((*(pkt + 18)) << 8) | (*(pkt + 19)); /* u2TdlsTxSeq[u4TdlsTxSeqId ++] = u2Identifier; */ DBGLOG(INIT, INFO, "<s> %d\n", u2Identifier); } } #endif /* check if WiFi is halt */ if (prGlueInfo->ulFlag & GLUE_FLAG_HALT) { DBGLOG(INIT, INFO, "GLUE_FLAG_HALT skip tx\n"); dev_kfree_skb(prSkb); return NETDEV_TX_OK; } #if CFG_SUPPORT_HOTSPOT_2_0 if (prGlueInfo->fgIsDad) { /* kalPrint("[Passpoint R2] Due to ipv4_dad...TX is forbidden\n"); */ dev_kfree_skb(prSkb); return NETDEV_TX_OK; } if (prGlueInfo->fgIs6Dad) { /* kalPrint("[Passpoint R2] Due to ipv6_dad...TX is forbidden\n"); */ dev_kfree_skb(prSkb); return NETDEV_TX_OK; } #endif STATS_TX_TIME_ARRIVE(prSkb); prQueueEntry = (P_QUE_ENTRY_T) GLUE_GET_PKT_QUEUE_ENTRY(prSkb); prTxQueue = &prGlueInfo->rTxQueue; #if CFG_BOW_TEST DBGLOG(BOW, TRACE, "sk_buff->len: %d\n", prSkb->len); DBGLOG(BOW, TRACE, "sk_buff->data_len: %d\n", prSkb->data_len); DBGLOG(BOW, TRACE, "sk_buff->data:\n"); for (i = 0; i < prSkb->len; i++) { DBGLOG(BOW, TRACE, "%4x", prSkb->data[i]); if ((i + 1) % 16 == 0) DBGLOG(BOW, TRACE, "\n"); } DBGLOG(BOW, TRACE, "\n"); #endif if (wlanProcessSecurityFrame(prGlueInfo->prAdapter, (P_NATIVE_PACKET) prSkb) == FALSE) { /* non-1x packets */ #if CFG_DBG_GPIO_PINS { /* TX request from OS */ mtk_wcn_stp_debug_gpio_assert(IDX_TX_REQ, DBG_TIE_LOW); kalUdelay(1); mtk_wcn_stp_debug_gpio_assert(IDX_TX_REQ, DBG_TIE_HIGH); } #endif u2QueueIdx = skb_get_queue_mapping(prSkb); ASSERT(u2QueueIdx < CFG_MAX_TXQ_NUM); #if CFG_ENABLE_PKT_LIFETIME_PROFILE GLUE_SET_PKT_ARRIVAL_TIME(prSkb, kalGetTimeTick()); #endif GLUE_INC_REF_CNT(prGlueInfo->i4TxPendingFrameNum); if (u2QueueIdx < CFG_MAX_TXQ_NUM) GLUE_INC_REF_CNT(prGlueInfo->ai4TxPendingFrameNumPerQueue[NETWORK_TYPE_AIS_INDEX][u2QueueIdx]); GLUE_ACQUIRE_SPIN_LOCK(prGlueInfo, SPIN_LOCK_TX_QUE); QUEUE_INSERT_TAIL(prTxQueue, prQueueEntry); GLUE_RELEASE_SPIN_LOCK(prGlueInfo, SPIN_LOCK_TX_QUE); /* GLUE_INC_REF_CNT(prGlueInfo->i4TxPendingFrameNum); */ /* GLUE_INC_REF_CNT(prGlueInfo->ai4TxPendingFrameNumPerQueue[NETWORK_TYPE_AIS_INDEX][u2QueueIdx]); */ if (u2QueueIdx < CFG_MAX_TXQ_NUM) { if (prGlueInfo->ai4TxPendingFrameNumPerQueue[NETWORK_TYPE_AIS_INDEX][u2QueueIdx] >= CFG_TX_STOP_NETIF_PER_QUEUE_THRESHOLD) { netif_stop_subqueue(prDev, u2QueueIdx); #if (CONF_HIF_LOOPBACK_AUTO == 1) prGlueInfo->rHifInfo.HifLoopbkFlg |= 0x01; #endif /* CONF_HIF_LOOPBACK_AUTO */ } } } else { /* printk("is security frame\n"); */ GLUE_INC_REF_CNT(prGlueInfo->i4TxPendingSecurityFrameNum); } DBGLOG(TX, EVENT, "\n+++++ pending frame %d len = %d +++++\n", prGlueInfo->i4TxPendingFrameNum, prSkb->len); prGlueInfo->rNetDevStats.tx_bytes += prSkb->len; prGlueInfo->rNetDevStats.tx_packets++; if (netif_carrier_ok(prDev)) kalPerMonStart(prGlueInfo); /* set GLUE_FLAG_TXREQ_BIT */ /* pr->u4Flag |= GLUE_FLAG_TXREQ; */ /* wake_up_interruptible(&prGlueInfo->waitq); */ kalSetEvent(prGlueInfo); /* For Linux, we'll always return OK FLAG, because we'll free this skb by ourself */ return NETDEV_TX_OK; } /* end of wlanHardStartXmit() */ /*----------------------------------------------------------------------------*/ /*! * \brief A method of struct net_device, to get the network interface statistical * information. * * Whenever an application needs to get statistics for the interface, this method * is called. This happens, for example, when ifconfig or netstat -i is run. * * \param[in] prDev Pointer to struct net_device. * * \return net_device_stats buffer pointer. */ /*----------------------------------------------------------------------------*/ struct net_device_stats *wlanGetStats(IN struct net_device *prDev) { P_GLUE_INFO_T prGlueInfo = *((P_GLUE_INFO_T *) netdev_priv(prDev)); #if 0 WLAN_STATUS rStatus; UINT_32 u4XmitError = 0; UINT_32 u4XmitOk = 0; UINT_32 u4RecvError = 0; UINT_32 u4RecvOk = 0; UINT_32 u4BufLen; ASSERT(prDev); /* @FIX ME: need a more clear way to do this */ rStatus = kalIoctl(prGlueInfo, wlanoidQueryXmitError, &u4XmitError, sizeof(UINT_32), TRUE, TRUE, TRUE, &u4BufLen); rStatus = kalIoctl(prGlueInfo, wlanoidQueryXmitOk, &u4XmitOk, sizeof(UINT_32), TRUE, TRUE, TRUE, &u4BufLen); rStatus = kalIoctl(prGlueInfo, wlanoidQueryRcvOk, &u4RecvOk, sizeof(UINT_32), TRUE, TRUE, TRUE, &u4BufLen); rStatus = kalIoctl(prGlueInfo, wlanoidQueryRcvError, &u4RecvError, sizeof(UINT_32), TRUE, TRUE, TRUE, &u4BufLen); prGlueInfo->rNetDevStats.rx_packets = u4RecvOk; prGlueInfo->rNetDevStats.tx_packets = u4XmitOk; prGlueInfo->rNetDevStats.tx_errors = u4XmitError; prGlueInfo->rNetDevStats.rx_errors = u4RecvError; /* prGlueInfo->rNetDevStats.rx_bytes = rCustomNetDevStats.u4RxBytes; */ /* prGlueInfo->rNetDevStats.tx_bytes = rCustomNetDevStats.u4TxBytes; */ /* prGlueInfo->rNetDevStats.rx_errors = rCustomNetDevStats.u4RxErrors; */ /* prGlueInfo->rNetDevStats.multicast = rCustomNetDevStats.u4Multicast; */ #endif /* prGlueInfo->rNetDevStats.rx_packets = 0; */ /* prGlueInfo->rNetDevStats.tx_packets = 0; */ prGlueInfo->rNetDevStats.tx_errors = 0; prGlueInfo->rNetDevStats.rx_errors = 0; /* prGlueInfo->rNetDevStats.rx_bytes = 0; */ /* prGlueInfo->rNetDevStats.tx_bytes = 0; */ prGlueInfo->rNetDevStats.rx_errors = 0; prGlueInfo->rNetDevStats.multicast = 0; return &prGlueInfo->rNetDevStats; } /* end of wlanGetStats() */ /*----------------------------------------------------------------------------*/ /*! * \brief A function for prDev->init * * \param[in] prDev Pointer to struct net_device. * * \retval 0 The execution of wlanInit succeeds. * \retval -ENXIO No such device. */ /*----------------------------------------------------------------------------*/ static int wlanInit(struct net_device *prDev) { P_GLUE_INFO_T prGlueInfo = NULL; if (fgIsWorkMcEverInit == FALSE) { if (!prDev) return -ENXIO; prGlueInfo = *((P_GLUE_INFO_T *) netdev_priv(prDev)); INIT_DELAYED_WORK(&workq, wlanSetMulticastListWorkQueue); /* 20150205 work queue for sched_scan */ INIT_DELAYED_WORK(&sched_workq, wlanSchedScanStoppedWorkQueue); fgIsWorkMcEverInit = TRUE; } return 0; /* success */ } /* end of wlanInit() */ /*----------------------------------------------------------------------------*/ /*! * \brief A function for prDev->uninit * * \param[in] prDev Pointer to struct net_device. * * \return (none) */ /*----------------------------------------------------------------------------*/ static void wlanUninit(struct net_device *prDev) { } /* end of wlanUninit() */ /*----------------------------------------------------------------------------*/ /*! * \brief A function for prDev->open * * \param[in] prDev Pointer to struct net_device. * * \retval 0 The execution of wlanOpen succeeds. * \retval < 0 The execution of wlanOpen failed. */ /*----------------------------------------------------------------------------*/ static int wlanOpen(struct net_device *prDev) { ASSERT(prDev); netif_tx_start_all_queues(prDev); return 0; /* success */ } /* end of wlanOpen() */ /*----------------------------------------------------------------------------*/ /*! * \brief A function for prDev->stop * * \param[in] prDev Pointer to struct net_device. * * \retval 0 The execution of wlanStop succeeds. * \retval < 0 The execution of wlanStop failed. */ /*----------------------------------------------------------------------------*/ static int wlanStop(struct net_device *prDev) { P_GLUE_INFO_T prGlueInfo = NULL; struct cfg80211_scan_request *prScanRequest = NULL; GLUE_SPIN_LOCK_DECLARATION(); ASSERT(prDev); prGlueInfo = *((P_GLUE_INFO_T *) netdev_priv(prDev)); /* CFG80211 down */ GLUE_ACQUIRE_SPIN_LOCK(prGlueInfo, SPIN_LOCK_NET_DEV); if (prGlueInfo->prScanRequest != NULL) { prScanRequest = prGlueInfo->prScanRequest; prGlueInfo->prScanRequest = NULL; } GLUE_RELEASE_SPIN_LOCK(prGlueInfo, SPIN_LOCK_NET_DEV); if (prScanRequest) cfg80211_scan_done(prScanRequest, TRUE); netif_tx_stop_all_queues(prDev); return 0; /* success */ } /* end of wlanStop() */ /*----------------------------------------------------------------------------*/ /*! * \brief Update Channel table for cfg80211 for Wi-Fi Direct based on current country code * * \param[in] prGlueInfo Pointer to glue info * * \return none */ /*----------------------------------------------------------------------------*/ VOID wlanUpdateChannelTable(P_GLUE_INFO_T prGlueInfo) { UINT_8 i, j; UINT_8 ucNumOfChannel; RF_CHANNEL_INFO_T aucChannelList[ARRAY_SIZE(mtk_2ghz_channels) + ARRAY_SIZE(mtk_5ghz_channels)]; /* 1. Disable all channel */ for (i = 0; i < ARRAY_SIZE(mtk_2ghz_channels); i++) { mtk_2ghz_channels[i].flags |= IEEE80211_CHAN_DISABLED; mtk_2ghz_channels[i].orig_flags |= IEEE80211_CHAN_DISABLED; } for (i = 0; i < ARRAY_SIZE(mtk_5ghz_channels); i++) { mtk_5ghz_channels[i].flags |= IEEE80211_CHAN_DISABLED; mtk_5ghz_channels[i].orig_flags |= IEEE80211_CHAN_DISABLED; } /* 2. Get current domain channel list */ rlmDomainGetChnlList(prGlueInfo->prAdapter, BAND_NULL, ARRAY_SIZE(mtk_2ghz_channels) + ARRAY_SIZE(mtk_5ghz_channels), &ucNumOfChannel, aucChannelList); /* 3. Enable specific channel based on domain channel list */ for (i = 0; i < ucNumOfChannel; i++) { switch (aucChannelList[i].eBand) { case BAND_2G4: for (j = 0; j < ARRAY_SIZE(mtk_2ghz_channels); j++) { if (mtk_2ghz_channels[j].hw_value == aucChannelList[i].ucChannelNum) { mtk_2ghz_channels[j].flags &= ~IEEE80211_CHAN_DISABLED; mtk_2ghz_channels[j].orig_flags &= ~IEEE80211_CHAN_DISABLED; break; } } break; case BAND_5G: for (j = 0; j < ARRAY_SIZE(mtk_5ghz_channels); j++) { if (mtk_5ghz_channels[j].hw_value == aucChannelList[i].ucChannelNum) { mtk_5ghz_channels[j].flags &= ~IEEE80211_CHAN_DISABLED; mtk_5ghz_channels[j].orig_flags &= ~IEEE80211_CHAN_DISABLED; break; } } break; default: break; } } } /*----------------------------------------------------------------------------*/ /*! * \brief Register the device to the kernel and return the index. * * \param[in] prDev Pointer to struct net_device. * * \retval 0 The execution of wlanNetRegister succeeds. * \retval < 0 The execution of wlanNetRegister failed. */ /*----------------------------------------------------------------------------*/ static INT_32 wlanNetRegister(struct wireless_dev *prWdev) { P_GLUE_INFO_T prGlueInfo; INT_32 i4DevIdx = -1; ASSERT(prWdev); do { if (!prWdev) break; prGlueInfo = (P_GLUE_INFO_T) wiphy_priv(prWdev->wiphy); i4DevIdx = wlanGetDevIdx(prWdev->netdev); if (i4DevIdx < 0) { DBGLOG(INIT, ERROR, "wlanNetRegister: net_device number exceeds.\n"); break; } /* adjust channel support status */ wlanUpdateChannelTable(prGlueInfo); #if !CFG_SUPPORT_PERSIST_NETDEV if (register_netdev(prWdev->netdev) < 0) { DBGLOG(INIT, ERROR, "wlanNetRegister: net_device context is not registered.\n"); wiphy_unregister(prWdev->wiphy); wlanClearDevIdx(prWdev->netdev); i4DevIdx = -1; } #endif if (i4DevIdx != -1) prGlueInfo->fgIsRegistered = TRUE; } while (FALSE); return i4DevIdx; /* success */ } /* end of wlanNetRegister() */ /*----------------------------------------------------------------------------*/ /*! * \brief Unregister the device from the kernel * * \param[in] prWdev Pointer to struct net_device. * * \return (none) */ /*----------------------------------------------------------------------------*/ static VOID wlanNetUnregister(struct wireless_dev *prWdev) { P_GLUE_INFO_T prGlueInfo; if (!prWdev) { DBGLOG(INIT, ERROR, "wlanNetUnregister: The device context is NULL\n"); return; } DBGLOG(INIT, TRACE, "unregister net_dev(0x%p)\n", prWdev->netdev); prGlueInfo = (P_GLUE_INFO_T) wiphy_priv(prWdev->wiphy); wlanClearDevIdx(prWdev->netdev); #if !CFG_SUPPORT_PERSIST_NETDEV unregister_netdev(prWdev->netdev); #endif prGlueInfo->fgIsRegistered = FALSE; DBGLOG(INIT, INFO, "unregister wireless_dev(0x%p), ifindex=%d\n", prWdev, prWdev->netdev->ifindex); } /* end of wlanNetUnregister() */ static const struct net_device_ops wlan_netdev_ops = { .ndo_open = wlanOpen, .ndo_stop = wlanStop, .ndo_set_rx_mode = wlanSetMulticastList, .ndo_get_stats = wlanGetStats, .ndo_do_ioctl = wlanDoIOCTL, .ndo_start_xmit = wlanHardStartXmit, .ndo_init = wlanInit, .ndo_uninit = wlanUninit, .ndo_select_queue = wlanSelectQueue, }; /*----------------------------------------------------------------------------*/ /*! * \brief A method for creating Linux NET4 struct net_device object and the * private data(prGlueInfo and prAdapter). Setup the IO address to the HIF. * Assign the function pointer to the net_device object * * \param[in] pvData Memory address for the device * * \retval Not null The wireless_dev object. * \retval NULL Fail to create wireless_dev object */ /*----------------------------------------------------------------------------*/ static struct lock_class_key rSpinKey[SPIN_LOCK_NUM]; static struct wireless_dev *wlanNetCreate(PVOID pvData) { P_GLUE_INFO_T prGlueInfo = NULL; struct wireless_dev *prWdev = gprWdev; UINT_32 i; struct device *prDev; if (!prWdev) { DBGLOG(INIT, ERROR, "Allocating memory to wireless_dev context failed\n"); return NULL; } /* 4 <1> co-relate wiphy & prDev */ #if MTK_WCN_HIF_SDIO mtk_wcn_hif_sdio_get_dev(*((MTK_WCN_HIF_SDIO_CLTCTX *) pvData), &prDev); #else /* prDev = &((struct sdio_func *) pvData)->dev; //samp */ prDev = pvData; /* samp */ #endif if (!prDev) DBGLOG(INIT, WARN, "unable to get struct dev for wlan\n"); /* don't set prDev as parent of wiphy->dev, because we have done device_add in driver init. if we set parent here, parent will be not able to know this child, and may occurs a KE in device_shutdown, to free wiphy->dev, because his parent has been freed. */ /*set_wiphy_dev(prWdev->wiphy, prDev);*/ #if !CFG_SUPPORT_PERSIST_NETDEV /* 4 <3> Initial Glue structure */ prGlueInfo = (P_GLUE_INFO_T) wiphy_priv(prWdev->wiphy); kalMemZero(prGlueInfo, sizeof(GLUE_INFO_T)); /* 4 <3.1> Create net device */ #if CFG_TC1_FEATURE if (wlan_if_changed) { prGlueInfo->prDevHandler = alloc_netdev_mq(sizeof(P_GLUE_INFO_T), NIC_INF_NAME_IN_AP_MODE, NET_NAME_PREDICTABLE, ether_setup, CFG_MAX_TXQ_NUM); } else { prGlueInfo->prDevHandler = alloc_netdev_mq(sizeof(P_GLUE_INFO_T), NIC_INF_NAME, NET_NAME_PREDICTABLE, ether_setup, CFG_MAX_TXQ_NUM); } #else prGlueInfo->prDevHandler = alloc_netdev_mq(sizeof(P_GLUE_INFO_T), NIC_INF_NAME, NET_NAME_PREDICTABLE, ether_setup, CFG_MAX_TXQ_NUM); #endif if (!prGlueInfo->prDevHandler) { DBGLOG(INIT, ERROR, "Allocating memory to net_device context failed\n"); return NULL; } DBGLOG(INIT, INFO, "net_device prDev(0x%p) allocated ifindex=%d\n", prGlueInfo->prDevHandler, prGlueInfo->prDevHandler->ifindex); /* 4 <3.1.1> initialize net device varaiables */ *((P_GLUE_INFO_T *) netdev_priv(prGlueInfo->prDevHandler)) = prGlueInfo; prGlueInfo->prDevHandler->netdev_ops = &wlan_netdev_ops; #ifdef CONFIG_WIRELESS_EXT prGlueInfo->prDevHandler->wireless_handlers = &wext_handler_def; #endif netif_carrier_off(prGlueInfo->prDevHandler); netif_tx_stop_all_queues(prGlueInfo->prDevHandler); /* 4 <3.1.2> co-relate with wiphy bi-directionally */ prGlueInfo->prDevHandler->ieee80211_ptr = prWdev; #if CFG_TCP_IP_CHKSUM_OFFLOAD prGlueInfo->prDevHandler->features = NETIF_F_HW_CSUM; #endif prWdev->netdev = prGlueInfo->prDevHandler; /* 4 <3.1.3> co-relate net device & prDev */ /*SET_NETDEV_DEV(prGlueInfo->prDevHandler, wiphy_dev(prWdev->wiphy));*/ SET_NETDEV_DEV(prGlueInfo->prDevHandler, prDev); #else /* CFG_SUPPORT_PERSIST_NETDEV */ prGlueInfo->prDevHandler = gprWdev->netdev; #endif /* CFG_SUPPORT_PERSIST_NETDEV */ /* 4 <3.2> initiali glue variables */ prGlueInfo->eParamMediaStateIndicated = PARAM_MEDIA_STATE_DISCONNECTED; prGlueInfo->ePowerState = ParamDeviceStateD0; prGlueInfo->fgIsMacAddrOverride = FALSE; prGlueInfo->fgIsRegistered = FALSE; prGlueInfo->prScanRequest = NULL; #if CFG_SUPPORT_HOTSPOT_2_0 /* Init DAD */ prGlueInfo->fgIsDad = FALSE; prGlueInfo->fgIs6Dad = FALSE; kalMemZero(prGlueInfo->aucDADipv4, 4); kalMemZero(prGlueInfo->aucDADipv6, 16); #endif init_completion(&prGlueInfo->rScanComp); init_completion(&prGlueInfo->rHaltComp); init_completion(&prGlueInfo->rPendComp); #if CFG_ENABLE_WIFI_DIRECT init_completion(&prGlueInfo->rSubModComp); #endif /* initialize timer for OID timeout checker */ kalOsTimerInitialize(prGlueInfo, kalTimeoutHandler); for (i = 0; i < SPIN_LOCK_NUM; i++) { spin_lock_init(&prGlueInfo->rSpinLock[i]); lockdep_set_class(&prGlueInfo->rSpinLock[i], &rSpinKey[i]); } /* initialize semaphore for ioctl */ sema_init(&prGlueInfo->ioctl_sem, 1); glSetHifInfo(prGlueInfo, (ULONG) pvData); /* 4 <8> Init Queues */ init_waitqueue_head(&prGlueInfo->waitq); QUEUE_INITIALIZE(&prGlueInfo->rCmdQueue); QUEUE_INITIALIZE(&prGlueInfo->rTxQueue); /* 4 <4> Create Adapter structure */ prGlueInfo->prAdapter = (P_ADAPTER_T) wlanAdapterCreate(prGlueInfo); if (!prGlueInfo->prAdapter) { DBGLOG(INIT, ERROR, "Allocating memory to adapter failed\n"); return NULL; } KAL_WAKE_LOCK_INIT(prAdapter, &prGlueInfo->rAhbIsrWakeLock, "WLAN AHB ISR"); #if CFG_SUPPORT_PERSIST_NETDEV dev_open(prGlueInfo->prDevHandler); netif_carrier_off(prGlueInfo->prDevHandler); netif_tx_stop_all_queues(prGlueInfo->prDevHandler); #endif return prWdev; } /* end of wlanNetCreate() */ /*----------------------------------------------------------------------------*/ /*! * \brief Destroying the struct net_device object and the private data. * * \param[in] prWdev Pointer to struct wireless_dev. * * \return (none) */ /*----------------------------------------------------------------------------*/ static VOID wlanNetDestroy(struct wireless_dev *prWdev) { P_GLUE_INFO_T prGlueInfo = NULL; ASSERT(prWdev); if (!prWdev) { DBGLOG(INIT, ERROR, "wlanNetDestroy: The device context is NULL\n"); return; } /* prGlueInfo is allocated with net_device */ prGlueInfo = (P_GLUE_INFO_T) wiphy_priv(prWdev->wiphy); ASSERT(prGlueInfo); /* destroy kal OS timer */ kalCancelTimer(prGlueInfo); glClearHifInfo(prGlueInfo); wlanAdapterDestroy(prGlueInfo->prAdapter); prGlueInfo->prAdapter = NULL; #if CFG_SUPPORT_PERSIST_NETDEV /* take the net_device to down state */ dev_close(prGlueInfo->prDevHandler); #else /* Free net_device and private data prGlueInfo, which are allocated by alloc_netdev(). */ free_netdev(prWdev->netdev); #endif } /* end of wlanNetDestroy() */ #ifndef CONFIG_X86 UINT_8 g_aucBufIpAddr[32] = { 0 }; static void wlanNotifyFwSuspend(P_GLUE_INFO_T prGlueInfo, BOOLEAN fgSuspend) { WLAN_STATUS rStatus = WLAN_STATUS_FAILURE; UINT_32 u4SetInfoLen; rStatus = kalIoctl(prGlueInfo, wlanoidNotifyFwSuspend, (PVOID)&fgSuspend, sizeof(fgSuspend), FALSE, FALSE, TRUE, FALSE, &u4SetInfoLen); if (rStatus != WLAN_STATUS_SUCCESS) DBGLOG(INIT, INFO, "wlanNotifyFwSuspend fail\n"); } void wlanHandleSystemSuspend(void) { WLAN_STATUS rStatus = WLAN_STATUS_FAILURE; struct net_device *prDev = NULL; P_GLUE_INFO_T prGlueInfo = NULL; UINT_8 ip[4] = { 0 }; UINT_32 u4NumIPv4 = 0; #ifdef CONFIG_IPV6 UINT_8 ip6[16] = { 0 }; /* FIX ME: avoid to allocate large memory in stack */ UINT_32 u4NumIPv6 = 0; #endif UINT_32 i; P_PARAM_NETWORK_ADDRESS_IP prParamIpAddr; #if CFG_SUPPORT_DROP_MC_PACKET UINT_32 u4PacketFilter = 0; UINT_32 u4SetInfoLen = 0; #endif /* <1> Sanity check and acquire the net_device */ ASSERT(u4WlanDevNum <= CFG_MAX_WLAN_DEVICES); if (u4WlanDevNum == 0) { DBGLOG(INIT, ERROR, "wlanEarlySuspend u4WlanDevNum==0 invalid!!\n"); return; } prDev = arWlanDevInfo[u4WlanDevNum - 1].prDev; fgIsUnderSuspend = true; prGlueInfo = *((P_GLUE_INFO_T *) netdev_priv(prDev)); ASSERT(prGlueInfo); #if CFG_SUPPORT_DROP_MC_PACKET /* new filter should not include p2p mask */ #if CFG_ENABLE_WIFI_DIRECT_CFG_80211 u4PacketFilter = prGlueInfo->prAdapter->u4OsPacketFilter & (~PARAM_PACKET_FILTER_P2P_MASK); #endif if (kalIoctl(prGlueInfo, wlanoidSetCurrentPacketFilter, &u4PacketFilter, sizeof(u4PacketFilter), FALSE, FALSE, TRUE, FALSE, &u4SetInfoLen) != WLAN_STATUS_SUCCESS) { DBGLOG(INIT, ERROR, "set packet filter failed.\n"); } #endif if (!prDev || !(prDev->ip_ptr) || !((struct in_device *)(prDev->ip_ptr))->ifa_list || !(&(((struct in_device *)(prDev->ip_ptr))->ifa_list->ifa_local))) { goto notify_suspend; } kalMemCopy(ip, &(((struct in_device *)(prDev->ip_ptr))->ifa_list->ifa_local), sizeof(ip)); /* todo: traverse between list to find whole sets of IPv4 addresses */ if (!((ip[0] == 0) && (ip[1] == 0) && (ip[2] == 0) && (ip[3] == 0))) u4NumIPv4++; #ifdef CONFIG_IPV6 if (!prDev || !(prDev->ip6_ptr) || !((struct in_device *)(prDev->ip6_ptr))->ifa_list || !(&(((struct in_device *)(prDev->ip6_ptr))->ifa_list->ifa_local))) { goto notify_suspend; } kalMemCopy(ip6, &(((struct in_device *)(prDev->ip6_ptr))->ifa_list->ifa_local), sizeof(ip6)); DBGLOG(INIT, INFO, "ipv6 is %d.%d.%d.%d.%d.%d.%d.%d.%d.%d.%d.%d.%d.%d.%d.%d\n", ip6[0], ip6[1], ip6[2], ip6[3], ip6[4], ip6[5], ip6[6], ip6[7], ip6[8], ip6[9], ip6[10], ip6[11], ip6[12], ip6[13], ip6[14], ip6[15] ); /* todo: traverse between list to find whole sets of IPv6 addresses */ if (!((ip6[0] == 0) && (ip6[1] == 0) && (ip6[2] == 0) && (ip6[3] == 0) && (ip6[4] == 0) && (ip6[5] == 0))) { /* Do nothing */ /* u4NumIPv6++; */ } #endif /* <7> set up the ARP filter */ { UINT_32 u4SetInfoLen = 0; UINT_32 u4Len = OFFSET_OF(PARAM_NETWORK_ADDRESS_LIST, arAddress); P_PARAM_NETWORK_ADDRESS_LIST prParamNetAddrList = (P_PARAM_NETWORK_ADDRESS_LIST) g_aucBufIpAddr; P_PARAM_NETWORK_ADDRESS prParamNetAddr = prParamNetAddrList->arAddress; kalMemZero(g_aucBufIpAddr, sizeof(g_aucBufIpAddr)); prParamNetAddrList->u4AddressCount = u4NumIPv4 + u4NumIPv6; prParamNetAddrList->u2AddressType = PARAM_PROTOCOL_ID_TCP_IP; for (i = 0; i < u4NumIPv4; i++) { prParamNetAddr->u2AddressLength = sizeof(PARAM_NETWORK_ADDRESS_IP); /* 4;; */ prParamNetAddr->u2AddressType = PARAM_PROTOCOL_ID_TCP_IP; prParamIpAddr = (P_PARAM_NETWORK_ADDRESS_IP) prParamNetAddr->aucAddress; kalMemCopy(&prParamIpAddr->in_addr, ip, sizeof(ip)); prParamNetAddr = (P_PARAM_NETWORK_ADDRESS) ((ULONG) prParamNetAddr + sizeof(PARAM_NETWORK_ADDRESS)); u4Len += OFFSET_OF(PARAM_NETWORK_ADDRESS, aucAddress) + sizeof(PARAM_NETWORK_ADDRESS); } #ifdef CONFIG_IPV6 for (i = 0; i < u4NumIPv6; i++) { prParamNetAddr->u2AddressLength = 6; prParamNetAddr->u2AddressType = PARAM_PROTOCOL_ID_TCP_IP; kalMemCopy(prParamNetAddr->aucAddress, ip6, sizeof(ip6)); prParamNetAddr = (P_PARAM_NETWORK_ADDRESS) ((ULONG) prParamNetAddr + sizeof(ip6)); u4Len += OFFSET_OF(PARAM_NETWORK_ADDRESS, aucAddress) + sizeof(ip6); } #endif ASSERT(u4Len <= sizeof(g_aucBufIpAddr)); rStatus = kalIoctl(prGlueInfo, wlanoidSetNetworkAddress, (PVOID) prParamNetAddrList, u4Len, FALSE, FALSE, TRUE, FALSE, &u4SetInfoLen); } notify_suspend: DBGLOG(INIT, INFO, "IP: %d.%d.%d.%d, rStatus: %u\n", ip[0], ip[1], ip[2], ip[3], rStatus); if (rStatus != WLAN_STATUS_SUCCESS) wlanNotifyFwSuspend(prGlueInfo, TRUE); } void wlanHandleSystemResume(void) { struct net_device *prDev = NULL; P_GLUE_INFO_T prGlueInfo = NULL; WLAN_STATUS rStatus = WLAN_STATUS_FAILURE; UINT_8 ip[4] = { 0 }; #ifdef CONFIG_IPV6 UINT_8 ip6[16] = { 0 }; /* FIX ME: avoid to allocate large memory in stack */ #endif EVENT_AIS_BSS_INFO_T rParam; UINT_32 u4BufLen = 0; #if CFG_SUPPORT_DROP_MC_PACKET UINT_32 u4PacketFilter = 0; UINT_32 u4SetInfoLen = 0; #endif /* <1> Sanity check and acquire the net_device */ ASSERT(u4WlanDevNum <= CFG_MAX_WLAN_DEVICES); if (u4WlanDevNum == 0) { DBGLOG(INIT, ERROR, "wlanLateResume u4WlanDevNum==0 invalid!!\n"); return; } prDev = arWlanDevInfo[u4WlanDevNum - 1].prDev; /* ASSERT(prDev); */ fgIsUnderSuspend = false; if (!prDev) { DBGLOG(INIT, INFO, "prDev == NULL!!!\n"); return; } /* <3> acquire the prGlueInfo */ prGlueInfo = *((P_GLUE_INFO_T *) netdev_priv(prDev)); ASSERT(prGlueInfo); #if CFG_SUPPORT_DROP_MC_PACKET /* new filter should not include p2p mask */ #if CFG_ENABLE_WIFI_DIRECT_CFG_80211 u4PacketFilter = prGlueInfo->prAdapter->u4OsPacketFilter & (~PARAM_PACKET_FILTER_P2P_MASK); #endif if (kalIoctl(prGlueInfo, wlanoidSetCurrentPacketFilter, &u4PacketFilter, sizeof(u4PacketFilter), FALSE, FALSE, TRUE, FALSE, &u4SetInfoLen) != WLAN_STATUS_SUCCESS) { DBGLOG(INIT, ERROR, "set packet filter failed.\n"); } #endif /* We will receive the event in rx, we will check if the status is the same in driver and FW, if not the same, trigger disconnetion procedure. */ kalMemZero(&rParam, sizeof(EVENT_AIS_BSS_INFO_T)); rStatus = kalIoctl(prGlueInfo, wlanoidQueryBSSInfo, &rParam, sizeof(EVENT_AIS_BSS_INFO_T), TRUE, TRUE, TRUE, FALSE, &u4BufLen); if (rStatus != WLAN_STATUS_SUCCESS) { DBGLOG(INIT, ERROR, "Query BSSinfo fail 0x%x!!\n", rStatus); } /* <2> get the IPv4 address */ if (!(prDev->ip_ptr) || !((struct in_device *)(prDev->ip_ptr))->ifa_list || !(&(((struct in_device *)(prDev->ip_ptr))->ifa_list->ifa_local))) { goto notify_resume; } /* <4> copy the IPv4 address */ kalMemCopy(ip, &(((struct in_device *)(prDev->ip_ptr))->ifa_list->ifa_local), sizeof(ip)); #ifdef CONFIG_IPV6 /* <5> get the IPv6 address */ if (!prDev || !(prDev->ip6_ptr) || !((struct in_device *)(prDev->ip6_ptr))->ifa_list || !(&(((struct in_device *)(prDev->ip6_ptr))->ifa_list->ifa_local))) { goto notify_resume; } /* <6> copy the IPv6 address */ kalMemCopy(ip6, &(((struct in_device *)(prDev->ip6_ptr))->ifa_list->ifa_local), sizeof(ip6)); DBGLOG(INIT, INFO, "ipv6 is %d.%d.%d.%d.%d.%d.%d.%d.%d.%d.%d.%d.%d.%d.%d.%d\n", ip6[0], ip6[1], ip6[2], ip6[3], ip6[4], ip6[5], ip6[6], ip6[7], ip6[8], ip6[9], ip6[10], ip6[11], ip6[12], ip6[13], ip6[14], ip6[15] ); #endif /* <7> clear the ARP filter */ { UINT_32 u4SetInfoLen = 0; /* UINT_8 aucBuf[32] = {0}; */ UINT_32 u4Len = sizeof(PARAM_NETWORK_ADDRESS_LIST); P_PARAM_NETWORK_ADDRESS_LIST prParamNetAddrList = (P_PARAM_NETWORK_ADDRESS_LIST) g_aucBufIpAddr; /* aucBuf; */ kalMemZero(g_aucBufIpAddr, sizeof(g_aucBufIpAddr)); prParamNetAddrList->u4AddressCount = 0; prParamNetAddrList->u2AddressType = PARAM_PROTOCOL_ID_TCP_IP; ASSERT(u4Len <= sizeof(g_aucBufIpAddr /*aucBuf */)); rStatus = kalIoctl(prGlueInfo, wlanoidSetNetworkAddress, (PVOID) prParamNetAddrList, u4Len, FALSE, FALSE, TRUE, FALSE, &u4SetInfoLen); } notify_resume: DBGLOG(INIT, INFO, "Query BSS result: %d %d %d, IP: %d.%d.%d.%d, rStatus: %u\n", rParam.eConnectionState, rParam.eCurrentOPMode, rParam.fgIsNetActive, ip[0], ip[1], ip[2], ip[3], rStatus); if (rStatus != WLAN_STATUS_SUCCESS) { wlanNotifyFwSuspend(prGlueInfo, FALSE); } } #endif /* ! CONFIG_X86 */ int set_p2p_mode_handler(struct net_device *netdev, PARAM_CUSTOM_P2P_SET_STRUCT_T p2pmode) { #if 0 P_GLUE_INFO_T prGlueInfo = *((P_GLUE_INFO_T *) netdev_priv(netdev)); PARAM_CUSTOM_P2P_SET_STRUCT_T rSetP2P; WLAN_STATUS rWlanStatus = WLAN_STATUS_SUCCESS; UINT_32 u4BufLen = 0; rSetP2P.u4Enable = p2pmode.u4Enable; rSetP2P.u4Mode = p2pmode.u4Mode; if (!rSetP2P.u4Enable) p2pNetUnregister(prGlueInfo, TRUE); rWlanStatus = kalIoctl(prGlueInfo, wlanoidSetP2pMode, (PVOID) &rSetP2P, sizeof(PARAM_CUSTOM_P2P_SET_STRUCT_T), FALSE, FALSE, TRUE, FALSE, &u4BufLen); DBGLOG(INIT, INFO, "ret = %d\n", rWlanStatus); if (rSetP2P.u4Enable) p2pNetRegister(prGlueInfo, TRUE); return 0; #else P_GLUE_INFO_T prGlueInfo = *((P_GLUE_INFO_T *) netdev_priv(netdev)); PARAM_CUSTOM_P2P_SET_STRUCT_T rSetP2P; WLAN_STATUS rWlanStatus = WLAN_STATUS_SUCCESS; BOOLEAN fgIsP2PEnding; UINT_32 u4BufLen = 0; GLUE_SPIN_LOCK_DECLARATION(); DBGLOG(INIT, INFO, "%u %u\n", (UINT_32) p2pmode.u4Enable, (UINT_32) p2pmode.u4Mode); /* avoid remove & p2p off command simultaneously */ GLUE_ACQUIRE_THE_SPIN_LOCK(&g_p2p_lock); fgIsP2PEnding = g_u4P2PEnding; g_u4P2POnOffing = 1; GLUE_RELEASE_THE_SPIN_LOCK(&g_p2p_lock); if (fgIsP2PEnding == 1) { /* skip the command if we are removing */ GLUE_ACQUIRE_THE_SPIN_LOCK(&g_p2p_lock); g_u4P2POnOffing = 0; GLUE_RELEASE_THE_SPIN_LOCK(&g_p2p_lock); return 0; } rSetP2P.u4Enable = p2pmode.u4Enable; rSetP2P.u4Mode = p2pmode.u4Mode; #if !CFG_SUPPORT_PERSIST_NETDEV if ((!rSetP2P.u4Enable) && (fgIsResetting == FALSE)) p2pNetUnregister(prGlueInfo, TRUE); #endif /* move out to caller to avoid kalIoctrl & suspend/resume deadlock problem ALPS00844864 */ /* Scenario: 1. System enters suspend/resume but not yet enter wlanearlysuspend() or wlanlateresume(); 2. System switches to do PRIV_CMD_P2P_MODE and execute kalIoctl() and get g_halt_sem then do glRegisterEarlySuspend() or glUnregisterEarlySuspend(); But system suspend/resume procedure is not yet finished so we suspend; 3. System switches back to do suspend/resume procedure and execute kalIoctl(). But driver does not yet release g_halt_sem so system suspend in wlanearlysuspend() or wlanlateresume(); ==> deadlock occurs. */ rWlanStatus = kalIoctl(prGlueInfo, wlanoidSetP2pMode, (PVOID) &rSetP2P,/* pu4IntBuf[0]is used as input SubCmd */ sizeof(PARAM_CUSTOM_P2P_SET_STRUCT_T), FALSE, FALSE, TRUE, FALSE, &u4BufLen); #if !CFG_SUPPORT_PERSIST_NETDEV /* Need to check fgIsP2PRegistered, in case of whole chip reset. * in this case, kalIOCTL return success always, * and prGlueInfo->prP2pInfo may be NULL */ if ((rSetP2P.u4Enable) && (prGlueInfo->prAdapter->fgIsP2PRegistered) && (fgIsResetting == FALSE)) p2pNetRegister(prGlueInfo, TRUE); #endif GLUE_ACQUIRE_THE_SPIN_LOCK(&g_p2p_lock); g_u4P2POnOffing = 0; GLUE_RELEASE_THE_SPIN_LOCK(&g_p2p_lock); return 0; #endif } static void set_dbg_level_handler(unsigned char dbg_lvl[DBG_MODULE_NUM]) { kalMemCopy(aucDebugModule, dbg_lvl, sizeof(aucDebugModule)); kalPrint("[wlan] change debug level"); } /*----------------------------------------------------------------------------*/ /*! * \brief Wlan probe function. This function probes and initializes the device. * * \param[in] pvData data passed by bus driver init function * _HIF_EHPI: NULL * _HIF_SDIO: sdio bus driver handle * * \retval 0 Success * \retval negative value Failed */ /*----------------------------------------------------------------------------*/ static INT_32 wlanProbe(PVOID pvData) { struct wireless_dev *prWdev = NULL; enum probe_fail_reason { BUS_INIT_FAIL, NET_CREATE_FAIL, BUS_SET_IRQ_FAIL, ADAPTER_START_FAIL, NET_REGISTER_FAIL, PROC_INIT_FAIL, FAIL_REASON_NUM } eFailReason; P_WLANDEV_INFO_T prWlandevInfo = NULL; INT_32 i4DevIdx = 0; P_GLUE_INFO_T prGlueInfo = NULL; P_ADAPTER_T prAdapter = NULL; INT_32 i4Status = 0; BOOLEAN bRet = FALSE; eFailReason = FAIL_REASON_NUM; do { /* 4 <1> Initialize the IO port of the interface */ /* GeorgeKuo: pData has different meaning for _HIF_XXX: * _HIF_EHPI: pointer to memory base variable, which will be * initialized by glBusInit(). * _HIF_SDIO: bus driver handle */ bRet = glBusInit(pvData); wlanDebugInit(); /* Cannot get IO address from interface */ if (FALSE == bRet) { DBGLOG(INIT, ERROR, KERN_ALERT "wlanProbe: glBusInit() fail\n"); i4Status = -EIO; eFailReason = BUS_INIT_FAIL; break; } /* 4 <2> Create network device, Adapter, KalInfo, prDevHandler(netdev) */ prWdev = wlanNetCreate(pvData); if (prWdev == NULL) { DBGLOG(INIT, ERROR, "wlanProbe: No memory for dev and its private\n"); i4Status = -ENOMEM; eFailReason = NET_CREATE_FAIL; break; } /* 4 <2.5> Set the ioaddr to HIF Info */ prGlueInfo = (P_GLUE_INFO_T) wiphy_priv(prWdev->wiphy); gPrDev = prGlueInfo->prDevHandler; /* 4 <4> Setup IRQ */ prWlandevInfo = &arWlanDevInfo[i4DevIdx]; i4Status = glBusSetIrq(prWdev->netdev, NULL, *((P_GLUE_INFO_T *) netdev_priv(prWdev->netdev))); if (i4Status != WLAN_STATUS_SUCCESS) { DBGLOG(INIT, ERROR, "wlanProbe: Set IRQ error\n"); eFailReason = BUS_SET_IRQ_FAIL; break; } prGlueInfo->i4DevIdx = i4DevIdx; prAdapter = prGlueInfo->prAdapter; prGlueInfo->u4ReadyFlag = 0; #if CFG_TCP_IP_CHKSUM_OFFLOAD prAdapter->u4CSUMFlags = (CSUM_OFFLOAD_EN_TX_TCP | CSUM_OFFLOAD_EN_TX_UDP | CSUM_OFFLOAD_EN_TX_IP); #endif #if CFG_SUPPORT_CFG_FILE { PUINT_8 pucConfigBuf; UINT_32 u4ConfigReadLen; wlanCfgInit(prAdapter, NULL, 0, 0); pucConfigBuf = (PUINT_8) kalMemAlloc(WLAN_CFG_FILE_BUF_SIZE, VIR_MEM_TYPE); u4ConfigReadLen = 0; DBGLOG(INIT, LOUD, "CFG_FILE: Read File...\n"); if (pucConfigBuf) { kalMemZero(pucConfigBuf, WLAN_CFG_FILE_BUF_SIZE); if (kalReadToFile("/data/misc/wifi.cfg", pucConfigBuf, WLAN_CFG_FILE_BUF_SIZE, &u4ConfigReadLen) == 0) { DBGLOG(INIT, LOUD, "CFG_FILE: Read /data/misc/wifi.cfg\n"); } else if (kalReadToFile("/data/misc/wifi/wifi.cfg", pucConfigBuf, WLAN_CFG_FILE_BUF_SIZE, &u4ConfigReadLen) == 0) { DBGLOG(INIT, LOUD, "CFG_FILE: Read /data/misc/wifi/wifi.cfg\n"); } else if (kalReadToFile("/etc/firmware/wifi.cfg", pucConfigBuf, WLAN_CFG_FILE_BUF_SIZE, &u4ConfigReadLen) == 0) { DBGLOG(INIT, LOUD, "CFG_FILE: Read /etc/firmware/wifi.cfg\n"); } if (pucConfigBuf[0] != '\0' && u4ConfigReadLen > 0) wlanCfgInit(prAdapter, pucConfigBuf, u4ConfigReadLen, 0); kalMemFree(pucConfigBuf, VIR_MEM_TYPE, WLAN_CFG_FILE_BUF_SIZE); } /* pucConfigBuf */ } #endif /* 4 <5> Start Device */ /* */ #if CFG_ENABLE_FW_DOWNLOAD DBGLOG(INIT, TRACE, "start to download firmware...\n"); /* before start adapter, we need to open and load firmware */ { UINT_32 u4FwSize = 0; PVOID prFwBuffer = NULL; P_REG_INFO_T prRegInfo = &prGlueInfo->rRegInfo; /* P_REG_INFO_T prRegInfo = (P_REG_INFO_T) kmalloc(sizeof(REG_INFO_T), GFP_KERNEL); */ kalMemSet(prRegInfo, 0, sizeof(REG_INFO_T)); prRegInfo->u4StartAddress = CFG_FW_START_ADDRESS; prRegInfo->u4LoadAddress = CFG_FW_LOAD_ADDRESS; /* Load NVRAM content to REG_INFO_T */ glLoadNvram(prGlueInfo, prRegInfo); #if CFG_SUPPORT_CFG_FILE wlanCfgApply(prAdapter); #endif /* kalMemCopy(&prGlueInfo->rRegInfo, prRegInfo, sizeof(REG_INFO_T)); */ prRegInfo->u4PowerMode = CFG_INIT_POWER_SAVE_PROF; prRegInfo->fgEnArpFilter = TRUE; if (kalFirmwareImageMapping(prGlueInfo, &prFwBuffer, &u4FwSize) == NULL) { i4Status = -EIO; DBGLOG(INIT, ERROR, "kalFirmwareImageMapping fail!\n"); goto bailout; } else { if (wlanAdapterStart(prAdapter, prRegInfo, prFwBuffer, u4FwSize) != WLAN_STATUS_SUCCESS) { i4Status = -EIO; } } kalFirmwareImageUnmapping(prGlueInfo, NULL, prFwBuffer); bailout: /* kfree(prRegInfo); */ DBGLOG(INIT, TRACE, "download firmware status = %d\n", i4Status); if (i4Status < 0) { GL_HIF_INFO_T *HifInfo; UINT_32 u4FwCnt; DBGLOG(INIT, WARN, "CONNSYS FW CPUINFO:\n"); HifInfo = &prAdapter->prGlueInfo->rHifInfo; for (u4FwCnt = 0; u4FwCnt < 16; u4FwCnt++) DBGLOG(INIT, WARN, "0x%08x ", MCU_REG_READL(HifInfo, CONN_MCU_CPUPCR)); /* CONSYS_REG_READ(CONSYS_CPUPCR_REG) */ /* dump HIF/DMA registers, if fgIsBusAccessFailed is FALSE, otherwise, */ /* dump HIF register may be hung */ if (!fgIsBusAccessFailed) HifRegDump(prGlueInfo->prAdapter); /* if (prGlueInfo->rHifInfo.DmaOps->DmaRegDump != NULL) */ /* prGlueInfo->rHifInfo.DmaOps->DmaRegDump(&prGlueInfo->rHifInfo); */ eFailReason = ADAPTER_START_FAIL; break; } } #else /* P_REG_INFO_T prRegInfo = (P_REG_INFO_T) kmalloc(sizeof(REG_INFO_T), GFP_KERNEL); */ kalMemSet(&prGlueInfo->rRegInfo, 0, sizeof(REG_INFO_T)); P_REG_INFO_T prRegInfo = &prGlueInfo->rRegInfo; /* Load NVRAM content to REG_INFO_T */ glLoadNvram(prGlueInfo, prRegInfo); prRegInfo->u4PowerMode = CFG_INIT_POWER_SAVE_PROF; if (wlanAdapterStart(prAdapter, prRegInfo, NULL, 0) != WLAN_STATUS_SUCCESS) { i4Status = -EIO; eFailReason = ADAPTER_START_FAIL; break; } #endif if (FALSE == prAdapter->fgEnable5GBand) prWdev->wiphy->bands[IEEE80211_BAND_5GHZ] = NULL; prGlueInfo->main_thread = kthread_run(tx_thread, prGlueInfo->prDevHandler, "tx_thread"); g_u4HaltFlag = 0; #if CFG_SUPPORT_ROAMING_ENC /* adjust roaming threshold */ { WLAN_STATUS rStatus = WLAN_STATUS_FAILURE; CMD_ROAMING_INFO_T rRoamingInfo; UINT_32 u4SetInfoLen = 0; prAdapter->fgIsRoamingEncEnabled = TRUE; /* suggestion from Tsaiyuan.Hsu */ kalMemZero(&rRoamingInfo, sizeof(CMD_ROAMING_INFO_T)); rRoamingInfo.fgIsFastRoamingApplied = TRUE; DBGLOG(INIT, TRACE, "Enable roaming enhance function\n"); rStatus = kalIoctl(prGlueInfo, wlanoidSetRoamingInfo, &rRoamingInfo, sizeof(rRoamingInfo), TRUE, TRUE, TRUE, FALSE, &u4SetInfoLen); if (rStatus != WLAN_STATUS_SUCCESS) DBGLOG(INIT, ERROR, "set roaming advance info fail 0x%x\n", rStatus); } #endif /* CFG_SUPPORT_ROAMING_ENC */ #if (CFG_SUPPORT_TXR_ENC == 1) /* adjust tx rate switch threshold */ rlmTxRateEnhanceConfig(prGlueInfo->prAdapter); #endif /* CFG_SUPPORT_TXR_ENC */ /* set MAC address */ { WLAN_STATUS rStatus = WLAN_STATUS_FAILURE; struct sockaddr MacAddr; UINT_32 u4SetInfoLen = 0; kalMemZero(MacAddr.sa_data, sizeof(MacAddr.sa_data)); rStatus = kalIoctl(prGlueInfo, wlanoidQueryCurrentAddr, &MacAddr.sa_data, PARAM_MAC_ADDR_LEN, TRUE, TRUE, TRUE, FALSE, &u4SetInfoLen); if (rStatus != WLAN_STATUS_SUCCESS) { DBGLOG(INIT, WARN, "set MAC addr fail 0x%x\n", rStatus); prGlueInfo->u4ReadyFlag = 0; } else { ether_addr_copy(prGlueInfo->prDevHandler->dev_addr, (const u8 *)&(MacAddr.sa_data)); ether_addr_copy(prGlueInfo->prDevHandler->perm_addr, prGlueInfo->prDevHandler->dev_addr); /* card is ready */ prGlueInfo->u4ReadyFlag = 1; #if CFG_SHOW_MACADDR_SOURCE DBGLOG(INIT, INFO, "MAC address: %pM ", (&MacAddr.sa_data)); #endif } } #if CFG_TCP_IP_CHKSUM_OFFLOAD /* set HW checksum offload */ { WLAN_STATUS rStatus = WLAN_STATUS_FAILURE; UINT_32 u4CSUMFlags = CSUM_OFFLOAD_EN_ALL; UINT_32 u4SetInfoLen = 0; rStatus = kalIoctl(prGlueInfo, wlanoidSetCSUMOffload, (PVOID) &u4CSUMFlags, sizeof(UINT_32), FALSE, FALSE, TRUE, FALSE, &u4SetInfoLen); if (rStatus != WLAN_STATUS_SUCCESS) DBGLOG(INIT, WARN, "set HW checksum offload fail 0x%x\n", rStatus); } #endif /* 4 <3> Register the card */ DBGLOG(INIT, TRACE, "wlanNetRegister...\n"); i4DevIdx = wlanNetRegister(prWdev); if (i4DevIdx < 0) { i4Status = -ENXIO; DBGLOG(INIT, ERROR, "wlanProbe: Cannot register the net_device context to the kernel\n"); eFailReason = NET_REGISTER_FAIL; break; } wlanRegisterNotifier(); /* 4 <6> Initialize /proc filesystem */ #ifdef WLAN_INCLUDE_PROC DBGLOG(INIT, TRACE, "init procfs...\n"); i4Status = procCreateFsEntry(prGlueInfo); if (i4Status < 0) { DBGLOG(INIT, ERROR, "wlanProbe: init procfs failed\n"); eFailReason = PROC_INIT_FAIL; break; } #endif /* WLAN_INCLUDE_PROC */ #if CFG_ENABLE_BT_OVER_WIFI prGlueInfo->rBowInfo.fgIsNetRegistered = FALSE; prGlueInfo->rBowInfo.fgIsRegistered = FALSE; glRegisterAmpc(prGlueInfo); #endif #if CFG_ENABLE_WIFI_DIRECT DBGLOG(INIT, TRACE, "wlanSubModInit...\n"); /* wlan is launched */ prGlueInfo->prAdapter->fgIsWlanLaunched = TRUE; /* if p2p module is inserted, notify tx_thread to init p2p network */ if (rSubModHandler[P2P_MODULE].subModInit) wlanSubModInit(prGlueInfo); /* register set_p2p_mode handler to mtk_wmt_wifi */ register_set_p2p_mode_handler(set_p2p_mode_handler); #endif #if CFG_SPM_WORKAROUND_FOR_HOTSPOT if (glIsChipNeedWakelock(prGlueInfo)) KAL_WAKE_LOCK_INIT(prGlueInfo->prAdapter, &prGlueInfo->prAdapter->rApWakeLock, "WLAN AP"); #endif } while (FALSE); if (i4Status != WLAN_STATUS_SUCCESS) { switch (eFailReason) { case PROC_INIT_FAIL: wlanNetUnregister(prWdev); set_bit(GLUE_FLAG_HALT_BIT, &prGlueInfo->ulFlag); /* wake up main thread */ wake_up_interruptible(&prGlueInfo->waitq); /* wait main thread stops */ wait_for_completion_interruptible(&prGlueInfo->rHaltComp); KAL_WAKE_LOCK_DESTROY(prAdapter, &prAdapter->rTxThreadWakeLock); wlanAdapterStop(prAdapter); glBusFreeIrq(prWdev->netdev, *((P_GLUE_INFO_T *) netdev_priv(prWdev->netdev))); KAL_WAKE_LOCK_DESTROY(prAdapter, &prGlueInfo->rAhbIsrWakeLock); wlanNetDestroy(prWdev); break; case NET_REGISTER_FAIL: set_bit(GLUE_FLAG_HALT_BIT, &prGlueInfo->ulFlag); /* wake up main thread */ wake_up_interruptible(&prGlueInfo->waitq); /* wait main thread stops */ wait_for_completion_interruptible(&prGlueInfo->rHaltComp); KAL_WAKE_LOCK_DESTROY(prAdapter, &prAdapter->rTxThreadWakeLock); wlanAdapterStop(prAdapter); glBusFreeIrq(prWdev->netdev, *((P_GLUE_INFO_T *) netdev_priv(prWdev->netdev))); KAL_WAKE_LOCK_DESTROY(prAdapter, &prGlueInfo->rAhbIsrWakeLock); wlanNetDestroy(prWdev); break; case ADAPTER_START_FAIL: glBusFreeIrq(prWdev->netdev, *((P_GLUE_INFO_T *) netdev_priv(prWdev->netdev))); KAL_WAKE_LOCK_DESTROY(prAdapter, &prGlueInfo->rAhbIsrWakeLock); wlanNetDestroy(prWdev); break; case BUS_SET_IRQ_FAIL: KAL_WAKE_LOCK_DESTROY(prAdapter, &prGlueInfo->rAhbIsrWakeLock); wlanNetDestroy(prWdev); break; case NET_CREATE_FAIL: break; case BUS_INIT_FAIL: break; default: break; } } #if CFG_ENABLE_WIFI_DIRECT { GLUE_SPIN_LOCK_DECLARATION(); GLUE_ACQUIRE_THE_SPIN_LOCK(&g_p2p_lock); g_u4P2PEnding = 0; GLUE_RELEASE_THE_SPIN_LOCK(&g_p2p_lock); } #endif #if CFG_SUPPORT_AGPS_ASSIST if (i4Status == WLAN_STATUS_SUCCESS) kalIndicateAgpsNotify(prAdapter, AGPS_EVENT_WLAN_ON, NULL, 0); #endif #if (CFG_SUPPORT_MET_PROFILING == 1) { int iMetInitRet = WLAN_STATUS_FAILURE; if (i4Status == WLAN_STATUS_SUCCESS) { DBGLOG(INIT, TRACE, "init MET procfs...\n"); iMetInitRet = kalMetInitProcfs(prGlueInfo); if (iMetInitRet < 0) DBGLOG(INIT, ERROR, "wlanProbe: init MET procfs failed\n"); } } #endif if (i4Status == WLAN_STATUS_SUCCESS) { /*Init performance monitor structure */ kalPerMonInit(prGlueInfo); /* probe ok */ DBGLOG(INIT, TRACE, "wlanProbe ok\n"); } else { /* we don't care the return value of mtk_wcn_set_connsys_power_off_flag, * because even this function returns * error, we can also call core dump but only core dump failed. */ if (g_IsNeedDoChipReset) mtk_wcn_set_connsys_power_off_flag(0); /* probe failed */ DBGLOG(INIT, ERROR, "wlanProbe failed\n"); } return i4Status; } /* end of wlanProbe() */ /*----------------------------------------------------------------------------*/ /*! * \brief A method to stop driver operation and release all resources. Following * this call, no frame should go up or down through this interface. * * \return (none) */ /*----------------------------------------------------------------------------*/ static VOID wlanRemove(VOID) { struct net_device *prDev = NULL; P_WLANDEV_INFO_T prWlandevInfo = NULL; P_GLUE_INFO_T prGlueInfo = NULL; P_ADAPTER_T prAdapter = NULL; DBGLOG(INIT, LOUD, "Remove wlan!\n"); /* 4 <0> Sanity check */ ASSERT(u4WlanDevNum <= CFG_MAX_WLAN_DEVICES); if (0 == u4WlanDevNum) { DBGLOG(INIT, ERROR, "0 == u4WlanDevNum\n"); return; } /* unregister set_p2p_mode handler to mtk_wmt_wifi */ register_set_p2p_mode_handler(NULL); prDev = arWlanDevInfo[u4WlanDevNum - 1].prDev; prWlandevInfo = &arWlanDevInfo[u4WlanDevNum - 1]; ASSERT(prDev); if (NULL == prDev) { DBGLOG(INIT, ERROR, "NULL == prDev\n"); return; } prGlueInfo = *((P_GLUE_INFO_T *) netdev_priv(prDev)); ASSERT(prGlueInfo); if (NULL == prGlueInfo) { DBGLOG(INIT, ERROR, "NULL == prGlueInfo\n"); free_netdev(prDev); return; } kalPerMonDestroy(prGlueInfo); /* 4 <3> Remove /proc filesystem. */ #ifdef WLAN_INCLUDE_PROC procRemoveProcfs(); #endif /* WLAN_INCLUDE_PROC */ #if CFG_ENABLE_WIFI_DIRECT /* avoid remove & p2p off command simultaneously */ { BOOLEAN fgIsP2POnOffing; GLUE_SPIN_LOCK_DECLARATION(); GLUE_ACQUIRE_THE_SPIN_LOCK(&g_p2p_lock); g_u4P2PEnding = 1; fgIsP2POnOffing = g_u4P2POnOffing; GLUE_RELEASE_THE_SPIN_LOCK(&g_p2p_lock); DBGLOG(INIT, TRACE, "waiting for fgIsP2POnOffing...\n"); /* History: cannot use down() here, sometimes we cannot come back here */ /* waiting for p2p off command finishes, we cannot skip the remove */ while (1) { if (fgIsP2POnOffing == 0) break; GLUE_ACQUIRE_THE_SPIN_LOCK(&g_p2p_lock); fgIsP2POnOffing = g_u4P2POnOffing; GLUE_RELEASE_THE_SPIN_LOCK(&g_p2p_lock); } } #endif #if CFG_ENABLE_BT_OVER_WIFI if (prGlueInfo->rBowInfo.fgIsNetRegistered) { bowNotifyAllLinkDisconnected(prGlueInfo->prAdapter); /* wait 300ms for BoW module to send deauth */ kalMsleep(300); } #endif /* 4 <1> Stopping handling interrupt and free IRQ */ DBGLOG(INIT, TRACE, "free IRQ...\n"); glBusFreeIrq(prDev, *((P_GLUE_INFO_T *) netdev_priv(prDev))); kalMemSet(&(prGlueInfo->prAdapter->rWlanInfo), 0, sizeof(WLAN_INFO_T)); g_u4HaltFlag = 1; /* before flush_delayed_work() */ if (fgIsWorkMcStart == TRUE) { DBGLOG(INIT, TRACE, "flush_delayed_work...\n"); flush_delayed_work(&workq); /* flush_delayed_work_sync is deprecated */ } flush_delayed_work(&sched_workq); DBGLOG(INIT, INFO, "down g_halt_sem...\n"); down(&g_halt_sem); #if CFG_SPM_WORKAROUND_FOR_HOTSPOT if (glIsChipNeedWakelock(prGlueInfo)) KAL_WAKE_LOCK_DESTROY(prGlueInfo->prAdapter, &prGlueInfo->prAdapter->rApWakeLock); #endif /* flush_delayed_work_sync(&workq); */ /* flush_delayed_work(&workq); */ /* flush_delayed_work_sync is deprecated */ /* 4 <2> Mark HALT, notify main thread to stop, and clean up queued requests */ /* prGlueInfo->u4Flag |= GLUE_FLAG_HALT; */ set_bit(GLUE_FLAG_HALT_BIT, &prGlueInfo->ulFlag); DBGLOG(INIT, TRACE, "waiting for tx_thread stop...\n"); /* wake up main thread */ wake_up_interruptible(&prGlueInfo->waitq); DBGLOG(INIT, TRACE, "wait_for_completion_interruptible\n"); /* wait main thread stops */ wait_for_completion_interruptible(&prGlueInfo->rHaltComp); DBGLOG(INIT, TRACE, "mtk_sdiod stopped\n"); KAL_WAKE_LOCK_DESTROY(prGlueInfo->prAdapter, &prGlueInfo->prAdapter->rTxThreadWakeLock); KAL_WAKE_LOCK_DESTROY(prGlueInfo->prAdapter, &prGlueInfo->rAhbIsrWakeLock); /* prGlueInfo->rHifInfo.main_thread = NULL; */ prGlueInfo->main_thread = NULL; #if CFG_ENABLE_BT_OVER_WIFI if (prGlueInfo->rBowInfo.fgIsRegistered) glUnregisterAmpc(prGlueInfo); #endif #if (CFG_SUPPORT_MET_PROFILING == 1) kalMetRemoveProcfs(); #endif /* Force to do DMA reset */ DBGLOG(INIT, TRACE, "glResetHif\n"); glResetHif(prGlueInfo); /* 4 <4> wlanAdapterStop */ prAdapter = prGlueInfo->prAdapter; #if CFG_SUPPORT_AGPS_ASSIST kalIndicateAgpsNotify(prAdapter, AGPS_EVENT_WLAN_OFF, NULL, 0); #endif wlanAdapterStop(prAdapter); DBGLOG(INIT, TRACE, "Number of Stalled Packets = %d\n", prGlueInfo->i4TxPendingFrameNum); #if CFG_ENABLE_WIFI_DIRECT prGlueInfo->prAdapter->fgIsWlanLaunched = FALSE; if (prGlueInfo->prAdapter->fgIsP2PRegistered) { DBGLOG(INIT, TRACE, "p2pNetUnregister...\n"); #if !CFG_SUPPORT_PERSIST_NETDEV p2pNetUnregister(prGlueInfo, FALSE); #endif DBGLOG(INIT, INFO, "p2pRemove...\n"); p2pRemove(prGlueInfo); } #endif /* 4 <5> Release the Bus */ glBusRelease(prDev); up(&g_halt_sem); wlanDebugUninit(); /* 4 <6> Unregister the card */ wlanNetUnregister(prDev->ieee80211_ptr); /* 4 <7> Destroy the device */ wlanNetDestroy(prDev->ieee80211_ptr); prDev = NULL; DBGLOG(INIT, LOUD, "wlanUnregisterNotifier...\n"); wlanUnregisterNotifier(); DBGLOG(INIT, INFO, "wlanRemove ok\n"); } /* end of wlanRemove() */ /*----------------------------------------------------------------------------*/ /*! * \brief Driver entry point when the driver is configured as a Linux Module, and * is called once at module load time, by the user-level modutils * application: insmod or modprobe. * * \retval 0 Success */ /*----------------------------------------------------------------------------*/ /* 1 Module Entry Point */ static int initWlan(void) { int ret = 0, i; #if DBG for (i = 0; i < DBG_MODULE_NUM; i++) aucDebugModule[i] = DBG_CLASS_MASK; /* enable all */ #else /* Initial debug level is D1 */ for (i = 0; i < DBG_MODULE_NUM; i++) aucDebugModule[i] = DBG_CLASS_ERROR | DBG_CLASS_WARN | DBG_CLASS_INFO | DBG_CLASS_STATE; #endif /* DBG */ DBGLOG(INIT, INFO, "initWlan\n"); spin_lock_init(&g_p2p_lock); /* memory pre-allocation */ kalInitIOBuffer(); procInitFs(); createWirelessDevice(); if (gprWdev) glP2pCreateWirelessDevice((P_GLUE_INFO_T) wiphy_priv(gprWdev->wiphy)); ret = ((glRegisterBus(wlanProbe, wlanRemove) == WLAN_STATUS_SUCCESS) ? 0 : -EIO); if (ret == -EIO) { kalUninitIOBuffer(); return ret; } #if (CFG_CHIP_RESET_SUPPORT) glResetInit(); #endif /* register set_dbg_level handler to mtk_wmt_wifi */ register_set_dbg_level_handler(set_dbg_level_handler); /* Register framebuffer notifier client*/ kalFbNotifierReg((P_GLUE_INFO_T) wiphy_priv(gprWdev->wiphy)); /* Set the initial DEBUG CLASS of each module */ return ret; } /* end of initWlan() */ /*----------------------------------------------------------------------------*/ /*! * \brief Driver exit point when the driver as a Linux Module is removed. Called * at module unload time, by the user level modutils application: rmmod. * This is our last chance to clean up after ourselves. * * \return (none) */ /*----------------------------------------------------------------------------*/ /* 1 Module Leave Point */ static VOID exitWlan(void) { DBGLOG(INIT, INFO, "exitWlan\n"); /* Unregister framebuffer notifier client*/ kalFbNotifierUnReg(); /* unregister set_dbg_level handler to mtk_wmt_wifi */ register_set_dbg_level_handler(NULL); #if CFG_CHIP_RESET_SUPPORT glResetUninit(); #endif destroyWirelessDevice(); glP2pDestroyWirelessDevice(); glUnregisterBus(wlanRemove); /* free pre-allocated memory */ kalUninitIOBuffer(); DBGLOG(INIT, INFO, "exitWlan\n"); procUninitProcFs(); } /* end of exitWlan() */ #ifdef MTK_WCN_BUILT_IN_DRIVER int mtk_wcn_wlan_gen2_init(void) { return initWlan(); } EXPORT_SYMBOL(mtk_wcn_wlan_gen2_init); void mtk_wcn_wlan_gen2_exit(void) { return exitWlan(); } EXPORT_SYMBOL(mtk_wcn_wlan_gen2_exit); #else module_init(initWlan); module_exit(exitWlan); #endif
bq/aquaris-M4.5
drivers/misc/mediatek/connectivity/wlan/gen2/os/linux/gl_init.c
C
gpl-2.0
114,508
/* * linux/fs/super.c * * Copyright (C) 1991, 1992 Linus Torvalds * * super.c contains code to handle: - mount structures * - super-block tables * - filesystem drivers list * - mount system call * - umount system call * - ustat system call * * GK 2/5/95 - Changed to support mounting the root fs via NFS * * Added kerneld support: Jacques Gelinas and Bjorn Ekwall * Added change_root: Werner Almesberger & Hans Lermen, Feb '96 * Added options to /proc/mounts: * Torbjörn Lindh (torbjorn.lindh@gopta.se), April 14, 1996. * Added devfs support: Richard Gooch <rgooch@atnf.csiro.au>, 13-JAN-1998 * Heavily rewritten for 'one fs - one tree' dcache architecture. AV, Mar 2000 */ #include <linux/module.h> #include <linux/slab.h> #include <linux/acct.h> #include <linux/blkdev.h> #include <linux/mount.h> #include <linux/security.h> #include <linux/writeback.h> /* for the emergency remount stuff */ #include <linux/idr.h> #include <linux/mutex.h> #include <linux/backing-dev.h> #include <linux/rculist_bl.h> #include <linux/cleancache.h> #include <linux/lockdep.h> #include "internal.h" LIST_HEAD(super_blocks); DEFINE_SPINLOCK(sb_lock); static struct lock_class_key sb_writers_key[SB_FREEZE_LEVELS-1]; static int init_sb_writers(struct super_block *s, int level, char *lockname) { struct sb_writers_level *sl = &s->s_writers[level-1]; int err; err = percpu_counter_init(&sl->counter, 0); if (err < 0) return err; init_waitqueue_head(&sl->wait); lockdep_init_map(&sl->lock_map, lockname, &sb_writers_key[level-1], 0); return 0; } static void destroy_sb_writers(struct super_block *s, int level) { percpu_counter_destroy(&s->s_writers[level-1].counter); } /** * alloc_super - create new superblock * @type: filesystem type superblock should belong to * * Allocates and initializes a new &struct super_block. alloc_super() * returns a pointer new superblock or %NULL if allocation had failed. */ static struct super_block *alloc_super(struct file_system_type *type) { struct super_block *s = kzalloc(sizeof(struct super_block), GFP_USER); static const struct super_operations default_op; if (s) { if (security_sb_alloc(s)) { /* * We cannot call security_sb_free() without * security_sb_alloc() succeeding. So bail out manually */ kfree(s); s = NULL; goto out; } #ifdef CONFIG_SMP s->s_files = alloc_percpu(struct list_head); if (!s->s_files) goto err_out; else { int i; for_each_possible_cpu(i) INIT_LIST_HEAD(per_cpu_ptr(s->s_files, i)); } #else INIT_LIST_HEAD(&s->s_files); #endif if (init_sb_writers(s, SB_FREEZE_WRITE, "sb_writers_write")) goto err_out; if (init_sb_writers(s, SB_FREEZE_TRANS, "sb_writers_trans")) goto err_out; s->s_bdi = &default_backing_dev_info; INIT_LIST_HEAD(&s->s_instances); INIT_HLIST_BL_HEAD(&s->s_anon); INIT_LIST_HEAD(&s->s_inodes); INIT_LIST_HEAD(&s->s_dentry_lru); init_rwsem(&s->s_umount); mutex_init(&s->s_lock); lockdep_set_class(&s->s_umount, &type->s_umount_key); /* * The locking rules for s_lock are up to the * filesystem. For example ext3fs has different * lock ordering than usbfs: */ lockdep_set_class(&s->s_lock, &type->s_lock_key); /* * sget() can have s_umount recursion. * * When it cannot find a suitable sb, it allocates a new * one (this one), and tries again to find a suitable old * one. * * In case that succeeds, it will acquire the s_umount * lock of the old one. Since these are clearly distrinct * locks, and this object isn't exposed yet, there's no * risk of deadlocks. * * Annotate this by putting this lock in a different * subclass. */ down_write_nested(&s->s_umount, SINGLE_DEPTH_NESTING); s->s_count = 1; atomic_set(&s->s_active, 1); mutex_init(&s->s_vfs_rename_mutex); lockdep_set_class(&s->s_vfs_rename_mutex, &type->s_vfs_rename_key); mutex_init(&s->s_dquot.dqio_mutex); mutex_init(&s->s_dquot.dqonoff_mutex); init_rwsem(&s->s_dquot.dqptr_sem); init_waitqueue_head(&s->s_wait_unfrozen); s->s_maxbytes = MAX_NON_LFS; s->s_op = &default_op; s->s_time_gran = 1000000000; s->cleancache_poolid = -1; } out: return s; err_out: security_sb_free(s); #ifdef CONFIG_SMP if (s->s_files) free_percpu(s->s_files); #endif destroy_sb_writers(s, SB_FREEZE_WRITE); destroy_sb_writers(s, SB_FREEZE_TRANS); kfree(s); s = NULL; goto out; } /** * destroy_super - frees a superblock * @s: superblock to free * * Frees a superblock. */ static inline void destroy_super(struct super_block *s) { #ifdef CONFIG_SMP free_percpu(s->s_files); #endif security_sb_free(s); kfree(s->s_subtype); kfree(s->s_options); kfree(s); } /* Superblock refcounting */ /* * Drop a superblock's refcount. The caller must hold sb_lock. */ void __put_super(struct super_block *sb) { if (!--sb->s_count) { list_del_init(&sb->s_list); destroy_super(sb); } } /** * put_super - drop a temporary reference to superblock * @sb: superblock in question * * Drops a temporary reference, frees superblock if there's no * references left. */ void put_super(struct super_block *sb) { spin_lock(&sb_lock); __put_super(sb); spin_unlock(&sb_lock); } /** * deactivate_locked_super - drop an active reference to superblock * @s: superblock to deactivate * * Drops an active reference to superblock, converting it into a temprory * one if there is no other active references left. In that case we * tell fs driver to shut it down and drop the temporary reference we * had just acquired. * * Caller holds exclusive lock on superblock; that lock is released. */ void deactivate_locked_super(struct super_block *s) { struct file_system_type *fs = s->s_type; if (atomic_dec_and_test(&s->s_active)) { cleancache_flush_fs(s); fs->kill_sb(s); /* * We need to call rcu_barrier so all the delayed rcu free * inodes are flushed before we release the fs module. */ rcu_barrier(); put_filesystem(fs); put_super(s); } else { up_write(&s->s_umount); } } EXPORT_SYMBOL(deactivate_locked_super); /** * deactivate_super - drop an active reference to superblock * @s: superblock to deactivate * * Variant of deactivate_locked_super(), except that superblock is *not* * locked by caller. If we are going to drop the final active reference, * lock will be acquired prior to that. */ void deactivate_super(struct super_block *s) { if (!atomic_add_unless(&s->s_active, -1, 1)) { down_write(&s->s_umount); deactivate_locked_super(s); } } EXPORT_SYMBOL(deactivate_super); /** * grab_super - acquire an active reference * @s: reference we are trying to make active * * Tries to acquire an active reference. grab_super() is used when we * had just found a superblock in super_blocks or fs_type->fs_supers * and want to turn it into a full-blown active reference. grab_super() * is called with sb_lock held and drops it. Returns 1 in case of * success, 0 if we had failed (superblock contents was already dead or * dying when grab_super() had been called). */ static int grab_super(struct super_block *s) __releases(sb_lock) { if (atomic_inc_not_zero(&s->s_active)) { spin_unlock(&sb_lock); return 1; } /* it's going away */ s->s_count++; spin_unlock(&sb_lock); /* wait for it to die */ down_write(&s->s_umount); up_write(&s->s_umount); put_super(s); return 0; } /* * grab_super_passive - acquire a passive reference * @s: reference we are trying to grab * * Tries to acquire a passive reference. This is used in places where we * cannot take an active reference but we need to ensure that the * superblock does not go away while we are working on it. It returns * false if a reference was not gained, and returns true with the s_umount * lock held in read mode if a reference is gained. On successful return, * the caller must drop the s_umount lock and the passive reference when * done. */ bool grab_super_passive(struct super_block *sb) { spin_lock(&sb_lock); if (list_empty(&sb->s_instances)) { spin_unlock(&sb_lock); return false; } sb->s_count++; spin_unlock(&sb_lock); if (down_read_trylock(&sb->s_umount)) { if (sb->s_root) return true; up_read(&sb->s_umount); } put_super(sb); return false; } /* * Superblock locking. We really ought to get rid of these two. */ void lock_super(struct super_block * sb) { mutex_lock(&sb->s_lock); } void unlock_super(struct super_block * sb) { mutex_unlock(&sb->s_lock); } EXPORT_SYMBOL(lock_super); EXPORT_SYMBOL(unlock_super); /** * generic_shutdown_super - common helper for ->kill_sb() * @sb: superblock to kill * * generic_shutdown_super() does all fs-independent work on superblock * shutdown. Typical ->kill_sb() should pick all fs-specific objects * that need destruction out of superblock, call generic_shutdown_super() * and release aforementioned objects. Note: dentries and inodes _are_ * taken care of and do not need specific handling. * * Upon calling this function, the filesystem may no longer alter or * rearrange the set of dentries belonging to this super_block, nor may it * change the attachments of dentries to inodes. */ void generic_shutdown_super(struct super_block *sb) { const struct super_operations *sop = sb->s_op; if (sb->s_root) { shrink_dcache_for_umount(sb); sync_filesystem(sb); get_fs_excl(); sb->s_flags &= ~MS_ACTIVE; fsnotify_unmount_inodes(&sb->s_inodes); evict_inodes(sb); if (sop->put_super) sop->put_super(sb); if (!list_empty(&sb->s_inodes)) { printk("VFS: Busy inodes after unmount of %s. " "Self-destruct in 5 seconds. Have a nice day...\n", sb->s_id); } put_fs_excl(); } spin_lock(&sb_lock); /* should be initialized for __put_super_and_need_restart() */ list_del_init(&sb->s_instances); spin_unlock(&sb_lock); up_write(&sb->s_umount); } EXPORT_SYMBOL(generic_shutdown_super); /** * sget - find or create a superblock * @type: filesystem type superblock should belong to * @test: comparison callback * @set: setup callback * @data: argument to each of them */ struct super_block *sget(struct file_system_type *type, int (*test)(struct super_block *,void *), int (*set)(struct super_block *,void *), void *data) { struct super_block *s = NULL; struct super_block *old; int err; retry: spin_lock(&sb_lock); if (test) { list_for_each_entry(old, &type->fs_supers, s_instances) { if (!test(old, data)) continue; if (!grab_super(old)) goto retry; if (s) { up_write(&s->s_umount); destroy_super(s); s = NULL; } down_write(&old->s_umount); if (unlikely(!(old->s_flags & MS_BORN))) { deactivate_locked_super(old); goto retry; } return old; } } if (!s) { spin_unlock(&sb_lock); s = alloc_super(type); if (!s) return ERR_PTR(-ENOMEM); goto retry; } err = set(s, data); if (err) { spin_unlock(&sb_lock); up_write(&s->s_umount); destroy_super(s); return ERR_PTR(err); } s->s_type = type; strlcpy(s->s_id, type->name, sizeof(s->s_id)); list_add_tail(&s->s_list, &super_blocks); list_add(&s->s_instances, &type->fs_supers); spin_unlock(&sb_lock); get_filesystem(type); return s; } EXPORT_SYMBOL(sget); void drop_super(struct super_block *sb) { up_read(&sb->s_umount); put_super(sb); } EXPORT_SYMBOL(drop_super); /** * sync_supers - helper for periodic superblock writeback * * Call the write_super method if present on all dirty superblocks in * the system. This is for the periodic writeback used by most older * filesystems. For data integrity superblock writeback use * sync_filesystems() instead. * * Note: check the dirty flag before waiting, so we don't * hold up the sync while mounting a device. (The newly * mounted device won't need syncing.) */ void sync_supers(void) { struct super_block *sb, *p = NULL; spin_lock(&sb_lock); list_for_each_entry(sb, &super_blocks, s_list) { if (list_empty(&sb->s_instances)) continue; if (sb->s_op->write_super && sb->s_dirt) { sb->s_count++; spin_unlock(&sb_lock); down_read(&sb->s_umount); if (sb->s_root && sb->s_dirt) sb->s_op->write_super(sb); up_read(&sb->s_umount); spin_lock(&sb_lock); if (p) __put_super(p); p = sb; } } if (p) __put_super(p); spin_unlock(&sb_lock); } /** * iterate_supers - call function for all active superblocks * @f: function to call * @arg: argument to pass to it * * Scans the superblock list and calls given function, passing it * locked superblock and given argument. */ void iterate_supers(void (*f)(struct super_block *, void *), void *arg) { struct super_block *sb, *p = NULL; spin_lock(&sb_lock); list_for_each_entry(sb, &super_blocks, s_list) { if (list_empty(&sb->s_instances)) continue; sb->s_count++; spin_unlock(&sb_lock); down_read(&sb->s_umount); if (sb->s_root) f(sb, arg); up_read(&sb->s_umount); spin_lock(&sb_lock); if (p) __put_super(p); p = sb; } if (p) __put_super(p); spin_unlock(&sb_lock); } /** * get_super - get the superblock of a device * @bdev: device to get the superblock for * * Scans the superblock list and finds the superblock of the file system * mounted on the device given. %NULL is returned if no match is found. */ struct super_block *get_super(struct block_device *bdev) { struct super_block *sb; if (!bdev) return NULL; spin_lock(&sb_lock); rescan: list_for_each_entry(sb, &super_blocks, s_list) { if (list_empty(&sb->s_instances)) continue; if (sb->s_bdev == bdev) { sb->s_count++; spin_unlock(&sb_lock); down_read(&sb->s_umount); /* still alive? */ if (sb->s_root) return sb; up_read(&sb->s_umount); /* nope, got unmounted */ spin_lock(&sb_lock); __put_super(sb); goto rescan; } } spin_unlock(&sb_lock); return NULL; } EXPORT_SYMBOL(get_super); /** * get_active_super - get an active reference to the superblock of a device * @bdev: device to get the superblock for * * Scans the superblock list and finds the superblock of the file system * mounted on the device given. Returns the superblock with an active * reference or %NULL if none was found. */ struct super_block *get_active_super(struct block_device *bdev) { struct super_block *sb; if (!bdev) return NULL; restart: spin_lock(&sb_lock); list_for_each_entry(sb, &super_blocks, s_list) { if (list_empty(&sb->s_instances)) continue; if (sb->s_bdev == bdev) { if (grab_super(sb)) /* drops sb_lock */ return sb; else goto restart; } } spin_unlock(&sb_lock); return NULL; } struct super_block *user_get_super(dev_t dev) { struct super_block *sb; spin_lock(&sb_lock); rescan: list_for_each_entry(sb, &super_blocks, s_list) { if (list_empty(&sb->s_instances)) continue; if (sb->s_dev == dev) { sb->s_count++; spin_unlock(&sb_lock); down_read(&sb->s_umount); /* still alive? */ if (sb->s_root) return sb; up_read(&sb->s_umount); /* nope, got unmounted */ spin_lock(&sb_lock); __put_super(sb); goto rescan; } } spin_unlock(&sb_lock); return NULL; } /** * do_remount_sb - asks filesystem to change mount options. * @sb: superblock in question * @flags: numeric part of options * @data: the rest of options * @force: whether or not to force the change * * Alters the mount options of a mounted file system. */ int do_remount_sb(struct super_block *sb, int flags, void *data, int force) { int retval; int remount_ro; if (sb->s_frozen != SB_UNFROZEN) return -EBUSY; #ifdef CONFIG_BLOCK if (!(flags & MS_RDONLY) && bdev_read_only(sb->s_bdev)) return -EACCES; #endif if (flags & MS_RDONLY) acct_auto_close(sb); shrink_dcache_sb(sb); sync_filesystem(sb); remount_ro = (flags & MS_RDONLY) && !(sb->s_flags & MS_RDONLY); /* If we are remounting RDONLY and current sb is read/write, make sure there are no rw files opened */ if (remount_ro) { if (force) mark_files_ro(sb); else if (!fs_may_remount_ro(sb)) return -EBUSY; } if (sb->s_op->remount_fs) { retval = sb->s_op->remount_fs(sb, &flags, data); if (retval) return retval; } sb->s_flags = (sb->s_flags & ~MS_RMT_MASK) | (flags & MS_RMT_MASK); /* * Some filesystems modify their metadata via some other path than the * bdev buffer cache (eg. use a private mapping, or directories in * pagecache, etc). Also file data modifications go via their own * mappings. So If we try to mount readonly then copy the filesystem * from bdev, we could get stale data, so invalidate it to give a best * effort at coherency. */ if (remount_ro && sb->s_bdev) invalidate_bdev(sb->s_bdev); return 0; } static void do_emergency_remount(struct work_struct *work) { struct super_block *sb, *p = NULL; spin_lock(&sb_lock); list_for_each_entry(sb, &super_blocks, s_list) { if (list_empty(&sb->s_instances)) continue; sb->s_count++; spin_unlock(&sb_lock); down_write(&sb->s_umount); if (sb->s_root && sb->s_bdev && !(sb->s_flags & MS_RDONLY)) { /* * What lock protects sb->s_flags?? */ do_remount_sb(sb, MS_RDONLY, NULL, 1); } up_write(&sb->s_umount); spin_lock(&sb_lock); if (p) __put_super(p); p = sb; } if (p) __put_super(p); spin_unlock(&sb_lock); kfree(work); printk("Emergency Remount complete\n"); } void emergency_remount(void) { struct work_struct *work; work = kmalloc(sizeof(*work), GFP_ATOMIC); if (work) { INIT_WORK(work, do_emergency_remount); schedule_work(work); } } /* * Unnamed block devices are dummy devices used by virtual * filesystems which don't use real block-devices. -- jrs */ static DEFINE_IDA(unnamed_dev_ida); static DEFINE_SPINLOCK(unnamed_dev_lock);/* protects the above */ static int unnamed_dev_start = 0; /* don't bother trying below it */ int set_anon_super(struct super_block *s, void *data) { int dev; int error; retry: if (ida_pre_get(&unnamed_dev_ida, GFP_ATOMIC) == 0) return -ENOMEM; spin_lock(&unnamed_dev_lock); error = ida_get_new_above(&unnamed_dev_ida, unnamed_dev_start, &dev); if (!error) unnamed_dev_start = dev + 1; spin_unlock(&unnamed_dev_lock); if (error == -EAGAIN) /* We raced and lost with another CPU. */ goto retry; else if (error) return -EAGAIN; if ((dev & MAX_ID_MASK) == (1 << MINORBITS)) { spin_lock(&unnamed_dev_lock); ida_remove(&unnamed_dev_ida, dev); if (unnamed_dev_start > dev) unnamed_dev_start = dev; spin_unlock(&unnamed_dev_lock); return -EMFILE; } s->s_dev = MKDEV(0, dev & MINORMASK); s->s_bdi = &noop_backing_dev_info; return 0; } EXPORT_SYMBOL(set_anon_super); void kill_anon_super(struct super_block *sb) { int slot = MINOR(sb->s_dev); generic_shutdown_super(sb); spin_lock(&unnamed_dev_lock); ida_remove(&unnamed_dev_ida, slot); if (slot < unnamed_dev_start) unnamed_dev_start = slot; spin_unlock(&unnamed_dev_lock); } EXPORT_SYMBOL(kill_anon_super); void kill_litter_super(struct super_block *sb) { if (sb->s_root) d_genocide(sb->s_root); kill_anon_super(sb); } EXPORT_SYMBOL(kill_litter_super); static int ns_test_super(struct super_block *sb, void *data) { return sb->s_fs_info == data; } static int ns_set_super(struct super_block *sb, void *data) { sb->s_fs_info = data; return set_anon_super(sb, NULL); } struct dentry *mount_ns(struct file_system_type *fs_type, int flags, void *data, int (*fill_super)(struct super_block *, void *, int)) { struct super_block *sb; sb = sget(fs_type, ns_test_super, ns_set_super, data); if (IS_ERR(sb)) return ERR_CAST(sb); if (!sb->s_root) { int err; sb->s_flags = flags; err = fill_super(sb, data, flags & MS_SILENT ? 1 : 0); if (err) { deactivate_locked_super(sb); return ERR_PTR(err); } sb->s_flags |= MS_ACTIVE; } return dget(sb->s_root); } EXPORT_SYMBOL(mount_ns); #ifdef CONFIG_BLOCK static int set_bdev_super(struct super_block *s, void *data) { s->s_bdev = data; s->s_dev = s->s_bdev->bd_dev; /* * We set the bdi here to the queue backing, file systems can * overwrite this in ->fill_super() */ s->s_bdi = &bdev_get_queue(s->s_bdev)->backing_dev_info; return 0; } static int test_bdev_super(struct super_block *s, void *data) { return (void *)s->s_bdev == data; } struct dentry *mount_bdev(struct file_system_type *fs_type, int flags, const char *dev_name, void *data, int (*fill_super)(struct super_block *, void *, int)) { struct block_device *bdev; struct super_block *s; fmode_t mode = FMODE_READ | FMODE_EXCL; int error = 0; if (!(flags & MS_RDONLY)) mode |= FMODE_WRITE; bdev = blkdev_get_by_path(dev_name, mode, fs_type); if (IS_ERR(bdev)) return ERR_CAST(bdev); /* * once the super is inserted into the list by sget, s_umount * will protect the lockfs code from trying to start a snapshot * while we are mounting */ mutex_lock(&bdev->bd_fsfreeze_mutex); if (bdev->bd_fsfreeze_count > 0) { mutex_unlock(&bdev->bd_fsfreeze_mutex); error = -EBUSY; goto error_bdev; } s = sget(fs_type, test_bdev_super, set_bdev_super, bdev); mutex_unlock(&bdev->bd_fsfreeze_mutex); if (IS_ERR(s)) goto error_s; if (s->s_root) { if ((flags ^ s->s_flags) & MS_RDONLY) { deactivate_locked_super(s); error = -EBUSY; goto error_bdev; } /* * s_umount nests inside bd_mutex during * __invalidate_device(). blkdev_put() acquires * bd_mutex and can't be called under s_umount. Drop * s_umount temporarily. This is safe as we're * holding an active reference. */ up_write(&s->s_umount); blkdev_put(bdev, mode); down_write(&s->s_umount); } else { char b[BDEVNAME_SIZE]; s->s_flags = flags; s->s_mode = mode; strlcpy(s->s_id, bdevname(bdev, b), sizeof(s->s_id)); sb_set_blocksize(s, block_size(bdev)); error = fill_super(s, data, flags & MS_SILENT ? 1 : 0); if (error) { deactivate_locked_super(s); goto error; } s->s_flags |= MS_ACTIVE; bdev->bd_super = s; } return dget(s->s_root); error_s: error = PTR_ERR(s); error_bdev: blkdev_put(bdev, mode); error: return ERR_PTR(error); } EXPORT_SYMBOL(mount_bdev); void kill_block_super(struct super_block *sb) { struct block_device *bdev = sb->s_bdev; fmode_t mode = sb->s_mode; bdev->bd_super = NULL; generic_shutdown_super(sb); sync_blockdev(bdev); WARN_ON_ONCE(!(mode & FMODE_EXCL)); blkdev_put(bdev, mode | FMODE_EXCL); } EXPORT_SYMBOL(kill_block_super); #endif struct dentry *mount_nodev(struct file_system_type *fs_type, int flags, void *data, int (*fill_super)(struct super_block *, void *, int)) { int error; struct super_block *s = sget(fs_type, NULL, set_anon_super, NULL); if (IS_ERR(s)) return ERR_CAST(s); s->s_flags = flags; error = fill_super(s, data, flags & MS_SILENT ? 1 : 0); if (error) { deactivate_locked_super(s); return ERR_PTR(error); } s->s_flags |= MS_ACTIVE; return dget(s->s_root); } EXPORT_SYMBOL(mount_nodev); static int compare_single(struct super_block *s, void *p) { return 1; } struct dentry *mount_single(struct file_system_type *fs_type, int flags, void *data, int (*fill_super)(struct super_block *, void *, int)) { struct super_block *s; int error; s = sget(fs_type, compare_single, set_anon_super, NULL); if (IS_ERR(s)) return ERR_CAST(s); if (!s->s_root) { s->s_flags = flags; error = fill_super(s, data, flags & MS_SILENT ? 1 : 0); if (error) { deactivate_locked_super(s); return ERR_PTR(error); } s->s_flags |= MS_ACTIVE; } else { do_remount_sb(s, flags, data, 0); } return dget(s->s_root); } EXPORT_SYMBOL(mount_single); struct dentry * mount_fs(struct file_system_type *type, int flags, const char *name, void *data) { struct dentry *root; struct super_block *sb; char *secdata = NULL; int error = -ENOMEM; if (data && !(type->fs_flags & FS_BINARY_MOUNTDATA)) { secdata = alloc_secdata(); if (!secdata) goto out; error = security_sb_copy_data(data, secdata); if (error) goto out_free_secdata; } root = type->mount(type, flags, name, data); if (IS_ERR(root)) { error = PTR_ERR(root); goto out_free_secdata; } sb = root->d_sb; BUG_ON(!sb); WARN_ON(!sb->s_bdi); WARN_ON(sb->s_bdi == &default_backing_dev_info); sb->s_flags |= MS_BORN; error = security_sb_kern_mount(sb, flags, secdata); if (error) goto out_sb; /* * filesystems should never set s_maxbytes larger than MAX_LFS_FILESIZE * but s_maxbytes was an unsigned long long for many releases. Throw * this warning for a little while to try and catch filesystems that * violate this rule. */ WARN((sb->s_maxbytes < 0), "%s set sb->s_maxbytes to " "negative value (%lld)\n", type->name, sb->s_maxbytes); up_write(&sb->s_umount); free_secdata(secdata); return root; out_sb: dput(root); deactivate_locked_super(sb); out_free_secdata: free_secdata(secdata); out: return ERR_PTR(error); } /** * sb_end_write - drop write access to a superblock * @sb: the super we wrote to * @level: the lowest level of freezing which we blocked * * Decrement number of writers to the filesystem preventing freezing of * given level. Wake up possible waiters wanting to freeze the filesystem. */ void sb_end_write(struct super_block *sb, int level) { struct sb_writers_level *sl = &sb->s_writers[level-1]; percpu_counter_dec(&sl->counter); /* * Make sure s_writers are updated before we wake up waiters in * freeze_super(). */ smp_mb(); if (waitqueue_active(&sl->wait)) wake_up(&sl->wait); rwsem_release(&sl->lock_map, 1, _RET_IP_); } EXPORT_SYMBOL(sb_end_write); /** * sb_start_write - get write access to a superblock * @sb: the super we write to * @level: the lowest level of freezing which we block * * When a process wants to write data to a filesystem (i.e. dirty a page), it * should embed the operation in a sb_start_write() - sb_end_write() pair to * get exclusion against filesystem freezing. This function increments number * of writers preventing freezing of given level to proceed. If the file * system is already frozen it waits until it is thawed. * * The lock orderding constraints of sb_start_write() for level SB_FREEZE_WRITE * are following: * mmap_sem (page-fault) * -> s_writers (block_page_mkwrite or equivalent) * * i_mutex (do_truncate, __generic_file_aio_write) * -> s_writers * * s_umount (freeze_super) * -> s_writers * * For level SB_FREEZE_TRANS lock constraints are rather file system dependent, * in most cases equivalent to constraints for starting a fs transaction. */ void sb_start_write(struct super_block *sb, int level) { retry: rwsem_acquire_read(&sb->s_writers[level-1].lock_map, 0, 0, _RET_IP_); vfs_check_frozen(sb, level); percpu_counter_inc(&sb->s_writers[level-1].counter); /* * Make sure s_writers are updated before we check s_frozen. * freeze_super() first sets s_frozen and then checks s_writers. */ smp_mb(); if (sb->s_frozen >= level) { sb_end_write(sb, level); goto retry; } } EXPORT_SYMBOL(sb_start_write); /** * sb_dup_write - get write access to a superblock without blocking * @sb: the super we write to * @level: the lowest level of freezing which we block * * This function is like sb_start_write() only that it does not check s_frozen * in the superblock. The caller can call this function only when it already * holds write access to the superblock at this level (i.e., called * sb_start_write(sb, level) previously). */ void sb_dup_write(struct super_block *sb, int level) { /* * Trick lockdep into acquiring read lock again without complaining * about lock recursion */ rwsem_acquire_read(&sb->s_writers[level-1].lock_map, 0, 1, _RET_IP_); percpu_counter_inc(&sb->s_writers[level-1].counter); } EXPORT_SYMBOL(sb_dup_write); /** * sb_wait_write - wait until all writers at given level finish * @sb: the super for which we wait * @level: the level at which we wait for writers * * This function waits until there are no writers at given level. Caller * of this function should make sure there can be no new writers at required * level before calling this function. Otherwise this function can livelock. */ void sb_wait_write(struct super_block *sb, int level) { s64 writers; struct sb_writers_level *sl = &sb->s_writers[level-1]; do { DEFINE_WAIT(wait); /* * We use a barrier in prepare_to_wait() to separate setting * of s_frozen and checking of s_writers */ prepare_to_wait(&sl->wait, &wait, TASK_UNINTERRUPTIBLE); writers = percpu_counter_sum(&sl->counter); if (writers) schedule(); finish_wait(&sl->wait, &wait); } while (writers); } EXPORT_SYMBOL(sb_wait_write); /* * Freeze superblock to given level, wait for writers at given level * to finish. */ static void sb_freeze_to_level(struct super_block *sb, int level) { sb->s_frozen = level; /* * We just cycle-through lockdep here so that it does not complain * about returning with lock to userspace */ rwsem_acquire(&sb->s_writers[level-1].lock_map, 0, 0, _THIS_IP_); rwsem_release(&sb->s_writers[level-1].lock_map, 1, _THIS_IP_); /* * Now wait for writers to finish. As s_frozen is already set to * 'level' we are guaranteed there are no new writers at given level. */ sb_wait_write(sb, level); } /** * freeze_super - lock the filesystem and force it into a consistent state * @sb: the super to lock * * Syncs the super to make sure the filesystem is consistent and calls the fs's * freeze_fs. Subsequent calls to this without first thawing the fs will return * -EBUSY. */ int freeze_super(struct super_block *sb) { int ret; atomic_inc(&sb->s_active); down_write(&sb->s_umount); if (sb->s_frozen) { deactivate_locked_super(sb); return -EBUSY; } if (sb->s_flags & MS_RDONLY) { sb->s_frozen = SB_FREEZE_TRANS; smp_wmb(); up_write(&sb->s_umount); return 0; } sb_freeze_to_level(sb, SB_FREEZE_WRITE); sync_filesystem(sb); sb_freeze_to_level(sb, SB_FREEZE_TRANS); sync_blockdev(sb->s_bdev); if (sb->s_op->freeze_fs) { ret = sb->s_op->freeze_fs(sb); if (ret) { printk(KERN_ERR "VFS:Filesystem freeze failed\n"); sb->s_frozen = SB_UNFROZEN; deactivate_locked_super(sb); return ret; } } up_write(&sb->s_umount); return 0; } EXPORT_SYMBOL(freeze_super); /** * thaw_super -- unlock filesystem * @sb: the super to thaw * * Unlocks the filesystem and marks it writeable again after freeze_super(). */ int thaw_super(struct super_block *sb) { int error; down_write(&sb->s_umount); if (sb->s_frozen == SB_UNFROZEN) { up_write(&sb->s_umount); return -EINVAL; } if (sb->s_flags & MS_RDONLY) goto out; if (sb->s_op->unfreeze_fs) { error = sb->s_op->unfreeze_fs(sb); if (error) { printk(KERN_ERR "VFS:Filesystem thaw failed\n"); sb->s_frozen = SB_FREEZE_TRANS; up_write(&sb->s_umount); return error; } } out: sb->s_frozen = SB_UNFROZEN; smp_wmb(); wake_up(&sb->s_wait_unfrozen); deactivate_locked_super(sb); return 0; } EXPORT_SYMBOL(thaw_super);
shankarathi07/linux_samsung_ics
fs/super.c
C
gpl-2.0
31,275
#include "cmdq_platform.h" #include "cmdq_core.h" #include "cmdq_reg.h" #include <linux/vmalloc.h> #include <mach/mt_clkmgr.h> #include <linux/seq_file.h> #include "smi_debug.h" #include "m4u.h" #define MMSYS_CONFIG_BASE cmdq_dev_get_module_base_VA_MMSYS_CONFIG() typedef struct RegDef { int offset; const char *name; } RegDef; const bool cmdq_core_support_sync_non_suspendable(void) { return true; } const bool cmdq_core_support_wait_and_receive_event_in_same_tick(void) { return true; } const uint32_t cmdq_core_get_subsys_LSB_in_argA(void) { return 16; } int32_t cmdq_subsys_from_phys_addr(uint32_t physAddr) { const int32_t msb = (physAddr & 0x0FFFF0000) >> 16; #undef DECLARE_CMDQ_SUBSYS #define DECLARE_CMDQ_SUBSYS(addr, id, grp, base) case addr: return id; switch (msb) { #include "cmdq_subsys.h" } CMDQ_ERR("unrecognized subsys, msb=0x%04x, physAddr:0x%08x\n", msb, physAddr); return -1; #undef DECLARE_CMDQ_SUBSYS } void cmdq_core_fix_command_desc_scenario_for_user_space_request(cmdqCommandStruct *pCommand) { if ((CMDQ_SCENARIO_USER_DISP_COLOR == pCommand->scenario) || (CMDQ_SCENARIO_USER_MDP == pCommand->scenario)) { CMDQ_VERBOSE("user space request, scenario:%d\n", pCommand->scenario); } else { CMDQ_VERBOSE("[WARNING]fix user space request to CMDQ_SCENARIO_USER_SPACE\n"); pCommand->scenario = CMDQ_SCENARIO_USER_SPACE; } } bool cmdq_core_is_request_from_user_space(const CMDQ_SCENARIO_ENUM scenario) { switch (scenario) { case CMDQ_SCENARIO_USER_DISP_COLOR: case CMDQ_SCENARIO_USER_MDP: case CMDQ_SCENARIO_USER_SPACE: /* phased out */ return true; default: return false; } return false; } bool cmdq_core_is_disp_scenario(const CMDQ_SCENARIO_ENUM scenario) { switch (scenario) { case CMDQ_SCENARIO_PRIMARY_DISP: case CMDQ_SCENARIO_PRIMARY_MEMOUT: case CMDQ_SCENARIO_PRIMARY_ALL: case CMDQ_SCENARIO_SUB_DISP: case CMDQ_SCENARIO_SUB_MEMOUT: case CMDQ_SCENARIO_SUB_ALL: case CMDQ_SCENARIO_MHL_DISP: case CMDQ_SCENARIO_RDMA0_DISP: case CMDQ_SCENARIO_RDMA0_COLOR0_DISP: case CMDQ_SCENARIO_RDMA1_DISP: case CMDQ_SCENARIO_TRIGGER_LOOP: case CMDQ_SCENARIO_DISP_ESD_CHECK: case CMDQ_SCENARIO_DISP_SCREEN_CAPTURE: case CMDQ_SCENARIO_DISP_MIRROR_MODE: /* color path */ case CMDQ_SCENARIO_DISP_COLOR: case CMDQ_SCENARIO_USER_DISP_COLOR: /* secure path */ case CMDQ_SCENARIO_DISP_PRIMARY_DISABLE_SECURE_PATH: case CMDQ_SCENARIO_DISP_SUB_DISABLE_SECURE_PATH: return true; default: return false; } /* freely dispatch */ return false; } bool cmdq_core_should_enable_prefetch(CMDQ_SCENARIO_ENUM scenario) { switch (scenario) { case CMDQ_SCENARIO_PRIMARY_DISP: case CMDQ_SCENARIO_PRIMARY_ALL: case CMDQ_SCENARIO_DEBUG_PREFETCH: /* HACK: force debug into 0/1 thread */ /* any path that connects to Primary DISP HW */ /* should enable prefetch. */ /* MEMOUT scenarios does not. */ /* Also, since thread 0/1 shares one prefetch buffer, */ /* we allow only PRIMARY path to use prefetch. */ return true; default: return false; } return false; } bool cmdq_core_should_profile(CMDQ_SCENARIO_ENUM scenario) { #ifdef CMDQ_GPR_SUPPORT switch (scenario) { default: return false; } return false; #else /* note command profile method depends on GPR */ CMDQ_ERR("func:%s failed since CMDQ dosen't support GPR\n", __func__); return false; #endif } const bool cmdq_core_is_a_secure_thread(const int32_t thread) { #ifdef CMDQ_SECURE_PATH_SUPPORT if ((CMDQ_MIN_SECURE_THREAD_ID <= thread) && (CMDQ_MIN_SECURE_THREAD_ID + CMDQ_MAX_SECURE_THREAD_COUNT > thread)){ return true; } #endif return false; } const bool cmdq_core_is_valid_notify_thread_for_secure_path(const int32_t thread) { #ifdef CMDQ_SECURE_PATH_SUPPORT return (15 == thread) ? (true) : (false); #else return false; #endif } int cmdq_core_get_thread_index_from_scenario_and_secure_data(CMDQ_SCENARIO_ENUM scenario, const bool secure) { #ifdef CMDQ_SECURE_PATH_SUPPORT if (!secure && CMDQ_SCENARIO_SECURE_NOTIFY_LOOP == scenario) { return 15; } #endif if (!secure) { return cmdq_core_disp_thread_index_from_scenario(scenario); } /* dispatch secure thread according to scenario */ switch (scenario) { case CMDQ_SCENARIO_DISP_PRIMARY_DISABLE_SECURE_PATH: case CMDQ_SCENARIO_PRIMARY_DISP: case CMDQ_SCENARIO_PRIMARY_ALL: case CMDQ_SCENARIO_RDMA0_DISP: case CMDQ_SCENARIO_DEBUG_PREFETCH: /* CMDQ_MIN_SECURE_THREAD_ID */ return 12; case CMDQ_SCENARIO_DISP_SUB_DISABLE_SECURE_PATH: case CMDQ_SCENARIO_SUB_DISP: case CMDQ_SCENARIO_SUB_ALL: case CMDQ_SCENARIO_MHL_DISP: /* because mirror mode and sub disp never use at the same time in secure path, */ /* dispatch to same HW thread */ case CMDQ_SCENARIO_DISP_MIRROR_MODE: case CMDQ_SCENARIO_DISP_COLOR: case CMDQ_SCENARIO_PRIMARY_MEMOUT: return 13; case CMDQ_SCENARIO_USER_MDP: case CMDQ_SCENARIO_USER_SPACE: case CMDQ_SCENARIO_DEBUG: /* because there is one input engine for MDP, reserve one secure thread is enough */ return 14; default: CMDQ_ERR("no dedicated secure thread for senario:%d\n", scenario); return CMDQ_INVALID_THREAD; } } int cmdq_core_disp_thread_index_from_scenario(CMDQ_SCENARIO_ENUM scenario) { if (cmdq_core_should_enable_prefetch(scenario)) { return 0; } switch (scenario) { case CMDQ_SCENARIO_PRIMARY_DISP: case CMDQ_SCENARIO_PRIMARY_ALL: case CMDQ_SCENARIO_RDMA0_DISP: case CMDQ_SCENARIO_RDMA0_COLOR0_DISP: case CMDQ_SCENARIO_DEBUG_PREFETCH: /* HACK: force debug into 0/1 thread */ /* primary config: thread 0 */ return 0; case CMDQ_SCENARIO_SUB_DISP: case CMDQ_SCENARIO_SUB_ALL: case CMDQ_SCENARIO_MHL_DISP: case CMDQ_SCENARIO_SUB_MEMOUT: case CMDQ_SCENARIO_RDMA1_DISP: /* when HW thread 0 enables pre-fetch, any thread 1 operation will let HW thread 0's behavior abnormally */ /* forbid thread 1 */ return 5; case CMDQ_SCENARIO_DISP_ESD_CHECK: return 2; case CMDQ_SCENARIO_DISP_SCREEN_CAPTURE: case CMDQ_SCENARIO_DISP_MIRROR_MODE: return 3; case CMDQ_SCENARIO_DISP_COLOR: case CMDQ_SCENARIO_USER_DISP_COLOR: case CMDQ_SCENARIO_PRIMARY_MEMOUT: return 4; default: /* freely dispatch */ return CMDQ_INVALID_THREAD; } /* freely dispatch */ return CMDQ_INVALID_THREAD; } CMDQ_HW_THREAD_PRIORITY_ENUM cmdq_core_priority_from_scenario(CMDQ_SCENARIO_ENUM scenario) { switch (scenario) { case CMDQ_SCENARIO_PRIMARY_DISP: case CMDQ_SCENARIO_PRIMARY_ALL: case CMDQ_SCENARIO_SUB_MEMOUT: case CMDQ_SCENARIO_SUB_DISP: case CMDQ_SCENARIO_SUB_ALL: case CMDQ_SCENARIO_RDMA1_DISP: case CMDQ_SCENARIO_MHL_DISP: case CMDQ_SCENARIO_RDMA0_DISP: case CMDQ_SCENARIO_RDMA0_COLOR0_DISP: case CMDQ_SCENARIO_DISP_MIRROR_MODE: case CMDQ_SCENARIO_PRIMARY_MEMOUT: /* color path */ case CMDQ_SCENARIO_DISP_COLOR: case CMDQ_SCENARIO_USER_DISP_COLOR: /* secure path **/ case CMDQ_SCENARIO_DISP_PRIMARY_DISABLE_SECURE_PATH: case CMDQ_SCENARIO_DISP_SUB_DISABLE_SECURE_PATH: /* currently, a prefetch thread is always in high priority. */ return CMDQ_THR_PRIO_DISPLAY_CONFIG; /* HACK: force debug into 0/1 thread */ case CMDQ_SCENARIO_DEBUG_PREFETCH: return CMDQ_THR_PRIO_DISPLAY_CONFIG; case CMDQ_SCENARIO_DISP_ESD_CHECK: case CMDQ_SCENARIO_DISP_SCREEN_CAPTURE: return CMDQ_THR_PRIO_DISPLAY_ESD; default: /* other cases need exta logic, see below. */ break; } if (cmdq_platform_is_loop_scenario(scenario, true)) { return CMDQ_THR_PRIO_DISPLAY_TRIGGER; } else { return CMDQ_THR_PRIO_NORMAL; } } bool cmdq_platform_force_loop_irq_from_scenario(CMDQ_SCENARIO_ENUM scenario) { #ifdef CMDQ_SECURE_PATH_SUPPORT if (CMDQ_SCENARIO_SECURE_NOTIFY_LOOP == scenario) { /* For secure notify loop, we need IRQ to update secure task */ return true; } #endif return false; } bool cmdq_platform_is_loop_scenario(CMDQ_SCENARIO_ENUM scenario, bool displayOnly) { #ifdef CMDQ_SECURE_PATH_SUPPORT if (!displayOnly && CMDQ_SCENARIO_SECURE_NOTIFY_LOOP == scenario) { return true; } #endif if (CMDQ_SCENARIO_TRIGGER_LOOP == scenario) { return true; } return false; } void cmdq_core_get_reg_id_from_hwflag(uint64_t hwflag, CMDQ_DATA_REGISTER_ENUM *valueRegId, CMDQ_DATA_REGISTER_ENUM *destRegId, CMDQ_EVENT_ENUM *regAccessToken) { *regAccessToken = CMDQ_SYNC_TOKEN_INVALID; if (hwflag & (1LL << CMDQ_ENG_JPEG_ENC)) { *valueRegId = CMDQ_DATA_REG_JPEG; *destRegId = CMDQ_DATA_REG_JPEG_DST; *regAccessToken = CMDQ_SYNC_TOKEN_GPR_SET_0; } else if (hwflag & (1LL << CMDQ_ENG_MDP_TDSHP0)) { *valueRegId = CMDQ_DATA_REG_2D_SHARPNESS_0; *destRegId = CMDQ_DATA_REG_2D_SHARPNESS_0_DST; *regAccessToken = CMDQ_SYNC_TOKEN_GPR_SET_1; } else if (hwflag & (1LL << CMDQ_ENG_DISP_COLOR0)) { *valueRegId = CMDQ_DATA_REG_PQ_COLOR; *destRegId = CMDQ_DATA_REG_PQ_COLOR_DST; *regAccessToken = CMDQ_SYNC_TOKEN_GPR_SET_3; } else { /* assume others are debug cases */ *valueRegId = CMDQ_DATA_REG_DEBUG; *destRegId = CMDQ_DATA_REG_DEBUG_DST; *regAccessToken = CMDQ_SYNC_TOKEN_GPR_SET_4; } return; } const char *cmdq_core_module_from_event_id(CMDQ_EVENT_ENUM event, uint32_t instA, uint32_t instB) { const char *module = "CMDQ"; switch (event) { case CMDQ_EVENT_DISP_RDMA0_SOF: case CMDQ_EVENT_DISP_RDMA1_SOF: case CMDQ_EVENT_DISP_RDMA0_EOF: case CMDQ_EVENT_DISP_RDMA1_EOF: case CMDQ_EVENT_DISP_RDMA0_UNDERRUN: case CMDQ_EVENT_DISP_RDMA1_UNDERRUN: module = "DISP_RDMA"; break; case CMDQ_EVENT_DISP_WDMA0_SOF: case CMDQ_EVENT_DISP_WDMA1_SOF: case CMDQ_EVENT_DISP_WDMA0_EOF: case CMDQ_EVENT_DISP_WDMA1_EOF: module = "DISP_WDMA"; break; case CMDQ_EVENT_DISP_OVL0_SOF: case CMDQ_EVENT_DISP_OVL1_SOF: case CMDQ_EVENT_DISP_OVL0_EOF: case CMDQ_EVENT_DISP_OVL1_EOF: module = "DISP_OVL"; break; case CMDQ_EVENT_DSI_TE: case CMDQ_EVENT_DISP_COLOR_SOF...CMDQ_EVENT_DISP_PWM0_SOF: case CMDQ_EVENT_DISP_COLOR_EOF...CMDQ_EVENT_DISP_DPI0_EOF: case CMDQ_EVENT_MUTEX0_STREAM_EOF...CMDQ_EVENT_MUTEX4_STREAM_EOF: case CMDQ_SYNC_TOKEN_CONFIG_DIRTY: case CMDQ_SYNC_TOKEN_STREAM_EOF: module = "DISP"; break; case CMDQ_EVENT_UFOD_RAMA0_L0_SOF...CMDQ_EVENT_UFOD_RAMA1_L3_SOF: case CMDQ_EVENT_UFOD_RAMA0_L0_EOF...CMDQ_EVENT_UFOD_RAMA1_L3_EOF: module = "DISP_UFOD"; break; case CMDQ_EVENT_MDP_RDMA0_SOF...CMDQ_EVENT_MDP_WROT_SOF: case CMDQ_EVENT_MDP_RDMA0_EOF...CMDQ_EVENT_MDP_WROT_READ_EOF: case CMDQ_EVENT_MUTEX5_STREAM_EOF...CMDQ_EVENT_MUTEX9_STREAM_EOF: module = "MDP"; break; case CMDQ_EVENT_ISP_PASS2_2_EOF...CMDQ_EVENT_ISP_PASS1_0_EOF: case CMDQ_EVENT_ISP_CAMSV_2_PASS1_DONE...CMDQ_EVENT_ISP_SENINF_CAM0_FULL: module = "ISP"; break; case CMDQ_EVENT_JPEG_ENC_EOF: case CMDQ_EVENT_JPEG_DEC_EOF: module = "JPGE"; break; case CMDQ_EVENT_VENC_EOF: case CMDQ_EVENT_VENC_MB_DONE: case CMDQ_EVENT_VENC_128BYTE_CNT_DONE: module = "VENC"; break; default: module = "CMDQ"; break; } return module; } const char *cmdq_core_parse_module_from_reg_addr(uint32_t reg_addr) { const uint32_t addr_base_and_page = (reg_addr & 0xFFFFF000); const uint32_t addr_base_shifted = (reg_addr & 0xFFFF0000) >> 16; const char *module = "CMDQ"; /* for well-known base, we check them with 12-bit mask */ /* defined in mt_reg_base.h */ /* TODO: comfirm with SS if IO_VIRT_TO_PHYS workable when enable device tree? */ #define DECLARE_REG_RANGE(base, name) case base: return #name; switch (addr_base_and_page) { DECLARE_REG_RANGE(0x14001000, MDP); /* MDP_RDMA */ DECLARE_REG_RANGE(0x14002000, MDP); /* MDP_RSZ0 */ DECLARE_REG_RANGE(0x14003000, MDP); /* MDP_RSZ1 */ DECLARE_REG_RANGE(0x14004000, MDP); /* MDP_WDMA */ DECLARE_REG_RANGE(0x14005000, MDP); /* MDP_WROT */ DECLARE_REG_RANGE(0x14006000, MDP); /* MDP_TDSHP */ DECLARE_REG_RANGE(0x1400C000, COLOR); /* DISP_COLOR */ DECLARE_REG_RANGE(0x1400D000, CCORR); /* DISP_CCORR */ DECLARE_REG_RANGE(0x14007000, OVL0); /* DISP_OVL0 */ DECLARE_REG_RANGE(0x14008000, OVL1); /* DISP_OVL1 */ DECLARE_REG_RANGE(0x1400E000, AAL); /* DISP_AAL */ DECLARE_REG_RANGE(0x1400F000, AAL); /* DISP_GAMMA */ DECLARE_REG_RANGE(0x17002FFF, VENC); /* VENC */ DECLARE_REG_RANGE(0x17003FFF, JPGENC); /* JPGENC */ DECLARE_REG_RANGE(0x17004FFF, JPGDEC); /* JPGDEC */ } #undef DECLARE_REG_RANGE /* for other register address we rely on GCE subsys to group them with */ /* 16-bit mask. */ #undef DECLARE_CMDQ_SUBSYS #define DECLARE_CMDQ_SUBSYS(msb, id, grp, base) case msb: return #grp; switch (addr_base_shifted) { #include "cmdq_subsys.h" } #undef DECLARE_CMDQ_SUBSYS return module; } const int32_t cmdq_core_can_module_entry_suspend(EngineStruct *engineList) { int32_t status = 0; int i; CMDQ_ENG_ENUM e = 0; CMDQ_ENG_ENUM mdpEngines[] = { CMDQ_ENG_ISP_IMGI, CMDQ_ENG_MDP_RDMA0, CMDQ_ENG_MDP_RSZ0, CMDQ_ENG_MDP_RSZ1, CMDQ_ENG_MDP_TDSHP0, CMDQ_ENG_MDP_WROT0, CMDQ_ENG_MDP_WDMA }; for (i = 0; i < (sizeof(mdpEngines) / sizeof(CMDQ_ENG_ENUM)); ++i) { e = mdpEngines[i]; if (0 != engineList[e].userCount) { CMDQ_ERR("suspend but engine %d has userCount %d, owner=%d\n", e, engineList[e].userCount, engineList[e].currOwner); status = -EBUSY; } } return status; } ssize_t cmdq_core_print_status_clock(char *buf) { int32_t length = 0; char *pBuffer = buf; #ifdef CMDQ_PWR_AWARE /* MT_CG_DISP0_MUTEX_32K is removed in this platform */ pBuffer += sprintf(pBuffer, "MT_CG_INFRA_GCE: %d\n", clock_is_on(MT_CG_INFRA_GCE)); #endif length = pBuffer - buf; return length; } void cmdq_core_print_status_seq_clock(struct seq_file *m) { #ifdef CMDQ_PWR_AWARE /* MT_CG_DISP0_MUTEX_32K is removed in this platform */ seq_printf(m, "MT_CG_INFRA_GCE: %d\n", clock_is_on(MT_CG_INFRA_GCE)); #endif } void cmdq_core_enable_common_clock_locked_impl(bool enable) { #ifdef CMDQ_PWR_AWARE if (enable) { CMDQ_VERBOSE("[CLOCK] Enable SMI & LARB0 Clock\n"); enable_clock(MT_CG_DISP0_SMI_COMMON, "CMDQ_MDP"); //enable_clock(MT_CG_DISP0_SMI_LARB0, "CMDQ_MDP"); m4u_larb0_enable("CMDQ_MDP"); #if 0 /* MT_CG_DISP0_MUTEX_32K is removed in this platform */ CMDQ_LOG("[CLOCK] enable MT_CG_DISP0_MUTEX_32K\n"); enable_clock(MT_CG_DISP0_MUTEX_32K, "CMDQ_MDP"); #endif } else { CMDQ_VERBOSE("[CLOCK] Disable SMI & LARB0 Clock\n"); /* disable, reverse the sequence */ //disable_clock(MT_CG_DISP0_SMI_LARB0, "CMDQ_MDP"); m4u_larb0_disable("CMDQ_MDP"); disable_clock(MT_CG_DISP0_SMI_COMMON, "CMDQ_MDP"); #if 0 /* MT_CG_DISP0_MUTEX_32K is removed in this platform */ CMDQ_LOG("[CLOCK] disable MT_CG_DISP0_MUTEX_32K\n"); disable_clock(MT_CG_DISP0_MUTEX_32K, "CMDQ_MDP"); #endif } #endif /* CMDQ_PWR_AWARE */ } void cmdq_core_enable_gce_clock_locked_impl(bool enable) { #ifdef CMDQ_PWR_AWARE if (enable) { CMDQ_VERBOSE("[CLOCK] Enable CMDQ(GCE) Clock\n"); cmdq_core_enable_cmdq_clock_locked_impl(enable, CMDQ_DRIVER_DEVICE_NAME); } else { CMDQ_VERBOSE("[CLOCK] Disable CMDQ(GCE) Clock\n"); cmdq_core_enable_cmdq_clock_locked_impl(enable, CMDQ_DRIVER_DEVICE_NAME); } #endif /* CMDQ_PWR_AWARE */ } void cmdq_core_enable_cmdq_clock_locked_impl(bool enable, char *deviceName) { #ifdef CMDQ_PWR_AWARE if (enable) { enable_clock(MT_CG_INFRA_GCE, deviceName); } else { disable_clock(MT_CG_INFRA_GCE, deviceName); } #endif /* CMDQ_PWR_AWARE */ } const char* cmdq_core_parse_error_module_by_hwflag_impl(struct TaskStruct *pTask) { const char *module = NULL; const uint32_t ISP_ONLY[2] = { ((1LL << CMDQ_ENG_ISP_IMGI) | (1LL << CMDQ_ENG_ISP_IMG2O)), ((1LL << CMDQ_ENG_ISP_IMGI) | (1LL << CMDQ_ENG_ISP_IMG2O) | (1LL << CMDQ_ENG_ISP_IMGO))}; /* common part for both normal and secure path */ /* for JPEG scenario, use HW flag is sufficient */ if (pTask->engineFlag & (1LL << CMDQ_ENG_JPEG_ENC)) { module = "JPGENC"; } else if (pTask->engineFlag & (1LL << CMDQ_ENG_JPEG_DEC)) { module = "JPGDEC"; } else if ((ISP_ONLY[0] == pTask->engineFlag) || (ISP_ONLY[1] == pTask->engineFlag)) { module = "ISP_ONLY"; } else if (cmdq_core_is_disp_scenario(pTask->scenario)) { module = "DISP"; } /* for secure path, use HW flag is sufficient */ do { if (NULL != module) { break; } if (false == pTask->secData.isSecure) { /* normal path, need parse current running instruciton for more detail */ break; } else if (CMDQ_ENG_MDP_GROUP_FLAG(pTask->engineFlag)) { module = "MDP"; break; } module = "CMDQ"; } while(0); /* other case, we need to analysis instruction for more detail */ return module; } void cmdq_core_dump_mmsys_config(void) { int i = 0; uint32_t value = 0; const static struct RegDef configRegisters[] = { {0x01c, "ISP_MOUT_EN"}, {0x020, "MDP_RDMA_MOUT_EN"}, {0x024, "MDP_PRZ0_MOUT_EN"}, {0x028, "MDP_PRZ1_MOUT_EN"}, {0x02C, "MDP_TDSHP_MOUT_EN"}, {0x030, "DISP_OVL0_MOUT_EN"}, {0x034, "DISP_OVL1_MOUT_EN"}, {0x038, "DISP_DITHER_MOUT_EN"}, {0x03C, "DISP_UFOE_MOUT_EN"}, /* {0x040, "MMSYS_MOUT_RST"}, */ {0x044, "MDP_PRZ0_SEL_IN"}, {0x048, "MDP_PRZ1_SEL_IN"}, {0x04C, "MDP_TDSHP_SEL_IN"}, {0x050, "MDP_WDMA_SEL_IN"}, {0x054, "MDP_WROT_SEL_IN"}, {0x058, "DISP_COLOR_SEL_IN"}, {0x05C, "DISP_WDMA_SEL_IN"}, {0x060, "DISP_UFOE_SEL_IN"}, {0x064, "DSI0_SEL_IN"}, {0x068, "DPI0_SEL_IN"}, {0x06C, "DISP_RDMA0_SOUT_SEL_IN"}, {0x070, "DISP_RDMA1_SOUT_SEL_IN"}, {0x0F0, "MMSYS_MISC"}, /* ACK and REQ related */ {0x8a0, "DISP_DL_VALID_0"}, {0x8a4, "DISP_DL_VALID_1"}, {0x8a8, "DISP_DL_READY_0"}, {0x8ac, "DISP_DL_READY_1"}, {0x8b0, "MDP_DL_VALID_0"}, {0x8b4, "MDP_DL_READY_0"} }; for (i = 0; i < sizeof(configRegisters) / sizeof(configRegisters[0]); ++i) { value = CMDQ_REG_GET16(MMSYS_CONFIG_BASE + configRegisters[i].offset); CMDQ_ERR("%s: 0x%08x\n", configRegisters[i].name, value); } return; } void cmdq_core_dump_clock_gating(void) { uint32_t value[3] = { 0 }; value[0] = CMDQ_REG_GET32(MMSYS_CONFIG_BASE + 0x100); value[1] = CMDQ_REG_GET32(MMSYS_CONFIG_BASE + 0x110); /* value[2] = CMDQ_REG_GET32(MMSYS_CONFIG_BASE + 0x890); */ CMDQ_ERR("MMSYS_CG_CON0(deprecated): 0x%08x, MMSYS_CG_CON1: 0x%08x\n", value[0], value[1]); /* CMDQ_ERR("MMSYS_DUMMY_REG: 0x%08x\n", value[2]); */ #ifndef CONFIG_MTK_FPGA CMDQ_ERR("ISPSys clock state %d\n", subsys_is_on(SYS_ISP)); CMDQ_ERR("DisSys clock state %d\n", subsys_is_on(SYS_DIS)); CMDQ_ERR("VDESys clock state %d\n", subsys_is_on(SYS_VDE)); #endif } int cmdq_core_dump_smi(const int showSmiDump) { #if 0 int isSMIHang = 0; #ifndef CONFIG_MTK_FPGA isSMIHang = smi_debug_bus_hanging_detect( SMI_DBG_DISPSYS | SMI_DBG_VDEC | SMI_DBG_IMGSYS | SMI_DBG_VENC | SMI_DBG_MJC, showSmiDump); isSMIHang = smi_debug_bus_hanging_detect_ext( SMI_DBG_DISPSYS | SMI_DBG_VDEC | SMI_DBG_IMGSYS | SMI_DBG_VENC | SMI_DBG_MJC, showSmiDump, 1); CMDQ_ERR("SMI Hang? = %d\n", isSMIHang); #endif return isSMIHang; #else CMDQ_LOG("[WARNING]not enable SMI dump now\n"); return 0; #endif } void cmdq_core_dump_secure_metadata(cmdqSecDataStruct *pSecData) { uint32_t i = 0; cmdqSecAddrMetadataStruct *pAddr = NULL; if (NULL == pSecData) { return; } pAddr = (cmdqSecAddrMetadataStruct *)(CMDQ_U32_PTR(pSecData->addrMetadatas)); CMDQ_LOG("========= pSecData: %p dump =========\n", pSecData); CMDQ_LOG("count:%d(%d), enginesNeedDAPC:0x%llx, enginesPortSecurity:0x%llx\n", pSecData->addrMetadataCount, pSecData->addrMetadataMaxCount, pSecData->enginesNeedDAPC, pSecData->enginesNeedPortSecurity); if (NULL == pAddr) { return; } for (i = 0; i < pSecData->addrMetadataCount; i++) { CMDQ_LOG("idx:%d, type:%d, baseHandle:%x, offset:%d, size:%d, port:%d\n", i, pAddr[i].type, pAddr[i].baseHandle, pAddr[i].offset, pAddr[i].size, pAddr[i].port); } } uint64_t cmdq_rec_flag_from_scenario(CMDQ_SCENARIO_ENUM scn) { uint64_t flag = 0; switch (scn) { case CMDQ_SCENARIO_JPEG_DEC: flag = (1LL << CMDQ_ENG_JPEG_DEC); break; case CMDQ_SCENARIO_PRIMARY_DISP: flag = (1LL << CMDQ_ENG_DISP_OVL0) | (1LL << CMDQ_ENG_DISP_COLOR0) | (1LL << CMDQ_ENG_DISP_AAL) | (1LL << CMDQ_ENG_DISP_GAMMA) | (1LL << CMDQ_ENG_DISP_RDMA0) | (1LL << CMDQ_ENG_DISP_UFOE) | (1LL << CMDQ_ENG_DISP_DSI0_CMD); break; case CMDQ_SCENARIO_PRIMARY_MEMOUT: flag = 0LL; break; case CMDQ_SCENARIO_PRIMARY_ALL: flag = ((1LL << CMDQ_ENG_DISP_OVL0) | (1LL << CMDQ_ENG_DISP_WDMA0) | (1LL << CMDQ_ENG_DISP_COLOR0) | (1LL << CMDQ_ENG_DISP_AAL) | (1LL << CMDQ_ENG_DISP_GAMMA) | (1LL << CMDQ_ENG_DISP_RDMA0) | (1LL << CMDQ_ENG_DISP_UFOE) | (1LL << CMDQ_ENG_DISP_DSI0_CMD)); break; case CMDQ_SCENARIO_SUB_DISP: flag = ((1LL << CMDQ_ENG_DISP_OVL1) | (1LL << CMDQ_ENG_DISP_RDMA1) | (1LL << CMDQ_ENG_DISP_DPI)); break; case CMDQ_SCENARIO_SUB_MEMOUT: flag = ((1LL << CMDQ_ENG_DISP_OVL1) | (1LL << CMDQ_ENG_DISP_WDMA1)); break; case CMDQ_SCENARIO_SUB_ALL: flag = ((1LL << CMDQ_ENG_DISP_OVL1) | (1LL << CMDQ_ENG_DISP_WDMA1) | (1LL << CMDQ_ENG_DISP_RDMA1) | (1LL << CMDQ_ENG_DISP_DPI)); break; case CMDQ_SCENARIO_RDMA0_DISP: flag = ((1LL << CMDQ_ENG_DISP_RDMA0) | (1LL << CMDQ_ENG_DISP_DSI0_CMD)); break; case CMDQ_SCENARIO_RDMA0_COLOR0_DISP: flag = ((1LL << CMDQ_ENG_DISP_RDMA0) | (1LL << CMDQ_ENG_DISP_COLOR0) | (1LL << CMDQ_ENG_DISP_AAL) | (1LL << CMDQ_ENG_DISP_GAMMA) | (1LL << CMDQ_ENG_DISP_UFOE) | (1LL << CMDQ_ENG_DISP_DSI0_CMD)); break; case CMDQ_SCENARIO_MHL_DISP: case CMDQ_SCENARIO_RDMA1_DISP: flag = ((1LL << CMDQ_ENG_DISP_RDMA1) | (1LL << CMDQ_ENG_DISP_DPI)); break; case CMDQ_SCENARIO_TRIGGER_LOOP: /* Trigger loop does not related to any HW by itself. */ flag = 0LL; break; case CMDQ_SCENARIO_USER_SPACE: /* user space case, engine flag is passed seprately */ flag = 0LL; break; case CMDQ_SCENARIO_DEBUG: case CMDQ_SCENARIO_DEBUG_PREFETCH: flag = 0LL; break; case CMDQ_SCENARIO_DISP_ESD_CHECK: case CMDQ_SCENARIO_DISP_SCREEN_CAPTURE: /* ESD check uses separate thread (not config, not trigger) */ flag = 0LL; break; case CMDQ_SCENARIO_DISP_COLOR: case CMDQ_SCENARIO_USER_DISP_COLOR: /* color path */ flag = 0LL; break; case CMDQ_SCENARIO_DISP_MIRROR_MODE: flag = 0LL; break; case CMDQ_SCENARIO_DISP_PRIMARY_DISABLE_SECURE_PATH: case CMDQ_SCENARIO_DISP_SUB_DISABLE_SECURE_PATH: /* secure path */ flag = 0LL; break; case CMDQ_SCENARIO_SECURE_NOTIFY_LOOP: flag = 0LL; break; default: CMDQ_ERR("Unknown scenario type %d\n", scn); flag = 0LL; break; } return flag; } void cmdq_core_gpr_dump(void) { int i = 0; long offset = 0; uint32_t value = 0; CMDQ_LOG("========= GPR dump ========= \n"); for (i = 0; i < 16; i++) { offset = CMDQ_GPR_R32(i); value = CMDQ_REG_GET32(offset); CMDQ_LOG("[GPR %2d]+0x%lx = 0x%08x\n", i, offset, value); } CMDQ_LOG("========= GPR dump ========= \n"); return; } void cmdq_test_setup(void) { /* unconditionally set CMDQ_SYNC_TOKEN_CONFIG_ALLOW and mutex STREAM_DONE */ /* so that DISPSYS scenarios may pass check. */ cmdqCoreSetEvent(CMDQ_SYNC_TOKEN_STREAM_EOF); cmdqCoreSetEvent(CMDQ_EVENT_MUTEX0_STREAM_EOF); cmdqCoreSetEvent(CMDQ_EVENT_MUTEX1_STREAM_EOF); cmdqCoreSetEvent(CMDQ_EVENT_MUTEX2_STREAM_EOF); cmdqCoreSetEvent(CMDQ_EVENT_MUTEX3_STREAM_EOF); } void cmdq_test_cleanup(void) { return; /* do nothing */ }
DKingCN/android_kernel_jiayu_s3_h560
drivers/misc/mediatek/cmdq/mt6752/cmdq_platform.c
C
gpl-2.0
23,146
/* Copyright (c) 2008-2013, The Linux Foundation. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 and * only version 2 as published by the Free Software Foundation. * * This program 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. */ #include <linux/slab.h> #include <linux/init.h> #include <linux/module.h> #include <linux/device.h> #include <linux/err.h> #include <linux/platform_device.h> #include <linux/sched.h> #include <linux/ratelimit.h> #include <linux/workqueue.h> #include <linux/pm_runtime.h> #include <linux/diagchar.h> #include <linux/delay.h> #include <linux/reboot.h> #include <linux/of.h> #include <linux/kmemleak.h> #ifdef CONFIG_DIAG_OVER_USB #include <mach/usbdiag.h> #endif #include <mach/msm_smd.h> #include <mach/socinfo.h> #include <mach/restart.h> #include "diagmem.h" #include "diagchar.h" #include "diagfwd.h" #include "diagfwd_cntl.h" #include "diagfwd_hsic.h" #include "diagchar_hdlc.h" #ifdef CONFIG_DIAG_SDIO_PIPE #include "diagfwd_sdio.h" #endif #include "diag_dci.h" #include "diag_masks.h" #include "diagfwd_bridge.h" #define MODE_CMD 41 #define RESET_ID 2 int diag_debug_buf_idx; unsigned char diag_debug_buf[1024]; static unsigned int buf_tbl_size = 8; /*Number of entries in table of buffers */ struct diag_master_table entry; struct diag_send_desc_type send = { NULL, NULL, DIAG_STATE_START, 0 }; struct diag_hdlc_dest_type enc = { NULL, NULL, 0 }; int wrap_enabled; uint16_t wrap_count; void encode_rsp_and_send(int buf_length) { struct diag_smd_info *data = &(driver->smd_data[MODEM_DATA]); send.state = DIAG_STATE_START; send.pkt = driver->apps_rsp_buf; send.last = (void *)(driver->apps_rsp_buf + buf_length); send.terminate = 1; if (!data->in_busy_1) { enc.dest = data->buf_in_1; enc.dest_last = (void *)(data->buf_in_1 + APPS_BUF_SIZE - 1); diag_hdlc_encode(&send, &enc); data->write_ptr_1->buf = data->buf_in_1; data->write_ptr_1->length = (int)(enc.dest - (void *)(data->buf_in_1)); data->in_busy_1 = 1; diag_device_write(data->buf_in_1, data->peripheral, data->write_ptr_1); memset(driver->apps_rsp_buf, '\0', APPS_BUF_SIZE); } } /* Determine if this device uses a device tree */ #ifdef CONFIG_OF static int has_device_tree(void) { struct device_node *node; node = of_find_node_by_path("/"); if (node) { of_node_put(node); return 1; } return 0; } #else static int has_device_tree(void) { return 0; } #endif int chk_config_get_id(void) { /* For all Fusion targets, Modem will always be present */ if (machine_is_msm8x60_fusion() || machine_is_msm8x60_fusn_ffa()) return 0; if (driver->use_device_tree) { if (machine_is_msm8974()) return MSM8974_TOOLS_ID; else return 0; } else { switch (socinfo_get_msm_cpu()) { case MSM_CPU_8X60: return APQ8060_TOOLS_ID; case MSM_CPU_8960: case MSM_CPU_8960AB: return AO8960_TOOLS_ID; case MSM_CPU_8064: case MSM_CPU_8064AB: case MSM_CPU_8064AA: return APQ8064_TOOLS_ID; case MSM_CPU_8930: case MSM_CPU_8930AA: case MSM_CPU_8930AB: return MSM8930_TOOLS_ID; case MSM_CPU_8974: return MSM8974_TOOLS_ID; case MSM_CPU_8625: return MSM8625_TOOLS_ID; default: return 0; } } } /* * This will return TRUE for targets which support apps only mode and hence SSR. * This applies to 8960 and newer targets. */ int chk_apps_only(void) { if (driver->use_device_tree) return 1; switch (socinfo_get_msm_cpu()) { case MSM_CPU_8960: case MSM_CPU_8960AB: case MSM_CPU_8064: case MSM_CPU_8064AB: case MSM_CPU_8064AA: case MSM_CPU_8930: case MSM_CPU_8930AA: case MSM_CPU_8930AB: case MSM_CPU_8627: case MSM_CPU_9615: case MSM_CPU_8974: return 1; default: return 0; } } /* * This will return TRUE for targets which support apps as master. * Thus, SW DLOAD and Mode Reset are supported on apps processor. * This applies to 8960 and newer targets. */ int chk_apps_master(void) { if (driver->use_device_tree) return 1; else if (soc_class_is_msm8960() || soc_class_is_msm8930() || soc_class_is_apq8064() || cpu_is_msm9615()) return 1; else return 0; } int chk_polling_response(void) { if (!(driver->polling_reg_flag) && chk_apps_master()) /* * If the apps processor is master and no other processor * has registered to respond for polling */ return 1; else if (!(driver->smd_data[MODEM_DATA].ch) && !(chk_apps_master())) /* * If the apps processor is not the master and the modem * is not up */ return 1; else return 0; } /* * This function should be called if you feel that the logging process may * need to be woken up. For instance, if the logging mode is MEMORY_DEVICE MODE * and while trying to read data from a SMD data channel there are no buffers * available to read the data into, then this function should be called to * determine if the logging process needs to be woken up. */ void chk_logging_wakeup(void) { int i; /* Find the index of the logging process */ for (i = 0; i < driver->num_clients; i++) if (driver->client_map[i].pid == driver->logging_process_id) break; if (i < driver->num_clients) { /* At very high logging rates a race condition can * occur where the buffers containing the data from * an smd channel are all in use, but the data_ready * flag is cleared. In this case, the buffers never * have their data read/logged. Detect and remedy this * situation. */ if ((driver->data_ready[i] & USER_SPACE_DATA_TYPE) == 0) { driver->data_ready[i] |= USER_SPACE_DATA_TYPE; pr_debug("diag: Force wakeup of logging process\n"); wake_up_interruptible(&driver->wait_q); } } } /* Process the data read from the smd data channel */ int diag_process_smd_read_data(struct diag_smd_info *smd_info, void *buf, int total_recd) { struct diag_request *write_ptr_modem = NULL; int *in_busy_ptr = 0; if (smd_info->buf_in_1 == buf) { write_ptr_modem = smd_info->write_ptr_1; in_busy_ptr = &smd_info->in_busy_1; } else if (smd_info->buf_in_2 == buf) { write_ptr_modem = smd_info->write_ptr_2; in_busy_ptr = &smd_info->in_busy_2; } else { pr_err("diag: In %s, no match for in_busy_1\n", __func__); } if (write_ptr_modem) { write_ptr_modem->length = total_recd; *in_busy_ptr = 1; diag_device_write(buf, smd_info->peripheral, write_ptr_modem); } return 0; } void diag_smd_send_req(struct diag_smd_info *smd_info) { void *buf = NULL, *temp_buf = NULL; int total_recd = 0, r = 0, pkt_len; int loop_count = 0; int notify = 0; if (!smd_info) { pr_err("diag: In %s, no smd info. Not able to read.\n", __func__); return; } if (!smd_info->in_busy_1) buf = smd_info->buf_in_1; else if ((smd_info->type == SMD_DATA_TYPE) && !smd_info->in_busy_2) buf = smd_info->buf_in_2; if (smd_info->ch && buf) { temp_buf = buf; pkt_len = smd_cur_packet_size(smd_info->ch); while (pkt_len && (pkt_len != total_recd)) { loop_count++; r = smd_read_avail(smd_info->ch); pr_debug("diag: In %s, received pkt %d %d\n", __func__, r, total_recd); if (!r) { /* Nothing to read from SMD */ wait_event(driver->smd_wait_q, ((smd_info->ch == 0) || smd_read_avail(smd_info->ch))); /* If the smd channel is open */ if (smd_info->ch) { pr_debug("diag: In %s, return from wait_event\n", __func__); continue; } else { pr_debug("diag: In %s, return from wait_event ch closed\n", __func__); return; } } total_recd += r; if (total_recd > IN_BUF_SIZE) { if (total_recd < MAX_IN_BUF_SIZE) { pr_err("diag: In %s, SMD sending in packets up to %d bytes\n", __func__, total_recd); buf = krealloc(buf, total_recd, GFP_KERNEL); } else { pr_err("diag: In %s, SMD sending in packets more than %d bytes\n", __func__, MAX_IN_BUF_SIZE); return; } } if (pkt_len < r) { pr_err("diag: In %s, SMD sending incorrect pkt\n", __func__); return; } if (pkt_len > r) { pr_err("diag: In %s, SMD sending partial pkt %d %d %d %d %d %d\n", __func__, pkt_len, r, total_recd, loop_count, smd_info->peripheral, smd_info->type); } /* keep reading for complete packet */ smd_read(smd_info->ch, temp_buf, r); temp_buf += r; } if (total_recd > 0) { if (!buf) { pr_err("diag: Out of diagmem for Modem\n"); } else if (smd_info->process_smd_read_data) { notify = smd_info->process_smd_read_data( smd_info, buf, total_recd); /* Poll SMD channels to check for data */ if (notify) diag_smd_notify(smd_info, SMD_EVENT_DATA); } } } else if (smd_info->ch && !buf && (driver->logging_mode == MEMORY_DEVICE_MODE)) { chk_logging_wakeup(); } } void diag_read_smd_work_fn(struct work_struct *work) { struct diag_smd_info *smd_info = container_of(work, struct diag_smd_info, diag_read_smd_work); diag_smd_send_req(smd_info); } int diag_device_write(void *buf, int data_type, struct diag_request *write_ptr) { int i, err = 0, index; index = 0; if (driver->logging_mode == MEMORY_DEVICE_MODE) { if (data_type == APPS_DATA) { for (i = 0; i < driver->poolsize_write_struct; i++) if (driver->buf_tbl[i].length == 0) { driver->buf_tbl[i].buf = buf; driver->buf_tbl[i].length = driver->used; #ifdef DIAG_DEBUG pr_debug("diag: ENQUEUE buf ptr" " and length is %x , %d\n", (unsigned int)(driver->buf_ tbl[i].buf), driver->buf_tbl[i].length); #endif break; } } #ifdef CONFIG_DIAGFWD_BRIDGE_CODE else if (data_type == HSIC_DATA || data_type == HSIC_2_DATA) { unsigned long flags; int foundIndex = -1; index = data_type - HSIC_DATA; spin_lock_irqsave(&diag_hsic[index].hsic_spinlock, flags); for (i = 0; i < diag_hsic[index].poolsize_hsic_write; i++) { if (diag_hsic[index].hsic_buf_tbl[i].length == 0) { diag_hsic[index].hsic_buf_tbl[i].buf = buf; diag_hsic[index].hsic_buf_tbl[i].length = diag_bridge[index].write_len; diag_hsic[index]. num_hsic_buf_tbl_entries++; foundIndex = i; break; } } spin_unlock_irqrestore(&diag_hsic[index].hsic_spinlock, flags); if (foundIndex == -1) err = -1; else pr_debug("diag: ENQUEUE HSIC buf ptr and length is %x , %d, ch %d\n", (unsigned int)buf, diag_bridge[index].write_len, index); } #endif for (i = 0; i < driver->num_clients; i++) if (driver->client_map[i].pid == driver->logging_process_id) break; if (i < driver->num_clients) { driver->data_ready[i] |= USER_SPACE_DATA_TYPE; pr_debug("diag: wake up logging process\n"); wake_up_interruptible(&driver->wait_q); } else return -EINVAL; } else if (driver->logging_mode == NO_LOGGING_MODE) { if ((data_type >= 0) && (data_type < NUM_SMD_DATA_CHANNELS)) { driver->smd_data[data_type].in_busy_1 = 0; driver->smd_data[data_type].in_busy_2 = 0; queue_work(driver->diag_wq, &(driver->smd_data[data_type]. diag_read_smd_work)); } #ifdef CONFIG_DIAG_SDIO_PIPE else if (data_type == SDIO_DATA) { driver->in_busy_sdio = 0; queue_work(driver->diag_sdio_wq, &(driver->diag_read_sdio_work)); } #endif #ifdef CONFIG_DIAGFWD_BRIDGE_CODE else if (data_type == HSIC_DATA || data_type == HSIC_2_DATA) { index = data_type - HSIC_DATA; if (diag_hsic[index].hsic_ch) queue_work(diag_bridge[index].wq, &(diag_hsic[index]. diag_read_hsic_work)); } #endif err = -1; } #ifdef CONFIG_DIAG_OVER_USB else if (driver->logging_mode == USB_MODE) { if (data_type == APPS_DATA) { driver->write_ptr_svc = (struct diag_request *) (diagmem_alloc(driver, sizeof(struct diag_request), POOL_TYPE_WRITE_STRUCT)); if (driver->write_ptr_svc) { driver->write_ptr_svc->length = driver->used; driver->write_ptr_svc->buf = buf; err = usb_diag_write(driver->legacy_ch, driver->write_ptr_svc); } else err = -1; } else if ((data_type >= 0) && (data_type < NUM_SMD_DATA_CHANNELS)) { write_ptr->buf = buf; #ifdef DIAG_DEBUG printk(KERN_INFO "writing data to USB," "pkt length %d\n", write_ptr->length); print_hex_dump(KERN_DEBUG, "Written Packet Data to" " USB: ", 16, 1, DUMP_PREFIX_ADDRESS, buf, write_ptr->length, 1); #endif /* DIAG DEBUG */ err = usb_diag_write(driver->legacy_ch, write_ptr); } #ifdef CONFIG_DIAG_SDIO_PIPE else if (data_type == SDIO_DATA) { if (machine_is_msm8x60_fusion() || machine_is_msm8x60_fusn_ffa()) { write_ptr->buf = buf; err = usb_diag_write(driver->mdm_ch, write_ptr); } else pr_err("diag: Incorrect sdio data " "while USB write\n"); } #endif #ifdef CONFIG_DIAGFWD_BRIDGE_CODE else if (data_type == HSIC_DATA || data_type == HSIC_2_DATA) { index = data_type - HSIC_DATA; if (diag_hsic[index].hsic_device_enabled) { struct diag_request *write_ptr_mdm; write_ptr_mdm = (struct diag_request *) diagmem_alloc(driver, sizeof(struct diag_request), index + POOL_TYPE_HSIC_WRITE); if (write_ptr_mdm) { write_ptr_mdm->buf = buf; write_ptr_mdm->length = diag_bridge[index].write_len; write_ptr_mdm->context = (void *)index; err = usb_diag_write( diag_bridge[index].ch, write_ptr_mdm); /* Return to the pool immediately */ if (err) { diagmem_free(driver, write_ptr_mdm, index + POOL_TYPE_HSIC_WRITE); pr_err_ratelimited("diag: HSIC write failure, err: %d, ch %d\n", err, index); } } else { pr_err("diag: allocate write fail\n"); err = -1; } } else { pr_err("diag: Incorrect HSIC data " "while USB write\n"); err = -1; } } else if (data_type == SMUX_DATA) { write_ptr->buf = buf; write_ptr->context = (void *)SMUX; pr_debug("diag: writing SMUX data\n"); err = usb_diag_write(diag_bridge[SMUX].ch, write_ptr); } #endif APPEND_DEBUG('d'); } #endif /* DIAG OVER USB */ return err; } static void diag_update_pkt_buffer(unsigned char *buf) { unsigned char *ptr = driver->pkt_buf; unsigned char *temp = buf; mutex_lock(&driver->diagchar_mutex); if (CHK_OVERFLOW(ptr, ptr, ptr + PKT_SIZE, driver->pkt_length)) memcpy(ptr, temp , driver->pkt_length); else printk(KERN_CRIT " Not enough buffer space for PKT_RESP\n"); mutex_unlock(&driver->diagchar_mutex); } void diag_update_userspace_clients(unsigned int type) { int i; mutex_lock(&driver->diagchar_mutex); for (i = 0; i < driver->num_clients; i++) if (driver->client_map[i].pid != 0) driver->data_ready[i] |= type; wake_up_interruptible(&driver->wait_q); mutex_unlock(&driver->diagchar_mutex); } void diag_update_sleeping_process(int process_id, int data_type) { int i; mutex_lock(&driver->diagchar_mutex); for (i = 0; i < driver->num_clients; i++) if (driver->client_map[i].pid == process_id) { driver->data_ready[i] |= data_type; break; } wake_up_interruptible(&driver->wait_q); mutex_unlock(&driver->diagchar_mutex); } static int diag_check_mode_reset(unsigned char *buf) { int is_mode_reset = 0; if (chk_apps_master() && (int)(*(char *)buf) == MODE_CMD) if ((int)(*(char *)(buf+1)) == RESET_ID) is_mode_reset = 1; return is_mode_reset; } void diag_send_data(struct diag_master_table entry, unsigned char *buf, int len, int type) { driver->pkt_length = len; if (entry.process_id != NON_APPS_PROC && type != MODEM_DATA) { diag_update_pkt_buffer(buf); diag_update_sleeping_process(entry.process_id, PKT_TYPE); } else { if (len > 0) { if ((entry.client_id >= 0) && (entry.client_id < NUM_SMD_DATA_CHANNELS)) { int index = entry.client_id; if (driver->smd_data[index].ch) { if ((index == MODEM_DATA) && diag_check_mode_reset(buf)) { return; } smd_write(driver->smd_data[index].ch, buf, len); } else { pr_err("diag: In %s, smd channel %d not open\n", __func__, index); } } else { pr_alert("diag: In %s, incorrect channel: %d", __func__, entry.client_id); } } } } static int diag_process_apps_pkt(unsigned char *buf, int len) { uint16_t subsys_cmd_code; int subsys_id, ssid_first, ssid_last, ssid_range; int packet_type = 1, i, cmd_code; unsigned char *temp = buf; int data_type; int mask_ret; #if defined(CONFIG_DIAG_OVER_USB) unsigned char *ptr; #endif /* Check if the command is a supported mask command */ mask_ret = diag_process_apps_masks(buf, len); if (mask_ret <= 0) return mask_ret; /* Check for registered clients and forward packet to apropriate proc */ cmd_code = (int)(*(char *)buf); temp++; subsys_id = (int)(*(char *)temp); temp++; subsys_cmd_code = *(uint16_t *)temp; temp += 2; data_type = APPS_DATA; /* Dont send any command other than mode reset */ if (chk_apps_master() && cmd_code == MODE_CMD) { if (subsys_id != RESET_ID) data_type = MODEM_DATA; } pr_debug("diag: %d %d %d", cmd_code, subsys_id, subsys_cmd_code); for (i = 0; i < diag_max_reg; i++) { entry = driver->table[i]; if (entry.process_id != NO_PROCESS) { if (entry.cmd_code == cmd_code && entry.subsys_id == subsys_id && entry.cmd_code_lo <= subsys_cmd_code && entry.cmd_code_hi >= subsys_cmd_code) { diag_send_data(entry, buf, len, data_type); packet_type = 0; } else if (entry.cmd_code == 255 && cmd_code == 75) { if (entry.subsys_id == subsys_id && entry.cmd_code_lo <= subsys_cmd_code && entry.cmd_code_hi >= subsys_cmd_code) { diag_send_data(entry, buf, len, data_type); packet_type = 0; } } else if (entry.cmd_code == 255 && entry.subsys_id == 255) { if (entry.cmd_code_lo <= cmd_code && entry. cmd_code_hi >= cmd_code) { diag_send_data(entry, buf, len, data_type); packet_type = 0; } } } } #if defined(CONFIG_DIAG_OVER_USB) /* Check for the command/respond msg for the maximum packet length */ if ((*buf == 0x4b) && (*(buf+1) == 0x12) && (*(uint16_t *)(buf+2) == 0x0055)) { for (i = 0; i < 4; i++) *(driver->apps_rsp_buf+i) = *(buf+i); *(uint32_t *)(driver->apps_rsp_buf+4) = PKT_SIZE; encode_rsp_and_send(7); return 0; } /* Check for Apps Only & get event mask request */ else if (!(driver->smd_data[MODEM_DATA].ch) && chk_apps_only() && *buf == 0x81) { driver->apps_rsp_buf[0] = 0x81; driver->apps_rsp_buf[1] = 0x0; *(uint16_t *)(driver->apps_rsp_buf + 2) = 0x0; *(uint16_t *)(driver->apps_rsp_buf + 4) = EVENT_LAST_ID + 1; for (i = 0; i < EVENT_LAST_ID/8 + 1; i++) *(unsigned char *)(driver->apps_rsp_buf + 6 + i) = 0x0; encode_rsp_and_send(6 + EVENT_LAST_ID/8); return 0; } /* Get log ID range & Check for Apps Only */ else if (!(driver->smd_data[MODEM_DATA].ch) && chk_apps_only() && (*buf == 0x73) && *(int *)(buf+4) == 1) { driver->apps_rsp_buf[0] = 0x73; *(int *)(driver->apps_rsp_buf + 4) = 0x1; /* operation ID */ *(int *)(driver->apps_rsp_buf + 8) = 0x0; /* success code */ *(int *)(driver->apps_rsp_buf + 12) = LOG_GET_ITEM_NUM(LOG_0); *(int *)(driver->apps_rsp_buf + 16) = LOG_GET_ITEM_NUM(LOG_1); *(int *)(driver->apps_rsp_buf + 20) = LOG_GET_ITEM_NUM(LOG_2); *(int *)(driver->apps_rsp_buf + 24) = LOG_GET_ITEM_NUM(LOG_3); *(int *)(driver->apps_rsp_buf + 28) = LOG_GET_ITEM_NUM(LOG_4); *(int *)(driver->apps_rsp_buf + 32) = LOG_GET_ITEM_NUM(LOG_5); *(int *)(driver->apps_rsp_buf + 36) = LOG_GET_ITEM_NUM(LOG_6); *(int *)(driver->apps_rsp_buf + 40) = LOG_GET_ITEM_NUM(LOG_7); *(int *)(driver->apps_rsp_buf + 44) = LOG_GET_ITEM_NUM(LOG_8); *(int *)(driver->apps_rsp_buf + 48) = LOG_GET_ITEM_NUM(LOG_9); *(int *)(driver->apps_rsp_buf + 52) = LOG_GET_ITEM_NUM(LOG_10); *(int *)(driver->apps_rsp_buf + 56) = LOG_GET_ITEM_NUM(LOG_11); *(int *)(driver->apps_rsp_buf + 60) = LOG_GET_ITEM_NUM(LOG_12); *(int *)(driver->apps_rsp_buf + 64) = LOG_GET_ITEM_NUM(LOG_13); *(int *)(driver->apps_rsp_buf + 68) = LOG_GET_ITEM_NUM(LOG_14); *(int *)(driver->apps_rsp_buf + 72) = LOG_GET_ITEM_NUM(LOG_15); encode_rsp_and_send(75); return 0; } /* Respond to Get SSID Range request message */ else if (!(driver->smd_data[MODEM_DATA].ch) && chk_apps_only() && (*buf == 0x7d) && (*(buf+1) == 0x1)) { driver->apps_rsp_buf[0] = 0x7d; driver->apps_rsp_buf[1] = 0x1; driver->apps_rsp_buf[2] = 0x1; driver->apps_rsp_buf[3] = 0x0; /* -1 to un-account for OEM SSID range */ *(int *)(driver->apps_rsp_buf + 4) = MSG_MASK_TBL_CNT - 1; *(uint16_t *)(driver->apps_rsp_buf + 8) = MSG_SSID_0; *(uint16_t *)(driver->apps_rsp_buf + 10) = MSG_SSID_0_LAST; *(uint16_t *)(driver->apps_rsp_buf + 12) = MSG_SSID_1; *(uint16_t *)(driver->apps_rsp_buf + 14) = MSG_SSID_1_LAST; *(uint16_t *)(driver->apps_rsp_buf + 16) = MSG_SSID_2; *(uint16_t *)(driver->apps_rsp_buf + 18) = MSG_SSID_2_LAST; *(uint16_t *)(driver->apps_rsp_buf + 20) = MSG_SSID_3; *(uint16_t *)(driver->apps_rsp_buf + 22) = MSG_SSID_3_LAST; *(uint16_t *)(driver->apps_rsp_buf + 24) = MSG_SSID_4; *(uint16_t *)(driver->apps_rsp_buf + 26) = MSG_SSID_4_LAST; *(uint16_t *)(driver->apps_rsp_buf + 28) = MSG_SSID_5; *(uint16_t *)(driver->apps_rsp_buf + 30) = MSG_SSID_5_LAST; *(uint16_t *)(driver->apps_rsp_buf + 32) = MSG_SSID_6; *(uint16_t *)(driver->apps_rsp_buf + 34) = MSG_SSID_6_LAST; *(uint16_t *)(driver->apps_rsp_buf + 36) = MSG_SSID_7; *(uint16_t *)(driver->apps_rsp_buf + 38) = MSG_SSID_7_LAST; *(uint16_t *)(driver->apps_rsp_buf + 40) = MSG_SSID_8; *(uint16_t *)(driver->apps_rsp_buf + 42) = MSG_SSID_8_LAST; *(uint16_t *)(driver->apps_rsp_buf + 44) = MSG_SSID_9; *(uint16_t *)(driver->apps_rsp_buf + 46) = MSG_SSID_9_LAST; *(uint16_t *)(driver->apps_rsp_buf + 48) = MSG_SSID_10; *(uint16_t *)(driver->apps_rsp_buf + 50) = MSG_SSID_10_LAST; *(uint16_t *)(driver->apps_rsp_buf + 52) = MSG_SSID_11; *(uint16_t *)(driver->apps_rsp_buf + 54) = MSG_SSID_11_LAST; *(uint16_t *)(driver->apps_rsp_buf + 56) = MSG_SSID_12; *(uint16_t *)(driver->apps_rsp_buf + 58) = MSG_SSID_12_LAST; *(uint16_t *)(driver->apps_rsp_buf + 60) = MSG_SSID_13; *(uint16_t *)(driver->apps_rsp_buf + 62) = MSG_SSID_13_LAST; *(uint16_t *)(driver->apps_rsp_buf + 64) = MSG_SSID_14; *(uint16_t *)(driver->apps_rsp_buf + 66) = MSG_SSID_14_LAST; *(uint16_t *)(driver->apps_rsp_buf + 68) = MSG_SSID_15; *(uint16_t *)(driver->apps_rsp_buf + 70) = MSG_SSID_15_LAST; *(uint16_t *)(driver->apps_rsp_buf + 72) = MSG_SSID_16; *(uint16_t *)(driver->apps_rsp_buf + 74) = MSG_SSID_16_LAST; *(uint16_t *)(driver->apps_rsp_buf + 76) = MSG_SSID_17; *(uint16_t *)(driver->apps_rsp_buf + 78) = MSG_SSID_17_LAST; *(uint16_t *)(driver->apps_rsp_buf + 80) = MSG_SSID_18; *(uint16_t *)(driver->apps_rsp_buf + 82) = MSG_SSID_18_LAST; *(uint16_t *)(driver->apps_rsp_buf + 84) = MSG_SSID_19; *(uint16_t *)(driver->apps_rsp_buf + 86) = MSG_SSID_19_LAST; *(uint16_t *)(driver->apps_rsp_buf + 88) = MSG_SSID_20; *(uint16_t *)(driver->apps_rsp_buf + 90) = MSG_SSID_20_LAST; *(uint16_t *)(driver->apps_rsp_buf + 92) = MSG_SSID_21; *(uint16_t *)(driver->apps_rsp_buf + 94) = MSG_SSID_21_LAST; *(uint16_t *)(driver->apps_rsp_buf + 96) = MSG_SSID_22; *(uint16_t *)(driver->apps_rsp_buf + 98) = MSG_SSID_22_LAST; encode_rsp_and_send(99); return 0; } /* Check for Apps Only Respond to Get Subsys Build mask */ else if (!(driver->smd_data[MODEM_DATA].ch) && chk_apps_only() && (*buf == 0x7d) && (*(buf+1) == 0x2)) { ssid_first = *(uint16_t *)(buf + 2); ssid_last = *(uint16_t *)(buf + 4); ssid_range = 4 * (ssid_last - ssid_first + 1); /* frame response */ driver->apps_rsp_buf[0] = 0x7d; driver->apps_rsp_buf[1] = 0x2; *(uint16_t *)(driver->apps_rsp_buf + 2) = ssid_first; *(uint16_t *)(driver->apps_rsp_buf + 4) = ssid_last; driver->apps_rsp_buf[6] = 0x1; driver->apps_rsp_buf[7] = 0x0; ptr = driver->apps_rsp_buf + 8; /* bld time masks */ switch (ssid_first) { case MSG_SSID_0: for (i = 0; i < ssid_range; i += 4) *(int *)(ptr + i) = msg_bld_masks_0[i/4]; break; case MSG_SSID_1: for (i = 0; i < ssid_range; i += 4) *(int *)(ptr + i) = msg_bld_masks_1[i/4]; break; case MSG_SSID_2: for (i = 0; i < ssid_range; i += 4) *(int *)(ptr + i) = msg_bld_masks_2[i/4]; break; case MSG_SSID_3: for (i = 0; i < ssid_range; i += 4) *(int *)(ptr + i) = msg_bld_masks_3[i/4]; break; case MSG_SSID_4: for (i = 0; i < ssid_range; i += 4) *(int *)(ptr + i) = msg_bld_masks_4[i/4]; break; case MSG_SSID_5: for (i = 0; i < ssid_range; i += 4) *(int *)(ptr + i) = msg_bld_masks_5[i/4]; break; case MSG_SSID_6: for (i = 0; i < ssid_range; i += 4) *(int *)(ptr + i) = msg_bld_masks_6[i/4]; break; case MSG_SSID_7: for (i = 0; i < ssid_range; i += 4) *(int *)(ptr + i) = msg_bld_masks_7[i/4]; break; case MSG_SSID_8: for (i = 0; i < ssid_range; i += 4) *(int *)(ptr + i) = msg_bld_masks_8[i/4]; break; case MSG_SSID_9: for (i = 0; i < ssid_range; i += 4) *(int *)(ptr + i) = msg_bld_masks_9[i/4]; break; case MSG_SSID_10: for (i = 0; i < ssid_range; i += 4) *(int *)(ptr + i) = msg_bld_masks_10[i/4]; break; case MSG_SSID_11: for (i = 0; i < ssid_range; i += 4) *(int *)(ptr + i) = msg_bld_masks_11[i/4]; break; case MSG_SSID_12: for (i = 0; i < ssid_range; i += 4) *(int *)(ptr + i) = msg_bld_masks_12[i/4]; break; case MSG_SSID_13: for (i = 0; i < ssid_range; i += 4) *(int *)(ptr + i) = msg_bld_masks_13[i/4]; break; case MSG_SSID_14: for (i = 0; i < ssid_range; i += 4) *(int *)(ptr + i) = msg_bld_masks_14[i/4]; break; case MSG_SSID_15: for (i = 0; i < ssid_range; i += 4) *(int *)(ptr + i) = msg_bld_masks_15[i/4]; break; case MSG_SSID_16: for (i = 0; i < ssid_range; i += 4) *(int *)(ptr + i) = msg_bld_masks_16[i/4]; break; case MSG_SSID_17: for (i = 0; i < ssid_range; i += 4) *(int *)(ptr + i) = msg_bld_masks_17[i/4]; break; case MSG_SSID_18: for (i = 0; i < ssid_range; i += 4) *(int *)(ptr + i) = msg_bld_masks_18[i/4]; break; case MSG_SSID_19: for (i = 0; i < ssid_range; i += 4) *(int *)(ptr + i) = msg_bld_masks_19[i/4]; break; case MSG_SSID_20: for (i = 0; i < ssid_range; i += 4) *(int *)(ptr + i) = msg_bld_masks_20[i/4]; break; case MSG_SSID_21: for (i = 0; i < ssid_range; i += 4) *(int *)(ptr + i) = msg_bld_masks_21[i/4]; break; case MSG_SSID_22: for (i = 0; i < ssid_range; i += 4) *(int *)(ptr + i) = msg_bld_masks_22[i/4]; break; } encode_rsp_and_send(8 + ssid_range - 1); return 0; } /* Check for download command */ else if ((cpu_is_msm8x60() || chk_apps_master()) && (*buf == 0x3A)) { /* send response back */ driver->apps_rsp_buf[0] = *buf; encode_rsp_and_send(0); msleep(5000); /* call download API */ msm_set_restart_mode(RESTART_DLOAD); printk(KERN_CRIT "diag: download mode set, Rebooting SoC..\n"); kernel_restart(NULL); /* Not required, represents that command isnt sent to modem */ return 0; } /* Check for polling for Apps only DIAG */ else if ((*buf == 0x4b) && (*(buf+1) == 0x32) && (*(buf+2) == 0x03)) { /* If no one has registered for polling */ if (chk_polling_response()) { /* Respond to polling for Apps only DIAG */ for (i = 0; i < 3; i++) driver->apps_rsp_buf[i] = *(buf+i); for (i = 0; i < 13; i++) driver->apps_rsp_buf[i+3] = 0; encode_rsp_and_send(15); return 0; } } /* Return the Delayed Response Wrap Status */ else if ((*buf == 0x4b) && (*(buf+1) == 0x32) && (*(buf+2) == 0x04) && (*(buf+3) == 0x0)) { memcpy(driver->apps_rsp_buf, buf, 4); driver->apps_rsp_buf[4] = wrap_enabled; encode_rsp_and_send(4); return 0; } /* Wrap the Delayed Rsp ID */ else if ((*buf == 0x4b) && (*(buf+1) == 0x32) && (*(buf+2) == 0x05) && (*(buf+3) == 0x0)) { wrap_enabled = true; memcpy(driver->apps_rsp_buf, buf, 4); driver->apps_rsp_buf[4] = wrap_count; encode_rsp_and_send(5); return 0; } /* Check for ID for NO MODEM present */ else if (chk_polling_response()) { /* respond to 0x0 command */ if (*buf == 0x00) { for (i = 0; i < 55; i++) driver->apps_rsp_buf[i] = 0; encode_rsp_and_send(54); return 0; } /* respond to 0x7c command */ else if (*buf == 0x7c) { driver->apps_rsp_buf[0] = 0x7c; for (i = 1; i < 8; i++) driver->apps_rsp_buf[i] = 0; /* Tools ID for APQ 8060 */ *(int *)(driver->apps_rsp_buf + 8) = chk_config_get_id(); *(unsigned char *)(driver->apps_rsp_buf + 12) = '\0'; *(unsigned char *)(driver->apps_rsp_buf + 13) = '\0'; encode_rsp_and_send(13); return 0; } } #endif return packet_type; } #ifdef CONFIG_DIAG_OVER_USB void diag_send_error_rsp(int index) { int i; if (index > 490) { pr_err("diag: error response too huge, aborting\n"); return; } driver->apps_rsp_buf[0] = 0x13; /* error code 13 */ for (i = 0; i < index; i++) driver->apps_rsp_buf[i+1] = *(driver->hdlc_buf+i); encode_rsp_and_send(index - 3); } #else static inline void diag_send_error_rsp(int index) {} #endif void diag_process_hdlc(void *data, unsigned len) { struct diag_hdlc_decode_type hdlc; int ret, type = 0; pr_debug("diag: HDLC decode fn, len of data %d\n", len); hdlc.dest_ptr = driver->hdlc_buf; hdlc.dest_size = USB_MAX_OUT_BUF; hdlc.src_ptr = data; hdlc.src_size = len; hdlc.src_idx = 0; hdlc.dest_idx = 0; hdlc.escaping = 0; ret = diag_hdlc_decode(&hdlc); if (hdlc.dest_idx < 3) { pr_err("diag: Integer underflow in hdlc processing\n"); return; } if (ret) { type = diag_process_apps_pkt(driver->hdlc_buf, hdlc.dest_idx - 3); if (type < 0) return; } else if (driver->debug_flag) { printk(KERN_ERR "Packet dropped due to bad HDLC coding/CRC" " errors or partial packet received, packet" " length = %d\n", len); print_hex_dump(KERN_DEBUG, "Dropped Packet Data: ", 16, 1, DUMP_PREFIX_ADDRESS, data, len, 1); driver->debug_flag = 0; } /* send error responses from APPS for Central Routing */ if (type == 1 && chk_apps_only()) { diag_send_error_rsp(hdlc.dest_idx); type = 0; } /* implies this packet is NOT meant for apps */ if (!(driver->smd_data[MODEM_DATA].ch) && type == 1) { if (chk_apps_only()) { diag_send_error_rsp(hdlc.dest_idx); } else { /* APQ 8060, Let Q6 respond */ if (driver->smd_data[LPASS_DATA].ch) smd_write(driver->smd_data[LPASS_DATA].ch, driver->hdlc_buf, hdlc.dest_idx - 3); } type = 0; } #ifdef DIAG_DEBUG pr_debug("diag: hdlc.dest_idx = %d", hdlc.dest_idx); for (i = 0; i < hdlc.dest_idx; i++) printk(KERN_DEBUG "\t%x", *(((unsigned char *) driver->hdlc_buf)+i)); #endif /* DIAG DEBUG */ /* ignore 2 bytes for CRC, one for 7E and send */ if ((driver->smd_data[MODEM_DATA].ch) && (ret) && (type) && (hdlc.dest_idx > 3)) { APPEND_DEBUG('g'); smd_write(driver->smd_data[MODEM_DATA].ch, driver->hdlc_buf, hdlc.dest_idx - 3); APPEND_DEBUG('h'); #ifdef DIAG_DEBUG printk(KERN_INFO "writing data to SMD, pkt length %d\n", len); print_hex_dump(KERN_DEBUG, "Written Packet Data to SMD: ", 16, 1, DUMP_PREFIX_ADDRESS, data, len, 1); #endif /* DIAG DEBUG */ } } #ifdef CONFIG_DIAG_OVER_USB /* 2+1 for modem ; 2 for LPASS ; 1 for WCNSS */ #define N_LEGACY_WRITE (driver->poolsize + 6) #define N_LEGACY_READ 1 int diagfwd_connect(void) { int err; int i; printk(KERN_DEBUG "diag: USB connected\n"); err = usb_diag_alloc_req(driver->legacy_ch, N_LEGACY_WRITE, N_LEGACY_READ); if (err) printk(KERN_ERR "diag: unable to alloc USB req on legacy ch"); driver->usb_connected = 1; for (i = 0; i < NUM_SMD_DATA_CHANNELS; i++) { driver->smd_data[i].in_busy_1 = 0; driver->smd_data[i].in_busy_2 = 0; /* Poll SMD data channels to check for data */ queue_work(driver->diag_wq, &(driver->smd_data[i].diag_read_smd_work)); /* Poll SMD CNTL channels to check for data */ diag_smd_notify(&(driver->smd_cntl[i]), SMD_EVENT_DATA); } /* Poll USB channel to check for data*/ queue_work(driver->diag_wq, &(driver->diag_read_work)); #ifdef CONFIG_DIAG_SDIO_PIPE if (machine_is_msm8x60_fusion() || machine_is_msm8x60_fusn_ffa()) { if (driver->mdm_ch && !IS_ERR(driver->mdm_ch)) diagfwd_connect_sdio(); else printk(KERN_INFO "diag: No USB MDM ch"); } #endif return 0; } int diagfwd_disconnect(void) { int i; printk(KERN_DEBUG "diag: USB disconnected\n"); driver->usb_connected = 0; driver->debug_flag = 1; usb_diag_free_req(driver->legacy_ch); if (driver->logging_mode == USB_MODE) { for (i = 0; i < NUM_SMD_DATA_CHANNELS; i++) { driver->smd_data[i].in_busy_1 = 1; driver->smd_data[i].in_busy_2 = 1; } } #ifdef CONFIG_DIAG_SDIO_PIPE if (machine_is_msm8x60_fusion() || machine_is_msm8x60_fusn_ffa()) if (driver->mdm_ch && !IS_ERR(driver->mdm_ch)) diagfwd_disconnect_sdio(); #endif /* TBD - notify and flow control SMD */ return 0; } int diagfwd_write_complete(struct diag_request *diag_write_ptr) { unsigned char *buf = diag_write_ptr->buf; int found_it = 0; int i; /* Determine if the write complete is for data from modem/apps/q6 */ /* Need a context variable here instead */ for (i = 0; i < NUM_SMD_DATA_CHANNELS; i++) { struct diag_smd_info *data = &(driver->smd_data[i]); if (buf == (void *)data->buf_in_1) { data->in_busy_1 = 0; queue_work(driver->diag_wq, &(data->diag_read_smd_work)); found_it = 1; break; } else if (buf == (void *)data->buf_in_2) { data->in_busy_2 = 0; queue_work(driver->diag_wq, &(data->diag_read_smd_work)); found_it = 1; break; } } #ifdef CONFIG_DIAG_SDIO_PIPE if (!found_it) { if (buf == (void *)driver->buf_in_sdio) { if (machine_is_msm8x60_fusion() || machine_is_msm8x60_fusn_ffa()) diagfwd_write_complete_sdio(); else pr_err("diag: Incorrect buffer pointer while WRITE"); found_it = 1; } } #endif if (!found_it) { diagmem_free(driver, (unsigned char *)buf, POOL_TYPE_HDLC); diagmem_free(driver, (unsigned char *)diag_write_ptr, POOL_TYPE_WRITE_STRUCT); } return 0; } int diagfwd_read_complete(struct diag_request *diag_read_ptr) { int status = diag_read_ptr->status; unsigned char *buf = diag_read_ptr->buf; /* Determine if the read complete is for data on legacy/mdm ch */ if (buf == (void *)driver->usb_buf_out) { driver->read_len_legacy = diag_read_ptr->actual; APPEND_DEBUG('s'); #ifdef DIAG_DEBUG printk(KERN_INFO "read data from USB, pkt length %d", diag_read_ptr->actual); print_hex_dump(KERN_DEBUG, "Read Packet Data from USB: ", 16, 1, DUMP_PREFIX_ADDRESS, diag_read_ptr->buf, diag_read_ptr->actual, 1); #endif /* DIAG DEBUG */ if (driver->logging_mode == USB_MODE) { if (status != -ECONNRESET && status != -ESHUTDOWN) queue_work(driver->diag_wq, &(driver->diag_proc_hdlc_work)); else queue_work(driver->diag_wq, &(driver->diag_read_work)); } } #ifdef CONFIG_DIAG_SDIO_PIPE else if (buf == (void *)driver->usb_buf_mdm_out) { if (machine_is_msm8x60_fusion() || machine_is_msm8x60_fusn_ffa()) { driver->read_len_mdm = diag_read_ptr->actual; diagfwd_read_complete_sdio(); } else pr_err("diag: Incorrect buffer pointer while READ"); } #endif else printk(KERN_ERR "diag: Unknown buffer ptr from USB"); return 0; } void diag_read_work_fn(struct work_struct *work) { APPEND_DEBUG('d'); driver->usb_read_ptr->buf = driver->usb_buf_out; driver->usb_read_ptr->length = USB_MAX_OUT_BUF; usb_diag_read(driver->legacy_ch, driver->usb_read_ptr); APPEND_DEBUG('e'); } void diag_process_hdlc_fn(struct work_struct *work) { APPEND_DEBUG('D'); diag_process_hdlc(driver->usb_buf_out, driver->read_len_legacy); diag_read_work_fn(work); APPEND_DEBUG('E'); } void diag_usb_legacy_notifier(void *priv, unsigned event, struct diag_request *d_req) { switch (event) { case USB_DIAG_CONNECT: diagfwd_connect(); break; case USB_DIAG_DISCONNECT: diagfwd_disconnect(); break; case USB_DIAG_READ_DONE: diagfwd_read_complete(d_req); break; case USB_DIAG_WRITE_DONE: diagfwd_write_complete(d_req); break; default: printk(KERN_ERR "Unknown event from USB diag\n"); break; } } #endif /* DIAG OVER USB */ void diag_smd_notify(void *ctxt, unsigned event) { struct diag_smd_info *smd_info = (struct diag_smd_info *)ctxt; if (!smd_info) return; if (event == SMD_EVENT_CLOSE) { smd_info->ch = 0; wake_up(&driver->smd_wait_q); if (smd_info->type == SMD_DATA_TYPE) { smd_info->notify_context = event; queue_work(driver->diag_cntl_wq, &(smd_info->diag_notify_update_smd_work)); } else if (smd_info->type == SMD_DCI_TYPE) { /* Notify the clients of the close */ diag_dci_notify_client(smd_info->peripheral_mask, DIAG_STATUS_CLOSED); } return; } else if (event == SMD_EVENT_OPEN) { if (smd_info->ch_save) smd_info->ch = smd_info->ch_save; if (smd_info->type == SMD_CNTL_TYPE) { smd_info->notify_context = event; queue_work(driver->diag_cntl_wq, &(smd_info->diag_notify_update_smd_work)); } else if (smd_info->type == SMD_DCI_TYPE) { smd_info->notify_context = event; queue_work(driver->diag_dci_wq, &(smd_info->diag_notify_update_smd_work)); /* Notify the clients of the open */ diag_dci_notify_client(smd_info->peripheral_mask, DIAG_STATUS_OPEN); } } wake_up(&driver->smd_wait_q); if (smd_info->type == SMD_DCI_TYPE) queue_work(driver->diag_dci_wq, &(smd_info->diag_read_smd_work)); else queue_work(driver->diag_wq, &(smd_info->diag_read_smd_work)); } static int diag_smd_probe(struct platform_device *pdev) { int r = 0; int index = -1; if (pdev->id == SMD_APPS_MODEM) { index = MODEM_DATA; r = smd_open("DIAG", &driver->smd_data[index].ch, &driver->smd_data[index], diag_smd_notify); driver->smd_data[index].ch_save = driver->smd_data[index].ch; } #if defined(CONFIG_MSM_N_WAY_SMD) if (pdev->id == SMD_APPS_QDSP) { index = LPASS_DATA; r = smd_named_open_on_edge("DIAG", SMD_APPS_QDSP, &driver->smd_data[index].ch, &driver->smd_data[index], diag_smd_notify); driver->smd_data[index].ch_save = driver->smd_data[index].ch; } #endif if (pdev->id == SMD_APPS_WCNSS) { index = WCNSS_DATA; r = smd_named_open_on_edge("APPS_RIVA_DATA", SMD_APPS_WCNSS, &driver->smd_data[index].ch, &driver->smd_data[index], diag_smd_notify); driver->smd_data[index].ch_save = driver->smd_data[index].ch; } pm_runtime_set_active(&pdev->dev); pm_runtime_enable(&pdev->dev); pr_debug("diag: open SMD port, Id = %d, r = %d\n", pdev->id, r); return 0; } static int diag_smd_runtime_suspend(struct device *dev) { dev_dbg(dev, "pm_runtime: suspending...\n"); return 0; } static int diag_smd_runtime_resume(struct device *dev) { dev_dbg(dev, "pm_runtime: resuming...\n"); return 0; } static const struct dev_pm_ops diag_smd_dev_pm_ops = { .runtime_suspend = diag_smd_runtime_suspend, .runtime_resume = diag_smd_runtime_resume, }; static struct platform_driver msm_smd_ch1_driver = { .probe = diag_smd_probe, .driver = { .name = "DIAG", .owner = THIS_MODULE, .pm = &diag_smd_dev_pm_ops, }, }; static struct platform_driver diag_smd_lite_driver = { .probe = diag_smd_probe, .driver = { .name = "APPS_RIVA_DATA", .owner = THIS_MODULE, .pm = &diag_smd_dev_pm_ops, }, }; void diag_smd_destructor(struct diag_smd_info *smd_info) { if (smd_info->ch) smd_close(smd_info->ch); smd_info->ch = 0; smd_info->ch_save = 0; kfree(smd_info->buf_in_1); kfree(smd_info->buf_in_2); kfree(smd_info->write_ptr_1); kfree(smd_info->write_ptr_2); } int diag_smd_constructor(struct diag_smd_info *smd_info, int peripheral, int type) { smd_info->peripheral = peripheral; smd_info->type = type; switch (peripheral) { case MODEM_DATA: smd_info->peripheral_mask = DIAG_CON_MPSS; break; case LPASS_DATA: smd_info->peripheral_mask = DIAG_CON_LPASS; break; case WCNSS_DATA: smd_info->peripheral_mask = DIAG_CON_WCNSS; break; default: pr_err("diag: In %s, unknown peripheral, peripheral: %d\n", __func__, peripheral); goto err; } smd_info->ch = 0; smd_info->ch_save = 0; if (smd_info->buf_in_1 == NULL) { smd_info->buf_in_1 = kzalloc(IN_BUF_SIZE, GFP_KERNEL); if (smd_info->buf_in_1 == NULL) goto err; kmemleak_not_leak(smd_info->buf_in_1); } if (smd_info->write_ptr_1 == NULL) { smd_info->write_ptr_1 = kzalloc(sizeof(struct diag_request), GFP_KERNEL); if (smd_info->write_ptr_1 == NULL) goto err; kmemleak_not_leak(smd_info->write_ptr_1); } /* The smd data type needs two buffers */ if (smd_info->type == SMD_DATA_TYPE) { if (smd_info->buf_in_2 == NULL) { smd_info->buf_in_2 = kzalloc(IN_BUF_SIZE, GFP_KERNEL); if (smd_info->buf_in_2 == NULL) goto err; kmemleak_not_leak(smd_info->buf_in_2); } if (smd_info->write_ptr_2 == NULL) { smd_info->write_ptr_2 = kzalloc(sizeof(struct diag_request), GFP_KERNEL); if (smd_info->write_ptr_2 == NULL) goto err; kmemleak_not_leak(smd_info->write_ptr_2); } } INIT_WORK(&(smd_info->diag_read_smd_work), diag_read_smd_work_fn); /* * The update function assigned to the diag_notify_update_smd_work * work_struct is meant to be used for updating that is not to * be done in the context of the smd notify function. The * notify_context variable can be used for passing additional * information to the update function. */ smd_info->notify_context = 0; if (type == SMD_DATA_TYPE) INIT_WORK(&(smd_info->diag_notify_update_smd_work), diag_clean_reg_fn); else if (type == SMD_CNTL_TYPE) INIT_WORK(&(smd_info->diag_notify_update_smd_work), diag_mask_update_fn); else if (type == SMD_DCI_TYPE) INIT_WORK(&(smd_info->diag_notify_update_smd_work), diag_update_smd_dci_work_fn); else { pr_err("diag: In %s, unknown type, type: %d\n", __func__, type); goto err; } /* * Set function ptr for function to call to process the data that * was just read from the smd channel */ if (type == SMD_DATA_TYPE) smd_info->process_smd_read_data = diag_process_smd_read_data; else if (type == SMD_CNTL_TYPE) smd_info->process_smd_read_data = diag_process_smd_cntl_read_data; else if (type == SMD_DCI_TYPE) smd_info->process_smd_read_data = diag_process_smd_dci_read_data; else { pr_err("diag: In %s, unknown type, type: %d\n", __func__, type); goto err; } return 1; err: kfree(smd_info->buf_in_1); kfree(smd_info->buf_in_2); kfree(smd_info->write_ptr_1); kfree(smd_info->write_ptr_2); return 0; } void diagfwd_init(void) { int success; int i; wrap_enabled = 0; wrap_count = 0; diag_debug_buf_idx = 0; driver->read_len_legacy = 0; driver->use_device_tree = has_device_tree(); mutex_init(&driver->diag_cntl_mutex); success = diag_smd_constructor(&driver->smd_data[MODEM_DATA], MODEM_DATA, SMD_DATA_TYPE); if (!success) goto err; success = diag_smd_constructor(&driver->smd_data[LPASS_DATA], LPASS_DATA, SMD_DATA_TYPE); if (!success) goto err; success = diag_smd_constructor(&driver->smd_data[WCNSS_DATA], WCNSS_DATA, SMD_DATA_TYPE); if (!success) goto err; if (driver->usb_buf_out == NULL && (driver->usb_buf_out = kzalloc(USB_MAX_OUT_BUF, GFP_KERNEL)) == NULL) goto err; kmemleak_not_leak(driver->usb_buf_out); if (driver->hdlc_buf == NULL && (driver->hdlc_buf = kzalloc(HDLC_MAX, GFP_KERNEL)) == NULL) goto err; kmemleak_not_leak(driver->hdlc_buf); if (driver->user_space_data == NULL) driver->user_space_data = kzalloc(USER_SPACE_DATA, GFP_KERNEL); if (driver->user_space_data == NULL) goto err; kmemleak_not_leak(driver->user_space_data); if (driver->client_map == NULL && (driver->client_map = kzalloc ((driver->num_clients) * sizeof(struct diag_client_map), GFP_KERNEL)) == NULL) goto err; kmemleak_not_leak(driver->client_map); if (driver->buf_tbl == NULL) driver->buf_tbl = kzalloc(buf_tbl_size * sizeof(struct diag_write_device), GFP_KERNEL); if (driver->buf_tbl == NULL) goto err; kmemleak_not_leak(driver->buf_tbl); if (driver->data_ready == NULL && (driver->data_ready = kzalloc(driver->num_clients * sizeof(int) , GFP_KERNEL)) == NULL) goto err; kmemleak_not_leak(driver->data_ready); if (driver->table == NULL && (driver->table = kzalloc(diag_max_reg* sizeof(struct diag_master_table), GFP_KERNEL)) == NULL) goto err; kmemleak_not_leak(driver->table); if (driver->usb_read_ptr == NULL) { driver->usb_read_ptr = kzalloc( sizeof(struct diag_request), GFP_KERNEL); if (driver->usb_read_ptr == NULL) goto err; kmemleak_not_leak(driver->usb_read_ptr); } if (driver->pkt_buf == NULL && (driver->pkt_buf = kzalloc(PKT_SIZE, GFP_KERNEL)) == NULL) goto err; kmemleak_not_leak(driver->pkt_buf); if (driver->apps_rsp_buf == NULL) { driver->apps_rsp_buf = kzalloc(APPS_BUF_SIZE, GFP_KERNEL); if (driver->apps_rsp_buf == NULL) goto err; kmemleak_not_leak(driver->apps_rsp_buf); } driver->diag_wq = create_singlethread_workqueue("diag_wq"); #ifdef CONFIG_DIAG_OVER_USB INIT_WORK(&(driver->diag_proc_hdlc_work), diag_process_hdlc_fn); INIT_WORK(&(driver->diag_read_work), diag_read_work_fn); driver->legacy_ch = usb_diag_open(DIAG_LEGACY, driver, diag_usb_legacy_notifier); if (IS_ERR(driver->legacy_ch)) { printk(KERN_ERR "Unable to open USB diag legacy channel\n"); goto err; } #endif platform_driver_register(&msm_smd_ch1_driver); platform_driver_register(&diag_smd_lite_driver); return; err: pr_err("diag: Could not initialize diag buffers"); for (i = 0; i < NUM_SMD_DATA_CHANNELS; i++) diag_smd_destructor(&driver->smd_data[i]); kfree(driver->buf_msg_mask_update); kfree(driver->buf_log_mask_update); kfree(driver->buf_event_mask_update); kfree(driver->usb_buf_out); kfree(driver->hdlc_buf); kfree(driver->client_map); kfree(driver->buf_tbl); kfree(driver->data_ready); kfree(driver->table); kfree(driver->pkt_buf); kfree(driver->usb_read_ptr); kfree(driver->apps_rsp_buf); kfree(driver->user_space_data); if (driver->diag_wq) destroy_workqueue(driver->diag_wq); } void diagfwd_exit(void) { int i; for (i = 0; i < NUM_SMD_DATA_CHANNELS; i++) diag_smd_destructor(&driver->smd_data[i]); #ifdef CONFIG_DIAG_OVER_USB if (driver->usb_connected) usb_diag_free_req(driver->legacy_ch); usb_diag_close(driver->legacy_ch); #endif platform_driver_unregister(&msm_smd_ch1_driver); platform_driver_unregister(&msm_diag_dci_driver); platform_driver_unregister(&diag_smd_lite_driver); kfree(driver->buf_msg_mask_update); kfree(driver->buf_log_mask_update); kfree(driver->buf_event_mask_update); kfree(driver->usb_buf_out); kfree(driver->hdlc_buf); kfree(driver->client_map); kfree(driver->buf_tbl); kfree(driver->data_ready); kfree(driver->table); kfree(driver->pkt_buf); kfree(driver->usb_read_ptr); kfree(driver->apps_rsp_buf); kfree(driver->user_space_data); destroy_workqueue(driver->diag_wq); }
paul-xxx/kernel_sony_fuji-3.7
drivers/char/diag/diagfwd.c
C
gpl-2.0
47,466
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_show_tab.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: pgritsen <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/08/05 19:31:02 by pgritsen #+# #+# */ /* Updated: 2017/08/05 19:31:04 by pgritsen ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_stock_par.h" void ft_putchar(char c); void ft_putstr(char *str) { int it; it = 0; while (str[it] != 0) ft_putchar(str[it++]); } void ft_putnbr(int nb) { long int mult; long int nb_t; mult = 1; nb_t = nb; if (nb_t < 0) { ft_putchar('-'); nb_t *= -1; } if (nb_t == 0) ft_putchar('0'); while (nb_t / mult != 0) mult *= 10; while (mult > 1) { mult /= 10; if (mult == 0) ft_putchar(nb_t + 48); else ft_putchar(nb_t / mult + 48); nb_t %= mult; } } void ft_show_tab(struct s_stock_par *par) { int it; int argv_it; it = 0; while (par[it].str) { ft_putstr(par[it].copy); ft_putchar('\n'); ft_putnbr(par[it].size_param); ft_putchar('\n'); argv_it = 0; while (par[it].tab[argv_it]) { ft_putstr(par[it].tab[argv_it]); ft_putchar('\n'); argv_it++; } it++; } }
CoZZmOnAvT/42-Piscine-C
d08/tmp/ex06/ft_show_tab.c
C
gpl-3.0
1,733
#ifdef TI83P # include <ti83pdefs.h> # include <ti83p.h> void YName() __naked { __asm push af push hl push iy ld iy,#flags___dw BCALL(_YName___db) pop iy pop hl pop af ret __endasm; } #endif
catastropher/tisdcc-deadproject
lib/old/YName.c
C
gpl-3.0
193
/** * This file is part of Hercules. * http://herc.ws - http://github.com/HerculesWS/Hercules * * Copyright (C) 2012-2015 Hercules Dev Team * Copyright (C) Athena Dev Teams * * Hercules 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. * * This program 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 this program. If not, see <http://www.gnu.org/licenses/>. */ #define HERCULES_CORE #include "conf.h" #include "common/showmsg.h" // ShowError #include "common/strlib.h" // safestrncpy #include "common/utils.h" // exists #include <libconfig/libconfig.h> /* interface source */ struct libconfig_interface libconfig_s; struct libconfig_interface *libconfig; /** * Initializes 'config' and loads a configuration file. * * Shows error and destroys 'config' in case of failure. * It is the caller's care to destroy 'config' in case of success. * * @param config The config file to initialize. * @param config_filename The file to read. * * @retval CONFIG_TRUE in case of success. * @retval CONFIG_FALSE in case of failure. */ int config_load_file(struct config_t *config, const char *config_filename) { libconfig->init(config); if (!exists(config_filename)) { ShowError("Unable to load '%s' - File not found\n", config_filename); return CONFIG_FALSE; } if (libconfig->read_file_src(config, config_filename) != CONFIG_TRUE) { ShowError("%s:%d - %s\n", config_error_file(config), config_error_line(config), config_error_text(config)); libconfig->destroy(config); return CONFIG_FALSE; } return CONFIG_TRUE; } // // Functions to copy settings from libconfig/contrib // void config_setting_copy_simple(struct config_setting_t *parent, const struct config_setting_t *src) { if (config_setting_is_aggregate(src)) { libconfig->setting_copy_aggregate(parent, src); } else { struct config_setting_t *set; if( libconfig->setting_get_member(parent, config_setting_name(src)) != NULL ) return; if ((set = libconfig->setting_add(parent, config_setting_name(src), config_setting_type(src))) == NULL) return; if (CONFIG_TYPE_INT == config_setting_type(src)) { libconfig->setting_set_int(set, libconfig->setting_get_int(src)); libconfig->setting_set_format(set, src->format); } else if (CONFIG_TYPE_INT64 == config_setting_type(src)) { libconfig->setting_set_int64(set, libconfig->setting_get_int64(src)); libconfig->setting_set_format(set, src->format); } else if (CONFIG_TYPE_FLOAT == config_setting_type(src)) { libconfig->setting_set_float(set, libconfig->setting_get_float(src)); } else if (CONFIG_TYPE_STRING == config_setting_type(src)) { libconfig->setting_set_string(set, libconfig->setting_get_string(src)); } else if (CONFIG_TYPE_BOOL == config_setting_type(src)) { libconfig->setting_set_bool(set, libconfig->setting_get_bool(src)); } } } void config_setting_copy_elem(struct config_setting_t *parent, const struct config_setting_t *src) { struct config_setting_t *set = NULL; if (config_setting_is_aggregate(src)) libconfig->setting_copy_aggregate(parent, src); else if (CONFIG_TYPE_INT == config_setting_type(src)) { set = libconfig->setting_set_int_elem(parent, -1, libconfig->setting_get_int(src)); libconfig->setting_set_format(set, src->format); } else if (CONFIG_TYPE_INT64 == config_setting_type(src)) { set = libconfig->setting_set_int64_elem(parent, -1, libconfig->setting_get_int64(src)); libconfig->setting_set_format(set, src->format); } else if (CONFIG_TYPE_FLOAT == config_setting_type(src)) { libconfig->setting_set_float_elem(parent, -1, libconfig->setting_get_float(src)); } else if (CONFIG_TYPE_STRING == config_setting_type(src)) { libconfig->setting_set_string_elem(parent, -1, libconfig->setting_get_string(src)); } else if (CONFIG_TYPE_BOOL == config_setting_type(src)) { libconfig->setting_set_bool_elem(parent, -1, libconfig->setting_get_bool(src)); } } void config_setting_copy_aggregate(struct config_setting_t *parent, const struct config_setting_t *src) { struct config_setting_t *newAgg; int i, n; if( libconfig->setting_get_member(parent, config_setting_name(src)) != NULL ) return; newAgg = libconfig->setting_add(parent, config_setting_name(src), config_setting_type(src)); if (newAgg == NULL) return; n = config_setting_length(src); for (i = 0; i < n; i++) { if (config_setting_is_group(src)) { libconfig->setting_copy_simple(newAgg, libconfig->setting_get_elem(src, i)); } else { libconfig->setting_copy_elem(newAgg, libconfig->setting_get_elem(src, i)); } } } int config_setting_copy(struct config_setting_t *parent, const struct config_setting_t *src) { if (!config_setting_is_group(parent) && !config_setting_is_list(parent)) return CONFIG_FALSE; if (config_setting_is_aggregate(src)) { libconfig->setting_copy_aggregate(parent, src); } else { libconfig->setting_copy_simple(parent, src); } return CONFIG_TRUE; } /** * Converts the value of a setting that is type CONFIG_TYPE_BOOL to bool. * * @param setting The setting to read. * * @return The converted value. * @retval false in case of failure. */ bool config_setting_get_bool_real(const struct config_setting_t *setting) { if (setting == NULL || setting->type != CONFIG_TYPE_BOOL) return false; return setting->value.ival ? true : false; } /** * Same as config_setting_lookup_bool, but uses bool instead of int. * * @param[in] setting The setting to read. * @param[in] name The setting name to lookup. * @param[out] value The output value. * * @retval CONFIG_TRUE in case of success. * @retval CONFIG_FALSE in case of failure. */ int config_setting_lookup_bool_real(const struct config_setting_t *setting, const char *name, bool *value) { struct config_setting_t *member = config_setting_get_member(setting, name); if (!member) return CONFIG_FALSE; if (config_setting_type(member) != CONFIG_TYPE_BOOL) return CONFIG_FALSE; *value = config_setting_get_bool_real(member); return CONFIG_TRUE; } /** * Converts and returns a configuration that is CONFIG_TYPE_INT to unsigned int (uint32). * * @param setting The setting to read. * * @return The converted value. * @retval 0 in case of failure. */ uint32 config_setting_get_uint32(const struct config_setting_t *setting) { if (setting == NULL || setting->type != CONFIG_TYPE_INT) return 0; if (setting->value.ival < 0) return 0; return (uint32)setting->value.ival; } /** * Looks up a configuration entry of type CONFIG_TYPE_INT and reads it as uint32. * * @param[in] setting The setting to read. * @param[in] name The setting name to lookup. * @param[out] value The output value. * * @retval CONFIG_TRUE in case of success. * @retval CONFIG_FALSE in case of failure. */ int config_setting_lookup_uint32(const struct config_setting_t *setting, const char *name, uint32 *value) { struct config_setting_t *member = config_setting_get_member(setting, name); if (!member) return CONFIG_FALSE; if (config_setting_type(member) != CONFIG_TYPE_INT) return CONFIG_FALSE; *value = config_setting_get_uint32(member); return CONFIG_TRUE; } /** * Converts and returns a configuration that is CONFIG_TYPE_INT to uint16 * * @param setting The setting to read. * * @return The converted value. * @retval 0 in case of failure. */ uint16 config_setting_get_uint16(const struct config_setting_t *setting) { if (setting == NULL || setting->type != CONFIG_TYPE_INT) return 0; if (setting->value.ival > UINT16_MAX) return UINT16_MAX; if (setting->value.ival < UINT16_MIN) return UINT16_MIN; return (uint16)setting->value.ival; } /** * Looks up a configuration entry of type CONFIG_TYPE_INT and reads it as uint16. * * @param[in] setting The setting to read. * @param[in] name The setting name to lookup. * @param[out] value The output value. * * @retval CONFIG_TRUE in case of success. * @retval CONFIG_FALSE in case of failure. */ int config_setting_lookup_uint16(const struct config_setting_t *setting, const char *name, uint16 *value) { struct config_setting_t *member = config_setting_get_member(setting, name); if (!member) return CONFIG_FALSE; if (config_setting_type(member) != CONFIG_TYPE_INT) return CONFIG_FALSE; *value = config_setting_get_uint16(member); return CONFIG_TRUE; } /** * Converts and returns a configuration that is CONFIG_TYPE_INT to int16 * * @param setting The setting to read. * * @return The converted value. * @retval 0 in case of failure. */ int16 config_setting_get_int16(const struct config_setting_t *setting) { if (setting == NULL || setting->type != CONFIG_TYPE_INT) return 0; if (setting->value.ival > INT16_MAX) return INT16_MAX; if (setting->value.ival < INT16_MIN) return INT16_MIN; return (int16)setting->value.ival; } /** * Looks up a configuration entry of type CONFIG_TYPE_INT and reads it as int16. * * @param[in] setting The setting to read. * @param[in] name The setting name to lookup. * @param[out] value The output value. * * @retval CONFIG_TRUE in case of success. * @retval CONFIG_FALSE in case of failure. */ int config_setting_lookup_int16(const struct config_setting_t *setting, const char *name, int16 *value) { struct config_setting_t *member = config_setting_get_member(setting, name); if (!member) return CONFIG_FALSE; if (config_setting_type(member) != CONFIG_TYPE_INT) return CONFIG_FALSE; *value = config_setting_get_int16(member); return CONFIG_TRUE; } /** * Looks up a configuration entry of type CONFIG_TYPE_STRING inside a struct config_setting_t and copies it into a (non-const) char buffer. * * @param[in] setting The setting to read. * @param[in] name The setting name to lookup. * @param[out] out The output buffer. * @param[in] out_size The size of the output buffer. * * @retval CONFIG_TRUE in case of success. * @retval CONFIG_FALSE in case of failure. */ int config_setting_lookup_mutable_string(const struct config_setting_t *setting, const char *name, char *out, size_t out_size) { const char *str = NULL; if (libconfig->setting_lookup_string(setting, name, &str) == CONFIG_TRUE) { safestrncpy(out, str, out_size); return CONFIG_TRUE; } return CONFIG_FALSE; } /** * Looks up a configuration entry of type CONFIG_TYPE_STRING inside a struct config_t and copies it into a (non-const) char buffer. * * @param[in] config The configuration to read. * @param[in] name The setting name to lookup. * @param[out] out The output buffer. * @param[in] out_size The size of the output buffer. * * @retval CONFIG_TRUE in case of success. * @retval CONFIG_FALSE in case of failure. */ int config_lookup_mutable_string(const struct config_t *config, const char *name, char *out, size_t out_size) { const char *str = NULL; if (libconfig->lookup_string(config, name, &str) == CONFIG_TRUE) { safestrncpy(out, str, out_size); return CONFIG_TRUE; } return CONFIG_FALSE; } void libconfig_defaults(void) { libconfig = &libconfig_s; libconfig->read = config_read; libconfig->write = config_write; /* */ libconfig->set_options = config_set_options; libconfig->get_options = config_get_options; /* */ libconfig->read_string = config_read_string; libconfig->read_file_src = config_read_file; libconfig->write_file = config_write_file; /* */ libconfig->set_destructor = config_set_destructor; libconfig->set_include_dir = config_set_include_dir; /* */ libconfig->init = config_init; libconfig->destroy = config_destroy; /* */ libconfig->setting_get_int = config_setting_get_int; libconfig->setting_get_int64 = config_setting_get_int64; libconfig->setting_get_float = config_setting_get_float; libconfig->setting_get_bool = config_setting_get_bool; libconfig->setting_get_string = config_setting_get_string; /* */ libconfig->setting_lookup = config_setting_lookup; libconfig->setting_lookup_int = config_setting_lookup_int; libconfig->setting_lookup_int64 = config_setting_lookup_int64; libconfig->setting_lookup_float = config_setting_lookup_float; libconfig->setting_lookup_bool = config_setting_lookup_bool; libconfig->setting_lookup_string = config_setting_lookup_string; /* */ libconfig->setting_set_int = config_setting_set_int; libconfig->setting_set_int64 = config_setting_set_int64; libconfig->setting_set_float = config_setting_set_float; libconfig->setting_set_bool = config_setting_set_bool; libconfig->setting_set_string = config_setting_set_string; /* */ libconfig->setting_set_format = config_setting_set_format; libconfig->setting_get_format = config_setting_get_format; /* */ libconfig->setting_get_int_elem = config_setting_get_int_elem; libconfig->setting_get_int64_elem = config_setting_get_int64_elem; libconfig->setting_get_float_elem = config_setting_get_float_elem; libconfig->setting_get_bool_elem = config_setting_get_bool_elem; libconfig->setting_get_string_elem = config_setting_get_string_elem; /* */ libconfig->setting_set_int_elem = config_setting_set_int_elem; libconfig->setting_set_int64_elem = config_setting_set_int64_elem; libconfig->setting_set_float_elem = config_setting_set_float_elem; libconfig->setting_set_bool_elem = config_setting_set_bool_elem; libconfig->setting_set_string_elem = config_setting_set_string_elem; /* */ libconfig->setting_index = config_setting_index; libconfig->setting_length = config_setting_length; /* */ libconfig->setting_get_elem = config_setting_get_elem; libconfig->setting_get_member = config_setting_get_member; /* */ libconfig->setting_add = config_setting_add; libconfig->setting_remove = config_setting_remove; libconfig->setting_remove_elem = config_setting_remove_elem; /* */ libconfig->setting_set_hook = config_setting_set_hook; /* */ libconfig->lookup = config_lookup; /* */ libconfig->lookup_int = config_lookup_int; libconfig->lookup_int64 = config_lookup_int64; libconfig->lookup_float = config_lookup_float; libconfig->lookup_bool = config_lookup_bool; libconfig->lookup_string = config_lookup_string; /* those are custom and are from src/common/conf.c */ libconfig->load_file = config_load_file; libconfig->setting_copy_simple = config_setting_copy_simple; libconfig->setting_copy_elem = config_setting_copy_elem; libconfig->setting_copy_aggregate = config_setting_copy_aggregate; libconfig->setting_copy = config_setting_copy; /* Functions to get different types */ libconfig->setting_get_bool_real = config_setting_get_bool_real; libconfig->setting_get_uint32 = config_setting_get_uint32; libconfig->setting_get_uint16 = config_setting_get_uint16; libconfig->setting_get_int16 = config_setting_get_int16; /* Functions to lookup different types */ libconfig->setting_lookup_int16 = config_setting_lookup_int16; libconfig->setting_lookup_bool_real = config_setting_lookup_bool_real; libconfig->setting_lookup_uint32 = config_setting_lookup_uint32; libconfig->setting_lookup_uint16 = config_setting_lookup_uint16; libconfig->setting_lookup_mutable_string = config_setting_lookup_mutable_string; libconfig->lookup_mutable_string = config_lookup_mutable_string; }
dor003/Herc
src/common/conf.c
C
gpl-3.0
15,602
/* dev: Mickeymouse, Moutarde and Nepta manager: Word Copyright © 2011 You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "bullet.h" /** * \fn Bullet* createBullet(Tower *tower) * \brief create a new bullet * a new bullet which doesn't have * \param tower the tower the bullet belong to */ Bullet* createBullet(Tower *tower){ Bullet *bullet = malloc(sizeof (Bullet)); bullet->type = tower->type->typeBul; bullet->position = searchEnemy(tower); return bullet; } /** * \fn void drawBullet(Bullet *bullet) * \brief draw a bullet * * \param bullet a bullet to draw */ void drawBullet(Bullet *bullet){ SDL_Rect position; position.x = 280; //=xx position.y = 280; //=yy blitToViewport(_viewport, bullet->type->image, NULL, &position); } /** * \fn void animateBullet(Bullet *bullet) * \brief move the bullet to an enemy and draw it * Depreciated, recode your own function! * \param bullet the bullet to animate */ void animateBullet(Bullet *bullet){ /* if(!(bullet->position->xx == bullet->position->x && bullet->position->yy == bullet->position->y)){*/ drawBullet(bullet); /* }*/ }
ycaihua/Tower-Defense-1
src/tower/bullet.c
C
gpl-3.0
1,216
/****************************************************************\ * * * Library for HSP sets (high-scoring segment pairs) * * * * Guy St.C. Slater.. mailto:guy@ebi.ac.uk * * Copyright (C) 2000-2008. All Rights Reserved. * * * * This source code is distributed under the terms of the * * GNU General Public License, version 3. See the file COPYING * * or http://www.gnu.org/licenses/gpl.txt for details * * * * If you use this code, please keep this notice intact. * * * \****************************************************************/ #include <string.h> /* For strlen() */ #include <ctype.h> /* For tolower() */ #include <stdlib.h> /* For qsort() */ #include "hspset.h" HSPset_ArgumentSet *HSPset_ArgumentSet_create(Argument *arg){ register ArgumentSet *as; static HSPset_ArgumentSet has = {0}; if(arg){ as = ArgumentSet_create("HSP creation options"); ArgumentSet_add_option(as, '\0', "hspfilter", NULL, "Aggressive HSP filtering level", "0", Argument_parse_int, &has.filter_threshold); ArgumentSet_add_option(as, '\0', "useworddropoff", NULL, "Use word neighbourhood dropoff", "TRUE", Argument_parse_boolean, &has.use_wordhood_dropoff); ArgumentSet_add_option(as, '\0', "seedrepeat", NULL, "Seeds per diagonal required for HSP seeding", "1", Argument_parse_int, &has.seed_repeat); /**/ ArgumentSet_add_option(as, 0, "dnawordlen", "bp", "Wordlength for DNA words", "12", Argument_parse_int, &has.dna_wordlen); ArgumentSet_add_option(as, 0, "proteinwordlen", "aa", "Wordlength for protein words", "6", Argument_parse_int, &has.protein_wordlen); ArgumentSet_add_option(as, 0, "codonwordlen", "bp", "Wordlength for codon words", "12", Argument_parse_int, &has.codon_wordlen); /**/ ArgumentSet_add_option(as, 0, "dnahspdropoff", "score", "DNA HSP dropoff score", "30", Argument_parse_int, &has.dna_hsp_dropoff); ArgumentSet_add_option(as, 0, "proteinhspdropoff", "score", "Protein HSP dropoff score", "20", Argument_parse_int, &has.protein_hsp_dropoff); ArgumentSet_add_option(as, 0, "codonhspdropoff", "score", "Codon HSP dropoff score", "40", Argument_parse_int, &has.codon_hsp_dropoff); /**/ ArgumentSet_add_option(as, 0, "dnahspthreshold", "score", "DNA HSP threshold score", "75", Argument_parse_int, &has.dna_hsp_threshold); ArgumentSet_add_option(as, 0, "proteinhspthreshold", "score", "Protein HSP threshold score", "30", Argument_parse_int, &has.protein_hsp_threshold); ArgumentSet_add_option(as, 0, "codonhspthreshold", "score", "Codon HSP threshold score", "50", Argument_parse_int, &has.codon_hsp_threshold); /**/ ArgumentSet_add_option(as, 0, "dnawordlimit", "score", "Score limit for dna word neighbourhood", "0", Argument_parse_int, &has.dna_wordlimit); ArgumentSet_add_option(as, 0, "proteinwordlimit", "score", "Score limit for protein word neighbourhood", "4", Argument_parse_int, &has.protein_wordlimit); ArgumentSet_add_option(as, 0, "codonwordlimit", "score", "Score limit for codon word neighbourhood", "4", Argument_parse_int, &has.codon_wordlimit); /**/ ArgumentSet_add_option(as, '\0', "geneseed", "threshold", "Geneseed Threshold", "0", Argument_parse_int, &has.geneseed_threshold); ArgumentSet_add_option(as, '\0', "geneseedrepeat", "number", "Seeds per diagonal required for geneseed HSP seeding", "3", Argument_parse_int, &has.geneseed_repeat); /**/ Argument_absorb_ArgumentSet(arg, as); } return &has; } /**/ static gboolean HSP_check_positions(HSPset *hsp_set, gint query_pos, gint target_pos){ g_assert(query_pos >= 0); g_assert(target_pos >= 0); g_assert(query_pos < hsp_set->query->len); g_assert(target_pos < hsp_set->target->len); return TRUE; } static gboolean HSP_check(HSP *hsp){ g_assert(hsp); g_assert(hsp->hsp_set); g_assert(hsp->length); g_assert(HSP_query_end(hsp) <= hsp->hsp_set->query->len); g_assert(HSP_target_end(hsp) <= hsp->hsp_set->target->len); return TRUE; } void HSP_Param_set_wordlen(HSP_Param *hsp_param, gint wordlen){ if(wordlen <= 0) g_error("Wordlength must be greater than zero"); hsp_param->wordlen = wordlen; hsp_param->seedlen = hsp_param->wordlen / hsp_param->match->query->advance; return; } /**/ void HSP_Param_set_dna_hsp_threshold(HSP_Param *hsp_param, gint dna_hsp_threshold){ if(hsp_param->match->type == Match_Type_DNA2DNA) hsp_param->threshold = dna_hsp_threshold; return; } void HSP_Param_set_protein_hsp_threshold(HSP_Param *hsp_param, gint protein_hsp_threshold){ if((hsp_param->match->type == Match_Type_PROTEIN2PROTEIN) || (hsp_param->match->type == Match_Type_PROTEIN2DNA) || (hsp_param->match->type == Match_Type_DNA2PROTEIN)) hsp_param->threshold = protein_hsp_threshold; return; } void HSP_Param_set_codon_hsp_threshold(HSP_Param *hsp_param, gint codon_hsp_threshold){ if(hsp_param->match->type == Match_Type_CODON2CODON) hsp_param->threshold = codon_hsp_threshold; return; } /**/ void HSP_Param_set_dna_hsp_dropoff(HSP_Param *hsp_param, gint dna_hsp_dropoff){ if(hsp_param->match->type == Match_Type_DNA2DNA) hsp_param->dropoff = dna_hsp_dropoff; return; } void HSP_Param_set_protein_hsp_dropoff(HSP_Param *hsp_param, gint protein_hsp_dropoff){ if((hsp_param->match->type == Match_Type_PROTEIN2PROTEIN) || (hsp_param->match->type == Match_Type_PROTEIN2DNA) || (hsp_param->match->type == Match_Type_DNA2PROTEIN)) hsp_param->dropoff = protein_hsp_dropoff; return; } void HSP_Param_set_codon_hsp_dropoff(HSP_Param *hsp_param, gint codon_hsp_dropoff){ if(hsp_param->match->type == Match_Type_CODON2CODON) hsp_param->dropoff = codon_hsp_dropoff; return; } /**/ void HSP_Param_set_hsp_threshold(HSP_Param *hsp_param, gint hsp_threshold){ hsp_param->threshold = hsp_threshold; return; } void HSP_Param_set_seed_repeat(HSP_Param *hsp_param, gint seed_repeat){ hsp_param->seed_repeat = seed_repeat; return; } HSP_Param *HSP_Param_create(Match *match, gboolean use_horizon){ register HSP_Param *hsp_param = g_new(HSP_Param, 1); register WordHood_Alphabet *wha = NULL; register Submat *submat; hsp_param->ref_count = 1; hsp_param->has = HSPset_ArgumentSet_create(NULL); hsp_param->match = match; hsp_param->seed_repeat = hsp_param->has->seed_repeat; switch(match->type){ case Match_Type_DNA2DNA: hsp_param->dropoff = hsp_param->has->dna_hsp_dropoff; hsp_param->threshold = hsp_param->has->dna_hsp_threshold; HSP_Param_set_wordlen(hsp_param, hsp_param->has->dna_wordlen); hsp_param->wordlimit = hsp_param->has->dna_wordlimit; break; case Match_Type_PROTEIN2PROTEIN: /*fallthrough*/ case Match_Type_PROTEIN2DNA: /*fallthrough*/ case Match_Type_DNA2PROTEIN: hsp_param->dropoff = hsp_param->has->protein_hsp_dropoff; hsp_param->threshold = hsp_param->has->protein_hsp_threshold; HSP_Param_set_wordlen(hsp_param, hsp_param->has->protein_wordlen); hsp_param->wordlimit = hsp_param->has->protein_wordlimit; break; case Match_Type_CODON2CODON: hsp_param->dropoff = hsp_param->has->codon_hsp_dropoff; hsp_param->threshold = hsp_param->has->codon_hsp_threshold; HSP_Param_set_wordlen(hsp_param, hsp_param->has->codon_wordlen); hsp_param->wordlimit = hsp_param->has->codon_wordlimit; g_assert(!(hsp_param->wordlen % 3)); break; default: g_error("Bad Match_Type [%d]", match->type); break; } hsp_param->use_horizon = use_horizon; if(hsp_param->has->use_wordhood_dropoff && (!hsp_param->wordlimit)){ hsp_param->wordhood = NULL; } else { submat = (match->type == Match_Type_DNA2DNA) ? match->mas->dna_submat : match->mas->protein_submat; wha = WordHood_Alphabet_create_from_Submat( (gchar*)match->comparison_alphabet->member, (gchar*)match->comparison_alphabet->member, submat, FALSE); g_assert(wha); hsp_param->wordhood = WordHood_create(wha, hsp_param->wordlimit, hsp_param->has->use_wordhood_dropoff); WordHood_Alphabet_destroy(wha); } return hsp_param; } void HSP_Param_destroy(HSP_Param *hsp_param){ g_assert(hsp_param); if(--hsp_param->ref_count) return; if(hsp_param->wordhood) WordHood_destroy(hsp_param->wordhood); g_free(hsp_param); return; } HSP_Param *HSP_Param_share(HSP_Param *hsp_param){ g_assert(hsp_param); hsp_param->ref_count++; return hsp_param; } HSP_Param *HSP_Param_swap(HSP_Param *hsp_param){ g_assert(hsp_param); return HSP_Param_create(Match_swap(hsp_param->match), hsp_param->use_horizon); } static RecycleBin *global_hsp_recycle_bin = NULL; HSPset *HSPset_create(Sequence *query, Sequence *target, HSP_Param *hsp_param){ register HSPset *hsp_set = g_new(HSPset, 1); g_assert(query); g_assert(target); hsp_set->ref_count = 1; hsp_set->query = Sequence_share(query); hsp_set->target = Sequence_share(target); hsp_set->param = HSP_Param_share(hsp_param); /**/ if(global_hsp_recycle_bin){ hsp_set->hsp_recycle = RecycleBin_share(global_hsp_recycle_bin); } else { global_hsp_recycle_bin = RecycleBin_create("HSP", sizeof(HSP), 64); hsp_set->hsp_recycle = global_hsp_recycle_bin; } if(hsp_param->use_horizon){ hsp_set->horizon = (gint****)Matrix4d_create( 1 + ((hsp_param->seed_repeat > 1)?1:0), query->len, hsp_param->match->query->advance, hsp_param->match->target->advance, sizeof(gint)); } else { hsp_set->horizon = NULL; } hsp_set->hsp_list = g_ptr_array_new(); hsp_set->is_finalised = FALSE; hsp_set->param->has = HSPset_ArgumentSet_create(NULL); if(hsp_set->param->has->filter_threshold){ hsp_set->filter = g_new0(PQueue*, query->len); hsp_set->pqueue_set = PQueueSet_create(); } else { hsp_set->filter = NULL; hsp_set->pqueue_set = NULL; } hsp_set->is_empty = TRUE; return hsp_set; } /**/ HSPset *HSPset_share(HSPset *hsp_set){ g_assert(hsp_set); hsp_set->ref_count++; return hsp_set; } void HSPset_destroy(HSPset *hsp_set){ register gint i; register HSP *hsp; g_assert(hsp_set); if(--hsp_set->ref_count) return; HSP_Param_destroy(hsp_set->param); if(hsp_set->filter) g_free(hsp_set->filter); if(hsp_set->pqueue_set) PQueueSet_destroy(hsp_set->pqueue_set); Sequence_destroy(hsp_set->query); Sequence_destroy(hsp_set->target); for(i = 0; i < hsp_set->hsp_list->len; i++){ hsp = hsp_set->hsp_list->pdata[i]; HSP_destroy(hsp); } g_ptr_array_free(hsp_set->hsp_list, TRUE); if(hsp_set->hsp_recycle->ref_count == 1) /* last active hsp_set */ global_hsp_recycle_bin = NULL; RecycleBin_destroy(hsp_set->hsp_recycle); if(hsp_set->horizon) g_free(hsp_set->horizon); g_free(hsp_set); return; } void HSPset_swap(HSPset *hsp_set, HSP_Param *hsp_param){ register Sequence *query; register gint i, query_start; register HSP *hsp; g_assert(hsp_set->ref_count == 1); /* Swap query and target */ query = hsp_set->query; hsp_set->query = hsp_set->target; hsp_set->target = query; /* Switch parameters */ HSP_Param_destroy(hsp_set->param); hsp_set->param = HSP_Param_share(hsp_param); /* Swap HSPs coordinates */ for(i = 0; i < hsp_set->hsp_list->len; i++){ hsp = hsp_set->hsp_list->pdata[i]; query_start = hsp->query_start; hsp->query_start = hsp->target_start; hsp->target_start = query_start; } return; } void HSPset_revcomp(HSPset *hsp_set){ register Sequence *rc_query = Sequence_revcomp(hsp_set->query), *rc_target = Sequence_revcomp(hsp_set->target); register gint i; register HSP *hsp; g_assert(hsp_set); g_assert(hsp_set->is_finalised); g_assert(hsp_set->ref_count == 1); /**/ Sequence_destroy(hsp_set->query); Sequence_destroy(hsp_set->target); hsp_set->query = rc_query; hsp_set->target = rc_target; for(i = 0; i < hsp_set->hsp_list->len; i++){ hsp = hsp_set->hsp_list->pdata[i]; hsp->query_start = hsp_set->query->len - HSP_query_end(hsp); hsp->target_start = hsp_set->target->len - HSP_target_end(hsp); } return; } static gint HSP_find_cobs(HSP *hsp){ register gint i, query_pos = hsp->query_start, target_pos = hsp->target_start; register Match_Score score = 0; /* Find the HSP centre offset by score */ for(i = 0; i < hsp->length; i++){ g_assert(HSP_check_positions(hsp->hsp_set, query_pos, target_pos)); score += HSP_get_score(hsp, query_pos, target_pos); if(score >= (hsp->score>>1)) break; query_pos += HSP_query_advance(hsp); target_pos += HSP_target_advance(hsp); } return i; } /**/ static void HSP_print_info(HSP *hsp){ g_print("HSP info (%p)\n" " query_start = [%d]\n" " target_start = [%d]\n" " length = [%d]\n" " score = [%d]\n" " cobs = [%d]\n", (gpointer)hsp, hsp->query_start, hsp->target_start, hsp->length, hsp->score, hsp->cobs); return; } typedef struct { HSP *hsp; /* not freed */ gint padding; gint max_advance; gint query_display_pad; gint target_display_pad; GString *top; GString *mid; GString *low; } HSP_Display; static HSP_Display *HSP_Display_create(HSP *hsp, gint padding){ register HSP_Display *hd = g_new(HSP_Display, 1); register gint approx_length; hd->hsp = hsp; hd->padding = padding; hd->max_advance = MAX(HSP_query_advance(hsp), HSP_target_advance(hsp)); hd->query_display_pad = (hd->max_advance -HSP_query_advance(hsp))>>1; hd->target_display_pad = (hd->max_advance -HSP_target_advance(hsp))>>1; approx_length = hd->max_advance * (hsp->length + 2); hd->top = g_string_sized_new(approx_length); hd->mid = g_string_sized_new(approx_length); hd->low = g_string_sized_new(approx_length); return hd; } static void HSP_Display_destroy(HSP_Display *hd){ g_assert(hd); g_string_free(hd->top, TRUE); g_string_free(hd->mid, TRUE); g_string_free(hd->low, TRUE); g_free(hd); return; } static void HSP_Display_add(HSP_Display *hd, gchar *top, gchar *mid, gchar *low){ g_assert(hd); g_assert(top); g_assert(mid); g_assert(low); g_string_append(hd->top, top); g_string_append(hd->mid, mid); g_string_append(hd->low, low); g_assert(hd->top->len == hd->mid->len); g_assert(hd->mid->len == hd->low->len); return; } static gchar HSP_Display_get_ruler_char(HSP_Display *hd, gint pos, gint advance){ register gint stop; register gint pad_length = 3; stop = hd->padding * hd->max_advance; if(pos >= stop){ if(pos < (stop+pad_length)){ return '#'; } stop = ((hd->padding+hd->hsp->length) * hd->max_advance) + pad_length; if(pos >= stop){ if(pos < (stop+pad_length)){ return '#'; } pos -= pad_length; } pos -= pad_length; } if((pos/advance) & 1) return '='; return '-'; } static void HSP_Display_print_ruler(HSP_Display *hd, gint width, gint pos, gboolean is_query){ register gint i, adv; if(is_query){ if(HSP_target_advance(hd->hsp) == 1) return; /* opposite padding */ adv = HSP_target_advance(hd->hsp); } else { /* Is target */ if(HSP_query_advance(hd->hsp) == 1) return; /* opposite padding */ adv = HSP_query_advance(hd->hsp); } g_print(" ruler:["); for(i = 0; i < width; i++) g_print("%c", HSP_Display_get_ruler_char(hd, pos+i, adv)); g_print("]\n"); return; } static void HSP_Display_print(HSP_Display *hd){ register gint pos, pause, width = 50; g_assert(hd); g_assert(hd->top->len == hd->mid->len); g_assert(hd->mid->len == hd->low->len); for(pos = 0, pause = hd->top->len-width; pos < pause; pos += width){ HSP_Display_print_ruler(hd, width, pos, TRUE); g_print(" query:[%.*s]\n [%.*s]\ntarget:[%.*s]\n", width, hd->top->str+pos, width, hd->mid->str+pos, width, hd->low->str+pos); HSP_Display_print_ruler(hd, width, pos, FALSE); g_print("\n"); } HSP_Display_print_ruler(hd, hd->top->len-pos, pos, TRUE); g_print(" query:[%.*s]\n [%.*s]\ntarget:[%.*s]\n", hd->top->len-pos, hd->top->str+pos, hd->mid->len-pos, hd->mid->str+pos, hd->low->len-pos, hd->low->str+pos); HSP_Display_print_ruler(hd, hd->top->len-pos, pos, FALSE); g_print("\n"); return; } static void HSP_Display_insert(HSP_Display *hd, gint position){ register gint query_pos, target_pos; register gboolean is_padding, query_valid = TRUE, target_valid = TRUE; register Match *match = hd->hsp->hsp_set->param->match; gchar query_str[4] = {0}, target_str[4] = {0}, equiv_str[4] = {0}; g_assert(hd); query_pos = hd->hsp->query_start + (HSP_query_advance(hd->hsp) * position); target_pos = hd->hsp->target_start + (HSP_target_advance(hd->hsp) * position); /* If outside HSP, then is_padding */ is_padding = ((position < 0) || (position >= hd->hsp->length)); /* If outside seqs, then invalid */ query_valid = ( (query_pos >= 0) &&((query_pos+HSP_query_advance(hd->hsp)) <= hd->hsp->hsp_set->query->len)); target_valid = ((target_pos >= 0) &&((target_pos+HSP_target_advance(hd->hsp)) <= hd->hsp->hsp_set->target->len)); /* Get equiv string */ if(query_valid && target_valid){ g_assert(HSP_check_positions(hd->hsp->hsp_set, query_pos, target_pos)); HSP_get_display(hd->hsp, query_pos, target_pos, equiv_str); } else { strncpy(equiv_str, "###", hd->max_advance); equiv_str[hd->max_advance] = '\0'; } /* Get query string */ if(query_valid){ Match_Strand_get_raw(match->query, hd->hsp->hsp_set->query, query_pos, query_str); if((match->query->advance == 1) && (hd->max_advance == 3)){ query_str[1] = query_str[0]; query_str[0] = query_str[2] = ' '; query_str[3] = '\0'; } } else { strncpy(query_str, "###", hd->max_advance); query_str[hd->max_advance] = '\0'; } /* Get target string */ if(target_valid){ Match_Strand_get_raw(match->target, hd->hsp->hsp_set->target, target_pos, target_str); if((match->target->advance == 1) && (hd->max_advance == 3)){ target_str[1] = target_str[0]; target_str[0] = target_str[2] = ' '; target_str[3] = '\0'; } } else { strncpy(target_str, "###", hd->max_advance); target_str[hd->max_advance] = '\0'; } /* Make lower case for padding */ if(is_padding){ g_strdown(query_str); g_strdown(target_str); } else { g_strup(query_str); g_strup(target_str); } HSP_Display_add(hd, query_str, equiv_str, target_str); return; } static void HSP_print_alignment(HSP *hsp){ register HSP_Display *hd = HSP_Display_create(hsp, 10); register gint i; for(i = 0; i < hd->padding; i++) /* Pre-padding */ HSP_Display_insert(hd, i-hd->padding); /* Use pad_length == 3 */ HSP_Display_add(hd, " < ", " < ", " < "); /* Start divider */ for(i = 0; i < hsp->length; i++) /* The HSP itself */ HSP_Display_insert(hd, i); HSP_Display_add(hd, " > ", " > ", " > "); /* End divider */ for(i = 0; i < hd->padding; i++) /* Post-padding */ HSP_Display_insert(hd, hsp->length+i); HSP_Display_print(hd); HSP_Display_destroy(hd); return; } /* * HSP display style: * * =-=-=- =-=-=-=-=-=-=-=-=- =-=-=- * nnnnnn < ACGACGCCCACGATCGAT > nnn### * ||| < |||:::||| |||||| > ||| * ### x < A R N D C Q > x ### * ===--- ===---===---===--- ===--- */ static void HSP_print_sugar(HSP *hsp){ g_print("sugar: %s %d %d %c %s %d %d %c %d\n", hsp->hsp_set->query->id, hsp->query_start, hsp->length*HSP_query_advance(hsp), Sequence_get_strand_as_char(hsp->hsp_set->query), hsp->hsp_set->target->id, hsp->target_start, hsp->length*HSP_target_advance(hsp), Sequence_get_strand_as_char(hsp->hsp_set->target), hsp->score); return; } /* Sugar output format: * sugar: <query_id> <query_start> <query_length> <query_strand> * <target_id> <target_start> <target_start> <target_strand> * <score> */ void HSP_print(HSP *hsp, gchar *name){ g_print("draw_hsp(%d, %d, %d, %d, %d, %d, \"%s\")\n", hsp->query_start, hsp->target_start, hsp->length, hsp->cobs, HSP_query_advance(hsp), HSP_target_advance(hsp), name); HSP_print_info(hsp); HSP_print_alignment(hsp); HSP_print_sugar(hsp); return; } void HSPset_print(HSPset *hsp_set){ register gint i; register gchar *name; g_print("HSPset [%p] contains [%d] hsps\n", (gpointer)hsp_set, hsp_set->hsp_list->len); g_print("Comparison of [%s] and [%s]\n", hsp_set->query->id, hsp_set->target->id); for(i = 0; i < hsp_set->hsp_list->len; i++){ name = g_strdup_printf("hsp [%d]", i+1); HSP_print(hsp_set->hsp_list->pdata[i], name); g_free(name); } return; } /**/ static void HSP_init(HSP *nh){ register gint i; register gint query_pos, target_pos; g_assert(HSP_check(nh)); /* Initial hsp score */ query_pos = nh->query_start; target_pos = nh->target_start; nh->score = 0; for(i = 0; i < nh->length; i++){ g_assert(HSP_check_positions(nh->hsp_set, query_pos, target_pos)); nh->score += HSP_get_score(nh, query_pos, target_pos); query_pos += HSP_query_advance(nh); target_pos += HSP_target_advance(nh); } if(nh->score < 0){ HSP_print(nh, "Bad HSP seed"); g_error("Initial HSP score [%d] less than zero", nh->score); } g_assert(HSP_check(nh)); return; } static void HSP_extend(HSP *nh, gboolean forbid_masked){ register Match_Score score, maxscore; register gint query_pos, target_pos; register gint extend, maxext; g_assert(HSP_check(nh)); /* extend left */ maxscore = score = nh->score; query_pos = nh->query_start-HSP_query_advance(nh); target_pos = nh->target_start-HSP_target_advance(nh); for(extend = 1, maxext = 0; ((query_pos >= 0) && (target_pos >= 0)); extend++){ g_assert(HSP_check_positions(nh->hsp_set, query_pos, target_pos)); if((forbid_masked) && (HSP_query_masked(nh, query_pos) || HSP_target_masked(nh, target_pos))) break; score += HSP_get_score(nh, query_pos, target_pos); if(maxscore <= score){ maxscore = score; maxext = extend; } else { if(score < 0) /* See note below */ break; if((maxscore-score) >= nh->hsp_set->param->dropoff) break; } query_pos -= HSP_query_advance(nh); target_pos -= HSP_target_advance(nh); } query_pos = HSP_query_end(nh); target_pos = HSP_target_end(nh); nh->query_start -= (maxext * HSP_query_advance(nh)); nh->target_start -= (maxext * HSP_target_advance(nh)); nh->length += maxext; score = maxscore; /* extend right */ for(extend = 1, maxext = 0; ( ((query_pos+HSP_query_advance(nh)) <= nh->hsp_set->query->len) && ((target_pos+HSP_target_advance(nh)) <= nh->hsp_set->target->len) ); extend++){ g_assert(HSP_check_positions(nh->hsp_set, query_pos, target_pos)); if((forbid_masked) && (HSP_query_masked(nh, query_pos) || HSP_target_masked(nh, target_pos))) break; score += HSP_get_score(nh, query_pos, target_pos); if(maxscore <= score){ maxscore = score; maxext = extend; } else { if(score < 0) /* See note below */ break; if((maxscore-score) >= nh->hsp_set->param->dropoff) break; } query_pos += HSP_query_advance(nh); target_pos += HSP_target_advance(nh); } nh->score = maxscore; nh->length += maxext; g_assert(HSP_check(nh)); return; } /* The score cannot be allowed to drop below zero in the HSP, * as this can result in overlapping HSPs in some circurmstances. */ static HSP *HSP_create(HSP *nh){ register HSP *hsp = RecycleBin_alloc(nh->hsp_set->hsp_recycle); hsp->hsp_set = nh->hsp_set; hsp->query_start = nh->query_start; hsp->target_start = nh->target_start; hsp->length = nh->length; hsp->score = nh->score; hsp->cobs = nh->cobs; /* Value can be set by HSPset_finalise(); */ return hsp; } void HSP_destroy(HSP *hsp){ register HSPset *hsp_set = hsp->hsp_set; RecycleBin_recycle(hsp_set->hsp_recycle, hsp); return; } static void HSP_trim_ends(HSP *hsp){ register gint i; register gint query_pos, target_pos; /* Trim left to first good match */ g_assert(HSP_check(hsp)); for(i = 0; i < hsp->length; i++){ if(HSP_get_score(hsp, hsp->query_start, hsp->target_start) > 0) break; hsp->query_start += HSP_query_advance(hsp); hsp->target_start += HSP_target_advance(hsp); } hsp->length -= i; /**/ g_assert(HSP_check(hsp)); query_pos = HSP_query_end(hsp) - HSP_query_advance(hsp); target_pos = HSP_target_end(hsp) - HSP_target_advance(hsp); /* Trim right to last good match */ while(hsp->length > 0){ g_assert(HSP_check_positions(hsp->hsp_set, query_pos, target_pos)); if(HSP_get_score(hsp, query_pos, target_pos) > 0) break; hsp->length--; query_pos -= HSP_query_advance(hsp); target_pos -= HSP_target_advance(hsp); } g_assert(HSP_check(hsp)); return; } /* This is to remove any unmatching ends from the HSP seed. */ static gboolean HSP_PQueue_comp_func(gpointer low, gpointer high, gpointer user_data){ register HSP *hsp_low = (HSP*)low, *hsp_high = (HSP*)high; return hsp_low->score - hsp_high->score; } static void HSP_store(HSP *nascent_hsp){ register HSPset *hsp_set = nascent_hsp->hsp_set; register PQueue *pq; register HSP *hsp = NULL; g_assert(nascent_hsp); if(nascent_hsp->score < hsp_set->param->threshold) return; if(hsp_set->param->has->filter_threshold){ /* If have filter */ /* Get cobs value */ nascent_hsp->cobs = HSP_find_cobs(nascent_hsp); pq = hsp_set->filter[HSP_query_cobs(nascent_hsp)]; if(pq){ /* Put in PQueue if better than worst */ if(PQueue_total(pq) < hsp_set->param->has->filter_threshold){ hsp = HSP_create(nascent_hsp); PQueue_push(pq, hsp); } else { g_assert(PQueue_total(pq)); hsp = PQueue_top(pq); if(hsp->score < nascent_hsp->score){ hsp = PQueue_pop(pq); HSP_destroy(hsp); hsp = HSP_create(nascent_hsp); PQueue_push(pq, hsp); } } } else { pq = PQueue_create(hsp_set->pqueue_set, HSP_PQueue_comp_func, NULL); hsp_set->filter[HSP_query_cobs(nascent_hsp)] = pq; hsp = HSP_create(nascent_hsp); PQueue_push(pq, hsp); hsp_set->is_empty = FALSE; } } else { hsp = HSP_create(nascent_hsp); g_ptr_array_add(hsp_set->hsp_list, hsp); hsp_set->is_empty = FALSE; } return; } /* FIXME: optimisation: could store HSPs as a list up until * filter_threshold, then convert to a PQueue */ void HSPset_seed_hsp(HSPset *hsp_set, guint query_start, guint target_start){ register gint diag_pos = ((target_start * hsp_set->param->match->query->advance) -(query_start * hsp_set->param->match->target->advance)); register gint query_frame = query_start % hsp_set->param->match->query->advance, target_frame = target_start % hsp_set->param->match->target->advance; register gint section_pos = (diag_pos + hsp_set->query->len) % hsp_set->query->len; HSP nascent_hsp; g_assert(!hsp_set->is_finalised); /**/ g_assert(section_pos >= 0); g_assert(section_pos < hsp_set->query->len); /* Check whether we have seen this HSP already */ if(target_start < hsp_set->horizon[0] [section_pos] [query_frame] [target_frame]) return; if(hsp_set->param->seed_repeat > 1){ if(++hsp_set->horizon[1][section_pos][query_frame][target_frame] < hsp_set->param->seed_repeat) return; hsp_set->horizon[1][section_pos][query_frame][target_frame] = 0; } /* Nascent HSP building: */ nascent_hsp.hsp_set = hsp_set; nascent_hsp.query_start = query_start; nascent_hsp.target_start = target_start; nascent_hsp.length = hsp_set->param->seedlen; nascent_hsp.cobs = 0; g_assert(HSP_check(&nascent_hsp)); HSP_trim_ends(&nascent_hsp); /* Score is irrelevant before HSP_init() */ HSP_init(&nascent_hsp); /* Try to make above threshold HSP using masking */ if(hsp_set->param->match->query->mask_func || hsp_set->param->match->target->mask_func){ HSP_extend(&nascent_hsp, TRUE); if(nascent_hsp.score < hsp_set->param->threshold){ hsp_set->horizon[0][section_pos][query_frame][target_frame] = HSP_target_end(&nascent_hsp); return; } } /* Extend the HSP again ignoring masking */ HSP_extend(&nascent_hsp, FALSE); HSP_store(&nascent_hsp); hsp_set->horizon[0][section_pos][query_frame][target_frame] = HSP_target_end(&nascent_hsp); return; } void HSPset_add_known_hsp(HSPset *hsp_set, guint query_start, guint target_start, guint length){ HSP nascent_hsp; nascent_hsp.hsp_set = hsp_set; nascent_hsp.query_start = query_start; nascent_hsp.target_start = target_start; nascent_hsp.length = length; nascent_hsp.cobs = 0; /* Score is irrelevant before HSP_init() */ HSP_init(&nascent_hsp); HSP_store(&nascent_hsp); return; } static void HSPset_seed_hsp_sorted(HSPset *hsp_set, guint query_start, guint target_start, gint ***horizon){ HSP nascent_hsp; register gint diag_pos = ((target_start * hsp_set->param->match->query->advance) -(query_start * hsp_set->param->match->target->advance)); register gint query_frame = query_start % hsp_set->param->match->query->advance, target_frame = target_start % hsp_set->param->match->target->advance; register gint section_pos = (diag_pos + hsp_set->query->len) % hsp_set->query->len; g_assert(!hsp_set->is_finalised); g_assert(!hsp_set->horizon); g_assert(section_pos >= 0); g_assert(section_pos < hsp_set->query->len); /**/ if(horizon[1][query_frame][target_frame] != section_pos){ horizon[1][query_frame][target_frame] = section_pos; horizon[0][query_frame][target_frame] = 0; horizon[2][query_frame][target_frame] = 0; } if(++horizon[2][query_frame][target_frame] < hsp_set->param->seed_repeat) return; horizon[2][query_frame][target_frame] = 0; /* Check whether we have seen this HSP already */ if(target_start < horizon[0][query_frame][target_frame]) return; /**/ /* Nascent HSP building: */ nascent_hsp.hsp_set = hsp_set; nascent_hsp.query_start = query_start; nascent_hsp.target_start = target_start; nascent_hsp.length = hsp_set->param->seedlen; nascent_hsp.cobs = 0; g_assert(HSP_check(&nascent_hsp)); HSP_trim_ends(&nascent_hsp); /* Score is irrelevant before HSP_init() */ HSP_init(&nascent_hsp); /* Try to make above threshold HSP using masking */ if(hsp_set->param->match->query->mask_func || hsp_set->param->match->target->mask_func){ HSP_extend(&nascent_hsp, TRUE); if(nascent_hsp.score < hsp_set->param->threshold){ horizon[0][query_frame][target_frame] = HSP_target_end(&nascent_hsp); return; } } /* Extend the HSP again ignoring masking */ HSP_extend(&nascent_hsp, FALSE); HSP_store(&nascent_hsp); /**/ horizon[0][query_frame][target_frame] = HSP_target_end(&nascent_hsp); return; } /* horizon[0] = diag * horizon[1] = target_end * horizon[2] = repeat_count */ /* Need to use the global to pass q,t advance to qsort compare func */ static HSPset *HSPset_seed_compare_hsp_set = NULL; static int HSPset_seed_compare(const void *a, const void *b){ register guint *seed_a = (guint*)a, *seed_b = (guint*)b; register gint diag_a, diag_b; register HSPset *hsp_set = HSPset_seed_compare_hsp_set; g_assert(hsp_set); diag_a = ((seed_a[1] * hsp_set->param->match->query->advance) - (seed_a[0] * hsp_set->param->match->target->advance)), diag_b = ((seed_b[1] * hsp_set->param->match->query->advance) - (seed_b[0] * hsp_set->param->match->target->advance)); if(diag_a == diag_b) return seed_a[0] - seed_b[0]; return diag_a - diag_b; } void HSPset_seed_all_hsps(HSPset *hsp_set, guint *seed_list, guint seed_list_len){ register gint i; register gint ***horizon; register gint qpos, tpos; if(seed_list_len > 1){ HSPset_seed_compare_hsp_set = hsp_set; qsort(seed_list, seed_list_len, sizeof(guint) << 1, HSPset_seed_compare); HSPset_seed_compare_hsp_set = NULL; } if(seed_list_len){ horizon = (gint***)Matrix3d_create(3, hsp_set->param->match->query->advance, hsp_set->param->match->target->advance, sizeof(gint)); for(i = 0; i < seed_list_len; i++){ HSPset_seed_hsp_sorted(hsp_set, seed_list[(i << 1)], seed_list[(i << 1) + 1], horizon); qpos = seed_list[(i << 1)]; tpos = seed_list[(i << 1) + 1]; } g_free(horizon); } HSPset_finalise(hsp_set); return; } /**/ HSPset *HSPset_finalise(HSPset *hsp_set){ register gint i; register HSP *hsp; register PQueue *pq; g_assert(!hsp_set->is_finalised); hsp_set->is_finalised = TRUE; if(hsp_set->param->has->filter_threshold && (!hsp_set->is_empty)){ /* Get HSPs from each PQueue */ for(i = 0; i < hsp_set->query->len; i++){ pq = hsp_set->filter[i]; if(pq){ while(PQueue_total(pq)){ hsp = PQueue_pop(pq); g_ptr_array_add(hsp_set->hsp_list, hsp); } } } } /* Set cobs for each HSP */ if(!hsp_set->param->has->filter_threshold){ for(i = 0; i < hsp_set->hsp_list->len; i++){ hsp = hsp_set->hsp_list->pdata[i]; hsp->cobs = HSP_find_cobs(hsp); } } hsp_set->is_finalised = TRUE; return hsp_set; } /**/ static int HSPset_sort_by_diag_then_query_start(const void *a, const void *b){ register HSP **hsp_a = (HSP**)a, **hsp_b = (HSP**)b; register gint diag_a = HSP_diagonal(*hsp_a), diag_b = HSP_diagonal(*hsp_b); if(diag_a == diag_b) return (*hsp_a)->query_start - (*hsp_b)->query_start; return diag_a - diag_b; } static Match_Score HSP_score_overlap(HSP *left, HSP *right){ register Match_Score score = 0; register gint query_pos, target_pos; g_assert(left->hsp_set == right->hsp_set); g_assert(HSP_diagonal(left) == HSP_diagonal(right)); query_pos = HSP_query_end(left) - HSP_query_advance(left); target_pos = HSP_target_end(left) - HSP_target_advance(left); while(query_pos >= right->query_start){ score += HSP_get_score(left, query_pos, target_pos); query_pos -= HSP_query_advance(left); target_pos -= HSP_target_advance(left); } query_pos = right->query_start; target_pos = right->target_start; while(query_pos < (HSP_query_end(left)- HSP_query_advance(right))){ score += HSP_get_score(right, query_pos, target_pos); query_pos += HSP_query_advance(right); target_pos += HSP_target_advance(right); } return score; } /* Returns score for overlapping region of HSPs on same diagonal */ void HSPset_filter_ungapped(HSPset *hsp_set){ register GPtrArray *new_hsp_list; register HSP *curr_hsp, *prev_hsp; register gboolean del_prev, del_curr; register gint i; register Match_Score score; /* Filter strongly overlapping HSPs on same diagonal * but different frames (happens with 3:3 HSPs only) */ if((hsp_set->hsp_list->len > 1) && (hsp_set->param->match->query->advance == 3) && (hsp_set->param->match->target->advance == 3)){ /* FIXME: should not sort when using all-at-once HSPset */ qsort(hsp_set->hsp_list->pdata, hsp_set->hsp_list->len, sizeof(gpointer), HSPset_sort_by_diag_then_query_start); prev_hsp = hsp_set->hsp_list->pdata[0]; del_prev = FALSE; del_curr = FALSE; new_hsp_list = g_ptr_array_new(); for(i = 1; i < hsp_set->hsp_list->len; i++){ curr_hsp = hsp_set->hsp_list->pdata[i]; del_curr = FALSE; if((HSP_diagonal(prev_hsp) == HSP_diagonal(curr_hsp)) && (HSP_query_end(prev_hsp) > curr_hsp->query_start)){ score = HSP_score_overlap(prev_hsp, curr_hsp); if((score << 1) > (curr_hsp->score + prev_hsp->score)){ /* FIXME: use codon_usage scores here instead */ if(prev_hsp->score < curr_hsp->score){ del_prev = TRUE; } else { del_curr = TRUE; } } } if(del_prev) HSP_destroy(prev_hsp); else g_ptr_array_add(new_hsp_list, prev_hsp); prev_hsp = curr_hsp; del_prev = del_curr; } if(del_prev) HSP_destroy(prev_hsp); else g_ptr_array_add(new_hsp_list, prev_hsp); g_ptr_array_free(hsp_set->hsp_list, TRUE); hsp_set->hsp_list = new_hsp_list; } return; } /**/ #define HSPset_SList_PAGE_BIT_WIDTH 10 #define HSPset_SList_PAGE_SIZE (1 << HSPset_SList_PAGE_BIT_WIDTH) RecycleBin *HSPset_SList_RecycleBin_create(void){ return RecycleBin_create("HSPset_Slist", sizeof(HSPset_SList_Node), 4096); } HSPset_SList_Node *HSPset_SList_append(RecycleBin *recycle_bin, HSPset_SList_Node *next, gint query_pos, gint target_pos){ register HSPset_SList_Node *node = RecycleBin_alloc(recycle_bin); node->next = next; node->query_pos = query_pos; node->target_pos = target_pos; return node; } #if 0 typedef struct { gint page_alloc; gint page_total; HSPset_SList_Node **diag_page_list; gint ****horizon; gint *page_used; gint page_used_total; } HSPset_SeedData; static HSPset_SeedData *HSPset_SeedData_create(HSP_Param *hsp_param, gint target_len){ register HSPset_SeedData *seed_data = g_new(HSPset_SeedData, 1); seed_data->page_total = (target_len >> HSPset_SList_PAGE_BIT_WIDTH) + 1; seed_data->page_alloc = seed_data->page_total; seed_data->diag_page_list = g_new0(HSPset_SList_Node*, seed_data->page_total); seed_data->page_used = g_new(gint, seed_data->page_total); seed_data->horizon = (gint****)Matrix4d_create( 2 + ((hsp_param->seed_repeat > 1)?1:0), HSPset_SList_PAGE_SIZE, hsp_param->match->query->advance, hsp_param->match->target->advance, sizeof(gint)); seed_data->page_used_total = 0; return seed_data; } static void HSPset_SeedData_destroy(HSPset_SeedData *seed_data){ g_free(seed_data->diag_page_list); g_free(seed_data->page_used); g_free(seed_data->horizon); g_free(seed_data); return; } static void HSPset_SeedData_set_target_len(HSPset_SeedData *seed_data, HSPset *hsp_set){ register gint new_page_total = (hsp_set->target->len >> HSPset_SList_PAGE_BIT_WIDTH) + 1; register gint i, a, b, c, d; seed_data->page_total = new_page_total; if(seed_data->page_alloc < new_page_total){ seed_data->page_alloc = seed_data->page_total; g_free(seed_data->diag_page_list); seed_data->diag_page_list = g_new(HSPset_SList_Node*, seed_data->page_total); g_free(seed_data->page_used); seed_data->page_used = g_new(gint, seed_data->page_total); } /* Clear diag_page_list */ for(i = 0; i < seed_data->page_total; i++) seed_data->diag_page_list[i] = 0; /* Clear horizon */ for(a = 2 + ((hsp_set->param->seed_repeat > 1)?1:0); a >= 0; a--) for(b = HSPset_SList_PAGE_SIZE; b >= 0; b--) for(c = hsp_set->param->match->query->advance; c >= 0; c--) for(d = hsp_set->param->match->target->advance; d >= 0; d--) seed_data->horizon[a][b][c][d] = 0; seed_data->page_used_total = 0; return; } #endif /* 0 */ void HSPset_seed_all_qy_sorted(HSPset *hsp_set, HSPset_SList_Node *seed_list){ register gint page_total = (hsp_set->target->len >> HSPset_SList_PAGE_BIT_WIDTH) + 1; register HSPset_SList_Node **diag_page_list = g_new0(HSPset_SList_Node*, page_total); register gint *page_used = g_new(gint, page_total); register gint ****horizon = (gint****)Matrix4d_create( 2 + ((hsp_set->param->seed_repeat > 1)?1:0), HSPset_SList_PAGE_SIZE, hsp_set->param->match->query->advance, hsp_set->param->match->target->advance, sizeof(gint)); /* register HSPset_SeedData *seed_data = HSPset_SeedData_create(hsp_set->param, hsp_set->target->len); */ register gint i, page, diag_pos, query_frame, target_frame, section_pos, page_pos; register HSPset_SList_Node *seed; register gint page_used_total = 0; HSP nascent_hsp; /* g_message("[%s] with [%d]", __FUNCTION__, hsp_set->target->len); */ /* HSPset_SeedData_set_target_len(seed_data, hsp_set); */ /* Bin on diagonal into pages */ while(seed_list){ seed = seed_list; seed_list = seed_list->next; /**/ diag_pos = (seed->target_pos * hsp_set->param->match->query->advance) - (seed->query_pos * hsp_set->param->match->target->advance); section_pos = ((diag_pos + hsp_set->target->len) % hsp_set->target->len); page = (section_pos >> HSPset_SList_PAGE_BIT_WIDTH); g_assert(section_pos >= 0); g_assert(section_pos < hsp_set->target->len); g_assert(page >= 0); g_assert(page < page_total); /**/ if(!diag_page_list[page]) page_used[page_used_total++] = page; seed->next = diag_page_list[page]; diag_page_list[page] = seed; } /* Seed each page using page horizon */ for(i = 0; i < page_used_total; i++){ page = page_used[i]; for(seed = diag_page_list[page]; seed; seed = seed->next){ g_assert((!seed->next) || (seed->query_pos <= seed->next->query_pos)); diag_pos = (seed->target_pos * hsp_set->param->match->query->advance) - (seed->query_pos * hsp_set->param->match->target->advance); query_frame = seed->query_pos % hsp_set->param->match->query->advance; target_frame = seed->target_pos % hsp_set->param->match->target->advance; section_pos = ((diag_pos + hsp_set->target->len) % hsp_set->target->len); page_pos = section_pos - (page << HSPset_SList_PAGE_BIT_WIDTH); g_assert(page_pos >= 0); g_assert(page_pos < HSPset_SList_PAGE_SIZE); /* Clear if page has changed */ if(horizon[1][page_pos][query_frame][target_frame] != page){ horizon[0][page_pos][query_frame][target_frame] = 0; horizon[1][page_pos][query_frame][target_frame] = page; if(hsp_set->param->seed_repeat > 1) horizon[2][page_pos][query_frame][target_frame] = 0; } if(seed->query_pos < horizon[0][page_pos][query_frame][target_frame]) continue; if(hsp_set->param->seed_repeat > 1){ if(++horizon[2][page_pos][query_frame][target_frame] < hsp_set->param->seed_repeat){ continue; } horizon[2][page_pos][query_frame][target_frame] = 0; } /* Nascent HSP building: */ nascent_hsp.hsp_set = hsp_set; nascent_hsp.query_start = seed->query_pos; nascent_hsp.target_start = seed->target_pos; nascent_hsp.length = hsp_set->param->seedlen; nascent_hsp.cobs = 0; g_assert(HSP_check(&nascent_hsp)); HSP_trim_ends(&nascent_hsp); /* Score is irrelevant before HSP_init() */ HSP_init(&nascent_hsp); /* Try to make above threshold HSP using masking */ if(hsp_set->param->match->query->mask_func || hsp_set->param->match->target->mask_func){ HSP_extend(&nascent_hsp, TRUE); if(nascent_hsp.score < hsp_set->param->threshold){ horizon[0][page_pos][query_frame][target_frame] = HSP_query_end(&nascent_hsp); continue; } } /* Extend the HSP again ignoring masking */ HSP_extend(&nascent_hsp, FALSE); HSP_store(&nascent_hsp); /**/ horizon[0][page_pos][query_frame][target_frame] = HSP_query_end(&nascent_hsp); } } g_free(diag_page_list); g_free(page_used); g_free(horizon); HSPset_finalise(hsp_set); /* HSPset_SeedData_destroy(seed_data); */ return; } /* horizon[horizon][mailbox][seed_repeat] * [page_size][qadv][tadv] */ /**/
hotdogee/exonerate-gff3
src/comparison/hspset.c
C
gpl-3.0
51,355
/* * Copyright (c) 2000-2005, 2008-2011 Apple Inc. All rights reserved. * * @APPLE_LICENSE_HEADER_START@ * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this * file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_LICENSE_HEADER_END@ */ /* * Modification History * * June 1, 2001 Allan Nathanson <ajn@apple.com> * - public API conversion * * March 31, 2000 Allan Nathanson <ajn@apple.com> * - initial revision */ #include <mach/mach.h> #include <mach/mach_error.h> #include <SystemConfiguration/SystemConfiguration.h> #include <SystemConfiguration/SCPrivate.h> #include "SCDynamicStoreInternal.h" #include "config.h" /* MiG generated file */ Boolean SCDynamicStoreNotifyCancel(SCDynamicStoreRef store) { SCDynamicStorePrivateRef storePrivate = (SCDynamicStorePrivateRef)store; kern_return_t status; int sc_status; if (store == NULL) { /* sorry, you must provide a session */ _SCErrorSet(kSCStatusNoStoreSession); return FALSE; } switch (storePrivate->notifyStatus) { case NotifierNotRegistered : /* if no notifications have been registered */ return TRUE; case Using_NotifierInformViaRunLoop : CFRunLoopSourceInvalidate(storePrivate->rls); storePrivate->rls = NULL; return TRUE; case Using_NotifierInformViaDispatch : (void) SCDynamicStoreSetDispatchQueue(store, NULL); return TRUE; default : break; } if (storePrivate->server == MACH_PORT_NULL) { /* sorry, you must have an open session to play */ sc_status = kSCStatusNoStoreServer; goto done; } status = notifycancel(storePrivate->server, (int *)&sc_status); if (__SCDynamicStoreCheckRetryAndHandleError(store, status, &sc_status, "SCDynamicStoreNotifyCancel notifycancel()")) { sc_status = kSCStatusOK; } done : /* set notifier inactive */ storePrivate->notifyStatus = NotifierNotRegistered; if (sc_status != kSCStatusOK) { _SCErrorSet(sc_status); return FALSE; } return TRUE; }
LubosD/darling
src/configd/SystemConfiguration.fproj/SCDNotifierCancel.c
C
gpl-3.0
2,715
/* Moonshine - a Lua-based chat client * * Copyright (C) 2010 Dylan William Hardison * * This file is part of Moonshine. * * Moonshine 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. * * Moonshine 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 Moonshine. If not, see <http://www.gnu.org/licenses/>. */ #include <moonshine/async-queue-source.h> #include <glib.h> #include <unistd.h> static guint tag = 0; void my_free_func(gpointer data) { g_print("free: %s\n", ((GString *)data)->str); g_string_free((GString *)data, TRUE); } void my_pool_func(gpointer data, gpointer userdata) { static int count = 1; GAsyncQueue *queue = userdata; GString *name = data; GString *msg = g_string_new(""); g_string_printf(msg, "count: %d", count++); g_print("- %s\n", name->str); g_string_free(name, TRUE); g_print("queue: %s\n", msg->str); g_async_queue_push(queue, msg); } gboolean my_queue_func(gpointer data, gpointer userdata) { GString *msg = data; GString *prefix = userdata; g_print("%s%s\n", prefix->str, msg->str); g_string_free(msg, TRUE); return TRUE; } gboolean my_start_func(gpointer userdata) { GAsyncQueue *queue = g_async_queue_new_full(my_free_func); GThreadPool *pool = g_thread_pool_new(my_pool_func, g_async_queue_ref(queue), 1, TRUE, NULL); tag = ms_async_queue_add_watch(queue, my_queue_func, g_string_new("msg: "), my_free_func); g_async_queue_unref(queue); g_thread_pool_push(pool, g_string_new("foo"), NULL); g_thread_pool_push(pool, g_string_new("bar"), NULL); g_thread_pool_push(pool, g_string_new("baz"), NULL); return FALSE; } gboolean my_beep_func(gpointer userdata) { g_print("beep!\n"); return FALSE; } gboolean my_stop_func(gpointer userdata) { g_print("stopping...\n"); gboolean rv = g_source_remove(tag); g_print("g_source_remove(%d): %s\n", tag, rv ? "TRUE" : "FALSE"); return FALSE; } int main(int argc, char *argv[]) { GMainLoop *loop = g_main_loop_new(NULL, FALSE); g_thread_init(NULL); g_timeout_add(10, my_start_func, NULL); //g_timeout_add(1000, my_beep_func, NULL); //g_timeout_add(5000, my_beep_func, NULL); g_timeout_add(5000, my_stop_func, NULL); g_main_loop_run(loop); return 0; }
bdonlan/moonshine
src/async-queue-test.c
C
gpl-3.0
2,762
/* * linux/kernel/math/div.c * * (C) 1991 Linus Torvalds */ /* * temporary real division routine. */ #include <linux/math_emu.h> static void shift_left(int * c) { __asm__ __volatile__("movl (%0),%%eax ; addl %%eax,(%0)\n\t" "movl 4(%0),%%eax ; adcl %%eax,4(%0)\n\t" "movl 8(%0),%%eax ; adcl %%eax,8(%0)\n\t" "movl 12(%0),%%eax ; adcl %%eax,12(%0)" ::"r" ((long) c):"ax"); } static void shift_right(int * c) { __asm__("shrl $1,12(%0) ; rcrl $1,8(%0) ; rcrl $1,4(%0) ; rcrl $1,(%0)" ::"r" ((long) c)); } static int try_sub(int * a, int * b) { char ok; __asm__ __volatile__("movl (%1),%%eax ; subl %%eax,(%2)\n\t" "movl 4(%1),%%eax ; sbbl %%eax,4(%2)\n\t" "movl 8(%1),%%eax ; sbbl %%eax,8(%2)\n\t" "movl 12(%1),%%eax ; sbbl %%eax,12(%2)\n\t" "setae %%al":"=a" (ok):"c" ((long) a),"d" ((long) b)); return ok; } static void div64(int * a, int * b, int * c) { int tmp[4]; int i; unsigned int mask = 0; c += 4; for (i = 0 ; i<64 ; i++) { if (!(mask >>= 1)) { c--; mask = 0x80000000; } tmp[0] = a[0]; tmp[1] = a[1]; tmp[2] = a[2]; tmp[3] = a[3]; if (try_sub(b,tmp)) { *c |= mask; a[0] = tmp[0]; a[1] = tmp[1]; a[2] = tmp[2]; a[3] = tmp[3]; } shift_right(b); } } void fdiv(const temp_real * src1, const temp_real * src2, temp_real * result) { int i,sign; int a[4],b[4],tmp[4] = {0,0,0,0}; sign = (src1->exponent ^ src2->exponent) & 0x8000; if (!(src2->a || src2->b)) { set_ZE(); return; } i = (src1->exponent & 0x7fff) - (src2->exponent & 0x7fff) + 16383; if (i<0) { set_UE(); result->exponent = sign; result->a = result->b = 0; return; } a[0] = a[1] = 0; a[2] = src1->a; a[3] = src1->b; b[0] = b[1] = 0; b[2] = src2->a; b[3] = src2->b; while (b[3] >= 0) { i++; shift_left(b); } div64(a,b,tmp); if (tmp[0] || tmp[1] || tmp[2] || tmp[3]) { while (i && tmp[3] >= 0) { i--; shift_left(tmp); } if (tmp[3] >= 0) set_DE(); } else i = 0; if (i>0x7fff) { set_OE(); return; } if (tmp[0] || tmp[1]) set_PE(); result->exponent = i | sign; result->a = tmp[2]; result->b = tmp[3]; }
honyyang/Linux-0.12
linux-0.12/kernel/math/div.c
C
gpl-3.0
2,099
/* * Copyright (C) 2009-2011 Andy Spencer <andy753421@gmail.com> * * 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 3 of the License, or * (at your option) any later version. * * This program 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 this program. If not, see <http://www.gnu.org/licenses/>. */ #include <math.h> #include <glib.h> #include <gdk/gdkgl.h> #include <gdk/gdkkeysyms.h> #include <objects/grits-volume.h> #include <objects/grits-callback.h> #include <objects/marching.h> #include <GL/gl.h> #include <rsl.h> #include <tester.h> /****************** * iso ball setup * ******************/ static double dist = 0.75; static gdouble distp(VolPoint *a, gdouble bx, gdouble by, gdouble bz) { return 1/((a->c.x-bx)*(a->c.x-bx) + (a->c.y-by)*(a->c.y-by) + (a->c.z-bz)*(a->c.z-bz)) * 0.10; //return 1-MIN(1,sqrt((a->c.x-bx)*(a->c.x-bx) + // (a->c.y-by)*(a->c.y-by) + // (a->c.z-bz)*(a->c.z-bz))); } static VolGrid *load_balls(float dist, int xs, int ys, int zs) { VolGrid *grid = vol_grid_new(xs, ys, zs); for (int x = 0; x < xs; x++) for (int y = 0; y < ys; y++) for (int z = 0; z < zs; z++) { VolPoint *point = vol_grid_get(grid, x, y, z); point->c.x = ((double)x/(xs-1)*2-1); point->c.y = ((double)y/(ys-1)*2-1); point->c.z = ((double)z/(zs-1)*2-1); point->value = distp(point, -dist, 0, 0) + distp(point, dist, 0, 0); point->value *= 100; } return grid; } /*************** * radar setup * ***************/ /* Load the radar into a Grits Volume */ static void _cart_to_sphere(VolCoord *out, VolCoord *in) { gdouble angle = in->x; gdouble dist = in->y; gdouble tilt = in->z; gdouble lx = sin(angle); gdouble ly = cos(angle); gdouble lz = sin(tilt); out->x = (ly*dist)/20000; out->y = (lz*dist)/10000-0.5; out->z = (lx*dist)/20000-1.5; } static VolGrid *load_radar(gchar *file, gchar *site) { /* Load radar file */ RSL_read_these_sweeps("all", NULL); Radar *rad = RSL_wsr88d_to_radar(file, site); Volume *vol = RSL_get_volume(rad, DZ_INDEX); RSL_sort_rays_in_volume(vol); /* Count dimensions */ Sweep *sweep = vol->sweep[0]; Ray *ray = sweep->ray[0]; gint nsweeps = vol->h.nsweeps; gint nrays = sweep->h.nrays/(1/sweep->h.beam_width)+1; gint nbins = ray->h.nbins /(1000/ray->h.gate_size); nbins = MIN(nbins, 100); /* Convert to VolGrid */ VolGrid *grid = vol_grid_new(nrays, nbins, nsweeps); gint rs, bs, val; gint si=0, ri=0, bi=0; for (si = 0; si < nsweeps; si++) { sweep = vol->sweep[si]; rs = 1.0/sweep->h.beam_width; for (ri = 0; ri < nrays; ri++) { /* TODO: missing rays, pick ri based on azimuth */ ray = sweep->ray[(ri*rs) % sweep->h.nrays]; bs = 1000/ray->h.gate_size; for (bi = 0; bi < nbins; bi++) { if (bi*bs >= ray->h.nbins) break; val = ray->h.f(ray->range[bi*bs]); if (val == BADVAL || val == RFVAL || val == APFLAG || val == NOECHO || val == NOTFOUND_H || val == NOTFOUND_V || val > 80) val = 0; VolPoint *point = vol_grid_get(grid, ri, bi, si); point->value = val; point->c.x = deg2rad(ray->h.azimuth); point->c.y = bi*bs*ray->h.gate_size + ray->h.range_bin1; point->c.z = deg2rad(ray->h.elev); } } } /* Convert to spherical coords */ for (si = 0; si < nsweeps; si++) for (ri = 0; ri < nrays; ri++) for (bi = 0; bi < nbins; bi++) { VolPoint *point = vol_grid_get(grid, ri, bi, si); if (point->c.y == 0) point->value = nan(""); else _cart_to_sphere(&point->c, &point->c); } return grid; } /********** * Common * **********/ static gboolean key_press(GritsTester *tester, GdkEventKey *event, GritsVolume *volume) { if (event->keyval == GDK_KEY_v) grits_volume_set_level(volume, volume->level-0.5); else if (event->keyval == GDK_KEY_V) grits_volume_set_level(volume, volume->level+0.5); else if (event->keyval == GDK_KEY_d) dist += 0.5; else if (event->keyval == GDK_KEY_D) dist -= 0.5; return FALSE; } /******** * Main * ********/ int main(int argc, char **argv) { gtk_init(&argc, &argv); GtkWidget *window = gtk_window_new(GTK_WINDOW_TOPLEVEL); GritsTester *tester = grits_tester_new(); gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(tester)); gtk_widget_show_all(window); /* Grits Volume */ VolGrid *balls_grid = load_balls(dist, 50, 50, 50); GritsVolume *balls = grits_volume_new(balls_grid); balls->proj = GRITS_VOLUME_CARTESIAN; balls->disp = GRITS_VOLUME_SURFACE; balls->color[0] = (0.8)*0xff; balls->color[1] = (0.6)*0xff; balls->color[2] = (0.2)*0xff; balls->color[3] = (1.0)*0xff; grits_volume_set_level(balls, 50); grits_tester_add(tester, GRITS_OBJECT(balls)); g_signal_connect(tester, "key-press-event", G_CALLBACK(key_press), balls); /* Grits Volume */ //char *file = "/home/andy/.cache/grits/nexrad/level2/KGWX/KGWX_20101130_0459.raw"; //char *file = "/home/andy/.cache/grits/nexrad/level2/KTLX/KTLX_19990503_2351.raw"; //VolGrid *radar_grid = load_radar(file, "KTLX"); //GritsVolume *radar = grits_volume_new(radar_grid); //radar->proj = GRITS_VOLUME_SPHERICAL; //radar->disp = GRITS_VOLUME_SURFACE; //radar->color[0] = (0.8)*0xff; //radar->color[1] = (0.6)*0xff; //radar->color[2] = (0.2)*0xff; //radar->color[3] = (1.0)*0xff; //grits_volume_set_level(radar, 50); //grits_tester_add(tester, GRITS_OBJECT(radar)); //g_signal_connect(tester, "key-press-event", G_CALLBACK(key_press), radar); /* Go */ gtk_main(); return 0; }
GNOME/grits
examples/volume/volume.c
C
gpl-3.0
5,906
/* * Copyright (C) 2008-2009 Martin Willi * Hochschule fuer Technik Rapperswil * * 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. See <http://www.fsf.org/copyleft/gpl.txt>. * * This program 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. */ #include "eap_aka_3gpp2_card.h" #include <daemon.h> typedef struct private_eap_aka_3gpp2_card_t private_eap_aka_3gpp2_card_t; /** * Private data of an eap_aka_3gpp2_card_t object. */ struct private_eap_aka_3gpp2_card_t { /** * Public eap_aka_3gpp2_card_t interface. */ eap_aka_3gpp2_card_t public; /** * AKA functions */ eap_aka_3gpp2_functions_t *f; /** * do sequence number checking? */ bool seq_check; /** * SQN stored in this pseudo-USIM */ char sqn[AKA_SQN_LEN]; }; /** * Functions from eap_aka_3gpp2_provider.c */ bool eap_aka_3gpp2_get_k(identification_t *id, char k[AKA_K_LEN]); void eap_aka_3gpp2_get_sqn(char sqn[AKA_SQN_LEN], int offset); METHOD(simaka_card_t, get_quintuplet, status_t, private_eap_aka_3gpp2_card_t *this, identification_t *id, char rand[AKA_RAND_LEN], char autn[AKA_AUTN_LEN], char ck[AKA_CK_LEN], char ik[AKA_IK_LEN], char res[AKA_RES_MAX], int *res_len) { char *amf, *mac; char k[AKA_K_LEN], ak[AKA_AK_LEN], sqn[AKA_SQN_LEN], xmac[AKA_MAC_LEN]; if (!eap_aka_3gpp2_get_k(id, k)) { DBG1(DBG_IKE, "no EAP key found for %Y to authenticate with AKA", id); return FAILED; } /* AUTN = SQN xor AK | AMF | MAC */ DBG3(DBG_IKE, "received autn %b", autn, AKA_AUTN_LEN); DBG3(DBG_IKE, "using K %b", k, AKA_K_LEN); DBG3(DBG_IKE, "using rand %b", rand, AKA_RAND_LEN); memcpy(sqn, autn, AKA_SQN_LEN); amf = autn + AKA_SQN_LEN; mac = autn + AKA_SQN_LEN + AKA_AMF_LEN; /* XOR anonymity key AK into SQN to decrypt it */ if (!this->f->f5(this->f, k, rand, ak)) { return FAILED; } DBG3(DBG_IKE, "using ak %b", ak, AKA_AK_LEN); memxor(sqn, ak, AKA_SQN_LEN); DBG3(DBG_IKE, "using sqn %b", sqn, AKA_SQN_LEN); /* calculate expected MAC and compare against received one */ if (!this->f->f1(this->f, k, rand, sqn, amf, xmac)) { return FAILED; } if (!memeq_const(mac, xmac, AKA_MAC_LEN)) { DBG1(DBG_IKE, "received MAC does not match XMAC"); DBG3(DBG_IKE, "MAC %b\nXMAC %b", mac, AKA_MAC_LEN, xmac, AKA_MAC_LEN); return FAILED; } if (this->seq_check && memcmp(this->sqn, sqn, AKA_SQN_LEN) >= 0) { DBG3(DBG_IKE, "received SQN %b\ncurrent SQN %b", sqn, AKA_SQN_LEN, this->sqn, AKA_SQN_LEN); return INVALID_STATE; } /* update stored SQN to the received one */ memcpy(this->sqn, sqn, AKA_SQN_LEN); /* CK/IK, calculate RES */ if (!this->f->f3(this->f, k, rand, ck) || !this->f->f4(this->f, k, rand, ik) || !this->f->f2(this->f, k, rand, res)) { return FAILED; } *res_len = AKA_RES_MAX; return SUCCESS; } METHOD(simaka_card_t, resync, bool, private_eap_aka_3gpp2_card_t *this, identification_t *id, char rand[AKA_RAND_LEN], char auts[AKA_AUTS_LEN]) { char amf[AKA_AMF_LEN], k[AKA_K_LEN], aks[AKA_AK_LEN], macs[AKA_MAC_LEN]; if (!eap_aka_3gpp2_get_k(id, k)) { DBG1(DBG_IKE, "no EAP key found for %Y to resync AKA", id); return FALSE; } /* AMF is set to zero in resync */ memset(amf, 0, AKA_AMF_LEN); if (!this->f->f5star(this->f, k, rand, aks) || !this->f->f1star(this->f, k, rand, this->sqn, amf, macs)) { return FALSE; } /* AUTS = SQN xor AKS | MACS */ memcpy(auts, this->sqn, AKA_SQN_LEN); memxor(auts, aks, AKA_AK_LEN); memcpy(auts + AKA_AK_LEN, macs, AKA_MAC_LEN); return TRUE; } METHOD(eap_aka_3gpp2_card_t, destroy, void, private_eap_aka_3gpp2_card_t *this) { free(this); } /** * See header */ eap_aka_3gpp2_card_t *eap_aka_3gpp2_card_create(eap_aka_3gpp2_functions_t *f) { private_eap_aka_3gpp2_card_t *this; INIT(this, .public = { .card = { .get_triplet = (void*)return_false, .get_quintuplet = _get_quintuplet, .resync = _resync, .get_pseudonym = (void*)return_null, .set_pseudonym = (void*)nop, .get_reauth = (void*)return_null, .set_reauth = (void*)nop, }, .destroy = _destroy, }, .f = f, .seq_check = lib->settings->get_bool(lib->settings, "%s.plugins.eap-aka-3gpp2.seq_check", #ifdef SEQ_CHECK /* handle legacy compile time configuration as default */ TRUE, #else /* !SEQ_CHECK */ FALSE, #endif /* SEQ_CHECK */ lib->ns), ); eap_aka_3gpp2_get_sqn(this->sqn, 0); return &this->public; }
ccwf2006/one-key-ikev2-vpn
strongswan-5.5.1/src/libcharon/plugins/eap_aka_3gpp2/eap_aka_3gpp2_card.c
C
gpl-3.0
4,765
/* Creative Machines Lab Aracna Firmware aracna.c - Main Program File Copyright (c) Creative Machines Lab, Cornell University, 2012 - http://www.creativemachines.org Authored by Jeremy Blum - http://www.jeremyblum.com LICENSE: GPLv3 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 3 of the License, or (at your option) any later version. This program 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 this program. If not, see <http://www.gnu.org/licenses/>. */ /** FIRMWARE REVISION */ #define FIRMWARE_VERSION 0x01 /** HARDWARE CONFIGURATION */ #define NUM_MOTORS 8 #ifndef F_CPU #define F_CPU 16000000UL #endif /** INCLUDE AVR HEADERS */ #include <avr/io.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <util/delay.h> /** INCLUDE PROGRAM HEADERS */ #include "aracna.h" #include "macros.h" #include "ax12.h" #include "uart.h" // UART Configuration and Buffers // putchar and getchar are in uart.c //FILE uart_str = FDEV_SETUP_STREAM(uart_putchar, uart_getchar, _FDEV_SETUP_RW); #define SERIAL_STRING_LENGTH 60 //Input String Length char input[SERIAL_STRING_LENGTH]; //complete input string uint16_t vals[NUM_MOTORS] = {0}; //For holding the values that come over serial for each of our servos char cmd; //the command character // making these volatile keeps the compiler from optimizing loops of available() volatile int ax_rx_Pointer; volatile int ax_tx_Pointer; volatile int ax_rx_int_Pointer; /** Main program entry point. This routine contains the overall program flow */ int main(void) { initialize(); //Configures Ports, sets default values, etc. //Loop Forever for (;;) { //we add data starting with an '.' to the buffer until we get the newline character. fgets(input, sizeof(input), stdin); //Get the actual input (reads up to and including newline character) cmd = input[1]; //command char is always the first char of the input data after the '.' //Command = 'q' - Query for the current status if (cmd == 'q') { memset(input, 0, sizeof(input)); //Clear previous input fprintf(stdout, ".q%d,%d\n", FIRMWARE_VERSION, NUM_MOTORS); //ACK w/ Firmware Version, # of Motors } //Command = 'l' - Command to Control Debug LED else if (cmd == 'l') { if (input[2] == '1') DEBUG_LED_ON(); //Turn LED On else if (input[2] == '0') DEBUG_LED_OFF(); //Turn LED Off memset(input, 0, sizeof(input)); //Clear previous input fprintf(stdout, ".l%d\n", DEBUG_LED_STATE()); //ACK } //Command = 'v' - Sets all motor speeds //Comma separated entries telling all motors to set certain speeds //Assumes motor IDs are 0 <-> NUM_MOTORS-1 else if (cmd == 'v') { parse_serial(); //Read the input string to an array of values memset(input, 0, sizeof(input)); //Clear previous input //send those speed commands for (int i = 0; i<NUM_MOTORS; i++) { ax12SetRegister2(i, AX_GOAL_SPEED_L, vals[i]); } _delay_ms(25); //Only after we have commanded all the speeds, can we check the status fprintf(stdout, ".v"); //ACK Character //Send ACK Info for (int i = 0; i<NUM_MOTORS; i++) { fprintf(stdout, "%d", ax12GetRegister(i, AX_GOAL_SPEED_L, 2)); //Return velocity setting if (i<NUM_MOTORS-1) fprintf(stdout, ","); //Print delimiter } fprintf(stdout, "\n"); //ACK Newline } //Command = 'c' - Command all the motors to a new position //Comma separated entries telling all motors to move to positions from 0-1023 //Assumes motor IDs are 0 <-> NUM_MOTORS-1 else if (cmd == 'c') { parse_serial(); //Read the input string to an array of positions memset(input, 0, sizeof(input)); //Clear previous input //send those position commands for (int i = 0; i<NUM_MOTORS; i++) { ax12SetRegister2(i, AX_GOAL_POSITION_L, vals[i]); } //Only after we have commanded all the positions, can we check the status fprintf(stdout, ".c"); //ACK Character //Send ACK Info for (int i = 0; i<NUM_MOTORS; i++) { while(ax12GetRegister(i,AX_MOVING,1)); //Wait for this motor to finish moving fprintf(stdout, "%d", ax12GetRegister(i, AX_PRESENT_POSITION_L, 2)); //Return the present position if (i<NUM_MOTORS-1) fprintf(stdout, ","); //Print delimiter } fprintf(stdout, "\n"); //ACK Newline } } } /** initialize() Sets up the UARTS, configures pin directions, says hello, then blinks at you. */ void initialize(void) { //init the UART0 to the Computer uart_init(); stdout = &uart_output; stdin = &uart_input; //Initialize the AX12 UART1 ax12Init(1000000); //Initialize Pin Directions and States for I/O DDRB |= (DEBUG_LED_NUM); DEBUG_LED_OFF(); //We're live. Say Hello fprintf(stdout,".h\n"); //Blink The Board LED and all Dynamixel LEDs to show We're good to go for (int i = 0; i<NUM_MOTORS; i++) ax12SetRegister(i, AX_LED, 0); DEBUG_LED_OFF(); _delay_ms(500); for (int i = 0; i<NUM_MOTORS; i++) ax12SetRegister(i, AX_LED, 1); DEBUG_LED_ON(); _delay_ms(500); for (int i = 0; i<NUM_MOTORS; i++) ax12SetRegister(i, AX_LED, 0); DEBUG_LED_OFF(); } /** parse_serial() Assumes the input buffer has been populated with data of this form: ".c<val0>,<val1>,<val2>,...<val7>\n" as a char array This function reads this buffer, and populates the "vals" array with the integer representations of 10-bit values for each motor command */ void parse_serial(void) { for (uint8_t i = 0; i < NUM_MOTORS; i++) vals[i] = 0; //Skip leading '.' and command char uint8_t i = 2; uint8_t motor_num = 0; uint8_t mtr_tmp[4] = {10, 10, 10, 10}; uint8_t mtr_tmp_pos = 0; while (motor_num < NUM_MOTORS) { //look for the commas if (input[i] == ',' || input[i] == '\n') { if (mtr_tmp[3] < 10) vals[motor_num] = mtr_tmp[0]*1000 + mtr_tmp[1]*100 + mtr_tmp[2]*10 + mtr_tmp[3]; else if (mtr_tmp[2] < 10) vals[motor_num] = mtr_tmp[0]*100 + mtr_tmp[1]*10 + mtr_tmp[2]; else if (mtr_tmp[1] < 10) vals[motor_num] = mtr_tmp[0]*10 + mtr_tmp[1]; else vals[motor_num] = mtr_tmp[0]; motor_num++; for (uint8_t j = 0; j<4; j++) mtr_tmp[j] = 10; mtr_tmp_pos = 0; } else { mtr_tmp[mtr_tmp_pos] = input[i] - '0'; mtr_tmp_pos++; } i++; } }
booi/aracna
aracna-embedded-code/aracna/aracna.c
C
gpl-3.0
6,751
/* * The copyright in this software is being made available under the 2-clauses * BSD License, included below. This software may be subject to other third * party and contributor rights, including patent rights, and no such rights * are granted under this license. * * Copyright (c) 2005, Herve Drolon, FreeImage Team * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "opj_includes.h" opj_image_t* opj_image_create0(void) { opj_image_t *image = (opj_image_t*)opj_calloc(1, sizeof(opj_image_t)); return image; } opj_image_t* OPJ_CALLCONV opj_image_create(int numcmpts, opj_image_cmptparm_t *cmptparms, OPJ_COLOR_SPACE clrspc) { int compno; opj_image_t *image = NULL; image = (opj_image_t*) opj_calloc(1, sizeof(opj_image_t)); if (image) { image->color_space = clrspc; image->numcomps = numcmpts; /* allocate memory for the per-component information */ image->comps = (opj_image_comp_t*)opj_malloc(image->numcomps * sizeof( opj_image_comp_t)); if (!image->comps) { fprintf(stderr, "Unable to allocate memory for image.\n"); opj_image_destroy(image); return NULL; } /* create the individual image components */ for (compno = 0; compno < numcmpts; compno++) { opj_image_comp_t *comp = &image->comps[compno]; comp->dx = cmptparms[compno].dx; comp->dy = cmptparms[compno].dy; comp->w = cmptparms[compno].w; comp->h = cmptparms[compno].h; comp->x0 = cmptparms[compno].x0; comp->y0 = cmptparms[compno].y0; comp->prec = cmptparms[compno].prec; comp->bpp = cmptparms[compno].bpp; comp->sgnd = cmptparms[compno].sgnd; comp->data = (int*) opj_calloc(comp->w * comp->h, sizeof(int)); if (!comp->data) { fprintf(stderr, "Unable to allocate memory for image.\n"); opj_image_destroy(image); return NULL; } } } return image; } void OPJ_CALLCONV opj_image_destroy(opj_image_t *image) { int i; if (image) { if (image->comps) { /* image components */ for (i = 0; i < image->numcomps; i++) { opj_image_comp_t *image_comp = &image->comps[i]; if (image_comp->data) { opj_free(image_comp->data); } } opj_free(image->comps); } opj_free(image); } }
AlienCowEatCake/ImageViewer
src/ThirdParty/OpenJPEG/openjpeg-2.4.0/src/lib/openmj2/image.c
C
gpl-3.0
3,859
/* FreeRTOS V7.3.0 - Copyright (C) 2012 Real Time Engineers Ltd. FEATURES AND PORTS ARE ADDED TO FREERTOS ALL THE TIME. PLEASE VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION. *************************************************************************** * * * FreeRTOS tutorial books are available in pdf and paperback. * * Complete, revised, and edited pdf reference manuals are also * * available. * * * * Purchasing FreeRTOS documentation will not only help you, by * * ensuring you get running as quickly as possible and with an * * in-depth knowledge of how to use FreeRTOS, it will also help * * the FreeRTOS project to continue with its mission of providing * * professional grade, cross platform, de facto standard solutions * * for microcontrollers - completely free of charge! * * * * >>> See http://www.FreeRTOS.org/Documentation for details. <<< * * * * Thank you for using FreeRTOS, and thank you for your support! * * * *************************************************************************** This file is part of the FreeRTOS distribution. FreeRTOS 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 AND MODIFIED BY the FreeRTOS exception. >>>NOTE<<< The modification to the GPL is included to allow you to distribute a combined work that includes FreeRTOS without being obliged to provide the source code for proprietary components outside of the FreeRTOS kernel. FreeRTOS 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 and the FreeRTOS license exception along with FreeRTOS; if not it can be viewed here: http://www.freertos.org/a00114.html and also obtained by writing to Richard Barry, contact details for whom are available on the FreeRTOS WEB site. 1 tab == 4 spaces! *************************************************************************** * * * Having a problem? Start by reading the FAQ "My application does * * not run, what could be wrong?" * * * * http://www.FreeRTOS.org/FAQHelp.html * * * *************************************************************************** http://www.FreeRTOS.org - Documentation, training, latest versions, license and contact details. http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products, including FreeRTOS+Trace - an indispensable productivity tool. Real Time Engineers ltd license FreeRTOS to High Integrity Systems, who sell the code with commercial support, indemnification, and middleware, under the OpenRTOS brand: http://www.OpenRTOS.com. High Integrity Systems also provide a safety engineered and independently SIL3 certified version under the SafeRTOS brand: http://www.SafeRTOS.com. */ /*----------------------------------------------------------- * Implementation of functions defined in portable.h for the PIC32MX port. *----------------------------------------------------------*/ /* Scheduler include files. */ #include "FreeRTOS.h" #include "task.h" /* Hardware specifics. */ #define portTIMER_PRESCALE 8 /* Bits within various registers. */ #define portIE_BIT ( 0x00000001 ) #define portEXL_BIT ( 0x00000002 ) /* The EXL bit is set to ensure interrupts do not occur while the context of the first task is being restored. */ #define portINITIAL_SR ( portIE_BIT | portEXL_BIT ) #ifndef configTICK_INTERRUPT_VECTOR #define configTICK_INTERRUPT_VECTOR _TIMER_1_VECTOR #endif /* Records the interrupt nesting depth. This starts at one as it will be decremented to 0 when the first task starts. */ volatile unsigned portBASE_TYPE uxInterruptNesting = 0x01; /* Stores the task stack pointer when a switch is made to use the system stack. */ unsigned portBASE_TYPE uxSavedTaskStackPointer = 0; /* The stack used by interrupt service routines that cause a context switch. */ portSTACK_TYPE xISRStack[ configISR_STACK_SIZE ] = { 0 }; /* The top of stack value ensures there is enough space to store 6 registers on the callers stack, as some functions seem to want to do this. */ const portSTACK_TYPE * const xISRStackTop = &( xISRStack[ configISR_STACK_SIZE - 7 ] ); /* * Place the prototype here to ensure the interrupt vector is correctly installed. * Note that because the interrupt is written in assembly, the IPL setting in the * following line of code has no effect. The interrupt priority is set by the * call to ConfigIntTimer1() in vApplicationSetupTickTimerInterrupt(). */ extern void __attribute__( (interrupt(ipl1), vector( configTICK_INTERRUPT_VECTOR ))) vPortTickInterruptHandler( void ); /* * The software interrupt handler that performs the yield. Note that, because * the interrupt is written in assembly, the IPL setting in the following line of * code has no effect. The interrupt priority is set by the call to * mConfigIntCoreSW0() in xPortStartScheduler(). */ void __attribute__( (interrupt(ipl1), vector(_CORE_SOFTWARE_0_VECTOR))) vPortYieldISR( void ); /*-----------------------------------------------------------*/ /* * See header file for description. */ portSTACK_TYPE *pxPortInitialiseStack( portSTACK_TYPE *pxTopOfStack, pdTASK_CODE pxCode, void *pvParameters ) { /* Ensure byte alignment is maintained when leaving this function. */ pxTopOfStack--; *pxTopOfStack = (portSTACK_TYPE) 0xDEADBEEF; pxTopOfStack--; *pxTopOfStack = (portSTACK_TYPE) 0x12345678; /* Word to which the stack pointer will be left pointing after context restore. */ pxTopOfStack--; *pxTopOfStack = (portSTACK_TYPE) _CP0_GET_CAUSE(); pxTopOfStack--; *pxTopOfStack = (portSTACK_TYPE) portINITIAL_SR; /* CP0_STATUS */ pxTopOfStack--; *pxTopOfStack = (portSTACK_TYPE) pxCode; /* CP0_EPC */ pxTopOfStack--; *pxTopOfStack = (portSTACK_TYPE) NULL; /* ra */ pxTopOfStack -= 15; *pxTopOfStack = (portSTACK_TYPE) pvParameters; /* Parameters to pass in */ pxTopOfStack -= 14; *pxTopOfStack = (portSTACK_TYPE) 0x00000000; /* critical nesting level - no longer used. */ pxTopOfStack--; return pxTopOfStack; } /*-----------------------------------------------------------*/ /* * Setup a timer for a regular tick. This function uses peripheral timer 1. * The function is declared weak so an application writer can use a different * timer by redefining this implementation. If a different timer is used then * configTICK_INTERRUPT_VECTOR must also be defined in FreeRTOSConfig.h to * ensure the RTOS provided tick interrupt handler is installed on the correct * vector number. When Timer 1 is used the vector number is defined as * _TIMER_1_VECTOR. */ __attribute__(( weak )) void vApplicationSetupTickTimerInterrupt( void ) { const unsigned long ulCompareMatch = ( (configPERIPHERAL_CLOCK_HZ / portTIMER_PRESCALE) / configTICK_RATE_HZ ) - 1; OpenTimer1( ( T1_ON | T1_PS_1_8 | T1_SOURCE_INT ), ulCompareMatch ); ConfigIntTimer1( T1_INT_ON | configKERNEL_INTERRUPT_PRIORITY ); } /*-----------------------------------------------------------*/ void vPortEndScheduler(void) { /* It is unlikely that the scheduler for the PIC port will get stopped once running. If required disable the tick interrupt here, then return to xPortStartScheduler(). */ for( ;; ); } /*-----------------------------------------------------------*/ portBASE_TYPE xPortStartScheduler( void ) { extern void vPortStartFirstTask( void ); extern void *pxCurrentTCB; /* Setup the software interrupt. */ mConfigIntCoreSW0( CSW_INT_ON | configKERNEL_INTERRUPT_PRIORITY | CSW_INT_SUB_PRIOR_0 ); /* Setup the timer to generate the tick. Interrupts will have been disabled by the time we get here. */ vApplicationSetupTickTimerInterrupt(); /* Kick off the highest priority task that has been created so far. Its stack location is loaded into uxSavedTaskStackPointer. */ uxSavedTaskStackPointer = *( unsigned portBASE_TYPE * ) pxCurrentTCB; vPortStartFirstTask(); /* Should never get here as the tasks will now be executing. */ return pdFALSE; } /*-----------------------------------------------------------*/ void vPortIncrementTick( void ) { unsigned portBASE_TYPE uxSavedStatus; uxSavedStatus = uxPortSetInterruptMaskFromISR(); vTaskIncrementTick(); vPortClearInterruptMaskFromISR( uxSavedStatus ); /* If we are using the preemptive scheduler then we might want to select a different task to execute. */ #if configUSE_PREEMPTION == 1 SetCoreSW0(); #endif /* configUSE_PREEMPTION */ /* Clear timer 0 interrupt. */ mT1ClearIntFlag(); } /*-----------------------------------------------------------*/ unsigned portBASE_TYPE uxPortSetInterruptMaskFromISR( void ) { unsigned portBASE_TYPE uxSavedStatusRegister; asm volatile ( "di" ); uxSavedStatusRegister = _CP0_GET_STATUS() | 0x01; /* This clears the IPL bits, then sets them to configMAX_SYSCALL_INTERRUPT_PRIORITY. This function should not be called from an interrupt that has a priority above configMAX_SYSCALL_INTERRUPT_PRIORITY so, when used correctly, the action can only result in the IPL being unchanged or raised, and therefore never lowered. */ _CP0_SET_STATUS( ( ( uxSavedStatusRegister & ( ~portALL_IPL_BITS ) ) ) | ( configMAX_SYSCALL_INTERRUPT_PRIORITY << portIPL_SHIFT ) ); return uxSavedStatusRegister; } /*-----------------------------------------------------------*/ void vPortClearInterruptMaskFromISR( unsigned portBASE_TYPE uxSavedStatusRegister ) { _CP0_SET_STATUS( uxSavedStatusRegister ); } /*-----------------------------------------------------------*/
ilikecake/Rocket-controller
software/freertos/freertos/Source/portable/MPLAB/PIC32MX/port.c
C
gpl-3.0
10,779
/* * PktGen by Steffen Schulz © 2009 * * Braindead TCP server that waits for a packet and then * - replies with stream of packets * - with inter-packet delays read as integers from stdin * * Disables Nagle Algo to prevent buffering in local network stack * */ #include <stdio.h> #include <stdlib.h> #include <signal.h> #include <stdarg.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <arpa/inet.h> #include <netdb.h> #include <fcntl.h> #define DEBUG (1) /* Basic signal handler closes nfq hooks on exit */ static void sig_handler(int signum) { printf("\nCaught Signal ...\n\n"); exit(0); } int main(int argc, char **argv) { struct sockaddr_in sin; struct sockaddr_in sout; int s = socket(AF_INET,SOCK_STREAM,0); unsigned int slen = sizeof(sout); unsigned int len = 0; char line[500]; long delay = 0; unsigned int cntr = 0; int port = 1194; int tmp = 0; sin.sin_family = AF_INET; sin.sin_port = htons(port); sin.sin_addr.s_addr = INADDR_ANY; /* make stdin non-blocking, i.e. optional */ int flags = fcntl(0, F_GETFL, 0); flags |= O_NONBLOCK; fcntl(0, F_SETFL, flags); /* close nfq hooks on exit */ if (signal(SIGINT, sig_handler) == SIG_IGN) signal(SIGINT, SIG_IGN); if (signal(SIGHUP, sig_handler) == SIG_IGN) signal(SIGHUP, SIG_IGN); if (signal(SIGTERM, sig_handler) == SIG_IGN) signal(SIGTERM, SIG_IGN); // wait for conn, store peer in sout bind(s, (struct sockaddr *)&sin, sizeof(sin)); listen(s, 2); int c = accept(s, (struct sockaddr *)&sout, &tmp); tmp=1; if (setsockopt(c, IPPROTO_TCP, TCP_NODELAY, &tmp, sizeof(tmp)) < 0) fprintf(stderr, "Error when disabling buffer..\n"); printf("Got connection from %s:%d, start sending..\n", inet_ntoa(sout.sin_addr), ntohs(sout.sin_port)); len = snprintf(line, 499, "%010d\n",cntr++); send(c, line, len+1,0); while (1) { if (fgets(line, 49, stdin)) { delay = atol(line); } else { if (argc > 1) exit(0); delay = 5000; } if (delay < 0) delay = 0; usleep(delay); len = snprintf(line, 499, "%010d\n",cntr++); send(c, line, len+1,0); } }
chandanmogal/ipsec-tfc
code/perfect-hiding-cc/tcpgen.c
C
gpl-3.0
2,149
/* armor.c - Armor filters * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2007, 2008, 2010 * Free Software Foundation, Inc. * * Author: Timo Schulz * * This file is part of OpenCDK. * * The OpenCDK 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 3 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 program. If not, see <http://www.gnu.org/licenses/> * * ChangeLog for basic BASE64 code (base64_encode, base64_decode): * Original author: Eric S. Raymond (Fetchmail) * Heavily modified by Brendan Cully <brendan@kublai.com> (Mutt) * Modify the code for generic use by Timo Schulz <twoaday@freakmail.de> */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <stdio.h> #include <string.h> #include <sys/stat.h> #include "opencdk.h" #include "main.h" #include "filters.h" #ifdef __MINGW32__ #define LF "\r\n" #define ALTLF "\n" #else #define LF "\n" #define ALTLF "\r\n" #endif #define CRCINIT 0xB704CE #define BAD -1 #define b64val(c) index64[(unsigned int)(c)] static u32 crc_table[] = { 0x000000, 0x864CFB, 0x8AD50D, 0x0C99F6, 0x93E6E1, 0x15AA1A, 0x1933EC, 0x9F7F17, 0xA18139, 0x27CDC2, 0x2B5434, 0xAD18CF, 0x3267D8, 0xB42B23, 0xB8B2D5, 0x3EFE2E, 0xC54E89, 0x430272, 0x4F9B84, 0xC9D77F, 0x56A868, 0xD0E493, 0xDC7D65, 0x5A319E, 0x64CFB0, 0xE2834B, 0xEE1ABD, 0x685646, 0xF72951, 0x7165AA, 0x7DFC5C, 0xFBB0A7, 0x0CD1E9, 0x8A9D12, 0x8604E4, 0x00481F, 0x9F3708, 0x197BF3, 0x15E205, 0x93AEFE, 0xAD50D0, 0x2B1C2B, 0x2785DD, 0xA1C926, 0x3EB631, 0xB8FACA, 0xB4633C, 0x322FC7, 0xC99F60, 0x4FD39B, 0x434A6D, 0xC50696, 0x5A7981, 0xDC357A, 0xD0AC8C, 0x56E077, 0x681E59, 0xEE52A2, 0xE2CB54, 0x6487AF, 0xFBF8B8, 0x7DB443, 0x712DB5, 0xF7614E, 0x19A3D2, 0x9FEF29, 0x9376DF, 0x153A24, 0x8A4533, 0x0C09C8, 0x00903E, 0x86DCC5, 0xB822EB, 0x3E6E10, 0x32F7E6, 0xB4BB1D, 0x2BC40A, 0xAD88F1, 0xA11107, 0x275DFC, 0xDCED5B, 0x5AA1A0, 0x563856, 0xD074AD, 0x4F0BBA, 0xC94741, 0xC5DEB7, 0x43924C, 0x7D6C62, 0xFB2099, 0xF7B96F, 0x71F594, 0xEE8A83, 0x68C678, 0x645F8E, 0xE21375, 0x15723B, 0x933EC0, 0x9FA736, 0x19EBCD, 0x8694DA, 0x00D821, 0x0C41D7, 0x8A0D2C, 0xB4F302, 0x32BFF9, 0x3E260F, 0xB86AF4, 0x2715E3, 0xA15918, 0xADC0EE, 0x2B8C15, 0xD03CB2, 0x567049, 0x5AE9BF, 0xDCA544, 0x43DA53, 0xC596A8, 0xC90F5E, 0x4F43A5, 0x71BD8B, 0xF7F170, 0xFB6886, 0x7D247D, 0xE25B6A, 0x641791, 0x688E67, 0xEEC29C, 0x3347A4, 0xB50B5F, 0xB992A9, 0x3FDE52, 0xA0A145, 0x26EDBE, 0x2A7448, 0xAC38B3, 0x92C69D, 0x148A66, 0x181390, 0x9E5F6B, 0x01207C, 0x876C87, 0x8BF571, 0x0DB98A, 0xF6092D, 0x7045D6, 0x7CDC20, 0xFA90DB, 0x65EFCC, 0xE3A337, 0xEF3AC1, 0x69763A, 0x578814, 0xD1C4EF, 0xDD5D19, 0x5B11E2, 0xC46EF5, 0x42220E, 0x4EBBF8, 0xC8F703, 0x3F964D, 0xB9DAB6, 0xB54340, 0x330FBB, 0xAC70AC, 0x2A3C57, 0x26A5A1, 0xA0E95A, 0x9E1774, 0x185B8F, 0x14C279, 0x928E82, 0x0DF195, 0x8BBD6E, 0x872498, 0x016863, 0xFAD8C4, 0x7C943F, 0x700DC9, 0xF64132, 0x693E25, 0xEF72DE, 0xE3EB28, 0x65A7D3, 0x5B59FD, 0xDD1506, 0xD18CF0, 0x57C00B, 0xC8BF1C, 0x4EF3E7, 0x426A11, 0xC426EA, 0x2AE476, 0xACA88D, 0xA0317B, 0x267D80, 0xB90297, 0x3F4E6C, 0x33D79A, 0xB59B61, 0x8B654F, 0x0D29B4, 0x01B042, 0x87FCB9, 0x1883AE, 0x9ECF55, 0x9256A3, 0x141A58, 0xEFAAFF, 0x69E604, 0x657FF2, 0xE33309, 0x7C4C1E, 0xFA00E5, 0xF69913, 0x70D5E8, 0x4E2BC6, 0xC8673D, 0xC4FECB, 0x42B230, 0xDDCD27, 0x5B81DC, 0x57182A, 0xD154D1, 0x26359F, 0xA07964, 0xACE092, 0x2AAC69, 0xB5D37E, 0x339F85, 0x3F0673, 0xB94A88, 0x87B4A6, 0x01F85D, 0x0D61AB, 0x8B2D50, 0x145247, 0x921EBC, 0x9E874A, 0x18CBB1, 0xE37B16, 0x6537ED, 0x69AE1B, 0xEFE2E0, 0x709DF7, 0xF6D10C, 0xFA48FA, 0x7C0401, 0x42FA2F, 0xC4B6D4, 0xC82F22, 0x4E63D9, 0xD11CCE, 0x575035, 0x5BC9C3, 0xDD8538 }; static const char *armor_begin[] = { "BEGIN PGP MESSAGE", "BEGIN PGP PUBLIC KEY BLOCK", "BEGIN PGP PRIVATE KEY BLOCK", "BEGIN PGP SIGNATURE", NULL }; static const char *armor_end[] = { "END PGP MESSAGE", "END PGP PUBLIC KEY BLOCK", "END PGP PRIVATE KEY BLOCK", "END PGP SIGNATURE", NULL }; static const char *valid_headers[] = { "Comment", "Version", "MessageID", "Hash", "Charset", NULL }; static char b64chars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; static int index64[128] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1 }; /* encode a raw binary buffer to a null-terminated base64 strings */ static int base64_encode (char *out, const byte * in, size_t len, size_t olen) { if (!out || !in) { gnutls_assert (); return CDK_Inv_Value; } while (len >= 3 && olen > 10) { *out++ = b64chars[in[0] >> 2]; *out++ = b64chars[((in[0] << 4) & 0x30) | (in[1] >> 4)]; *out++ = b64chars[((in[1] << 2) & 0x3c) | (in[2] >> 6)]; *out++ = b64chars[in[2] & 0x3f]; olen -= 4; len -= 3; in += 3; } /* clean up remainder */ if (len > 0 && olen > 4) { byte fragment = 0; *out++ = b64chars[in[0] >> 2]; fragment = (in[0] << 4) & 0x30; if (len > 1) fragment |= in[1] >> 4; *out++ = b64chars[fragment]; *out++ = (len < 2) ? '=' : b64chars[(in[1] << 2) & 0x3c]; *out++ = '='; } *out = '\0'; return 0; } /* Convert '\0'-terminated base64 string to raw byte buffer. Returns length of returned buffer, or -1 on error. */ static int base64_decode (byte * out, const char *in) { size_t len; byte digit1, digit2, digit3, digit4; if (!out || !in) { gnutls_assert (); return -1; } len = 0; do { digit1 = in[0]; if (digit1 > 127 || b64val (digit1) == BAD) { gnutls_assert (); return -1; } digit2 = in[1]; if (digit2 > 127 || b64val (digit2) == BAD) { gnutls_assert (); return -1; } digit3 = in[2]; if (digit3 > 127 || ((digit3 != '=') && (b64val (digit3) == BAD))) { gnutls_assert (); return -1; } digit4 = in[3]; if (digit4 > 127 || ((digit4 != '=') && (b64val (digit4) == BAD))) { gnutls_assert (); return -1; } in += 4; /* digits are already sanity-checked */ *out++ = (b64val (digit1) << 2) | (b64val (digit2) >> 4); len++; if (digit3 != '=') { *out++ = ((b64val (digit2) << 4) & 0xf0) | (b64val (digit3) >> 2); len++; if (digit4 != '=') { *out++ = ((b64val (digit3) << 6) & 0xc0) | b64val (digit4); len++; } } } while (*in && digit4 != '='); return len; } /* Return the compression algorithm in @r_zipalgo. If the parameter is not set after execution, the stream is not compressed. */ static int compress_get_algo (cdk_stream_t inp, int *r_zipalgo) { byte plain[512]; char buf[128]; int nread, pkttype; *r_zipalgo = 0; cdk_stream_seek (inp, 0); while (!cdk_stream_eof (inp)) { nread = _cdk_stream_gets (inp, buf, DIM (buf) - 1); if (!nread || nread == -1) break; if (nread == 1 && !cdk_stream_eof (inp) && (nread = _cdk_stream_gets (inp, buf, DIM (buf) - 1)) > 0) { base64_decode (plain, buf); if (!(*plain & 0x80)) break; pkttype = *plain & 0x40 ? (*plain & 0x3f) : ((*plain >> 2) & 0xf); if (pkttype == CDK_PKT_COMPRESSED && r_zipalgo) { _gnutls_buffers_log ("armor compressed (algo=%d)\n", *(plain + 1)); *r_zipalgo = *(plain + 1); } break; } } return 0; } static int check_armor (cdk_stream_t inp, int *r_zipalgo) { char buf[4096]; size_t nread; int check; check = 0; nread = cdk_stream_read (inp, buf, DIM (buf) - 1); if (nread > 0) { buf[nread] = '\0'; if (strstr (buf, "-----BEGIN PGP")) { compress_get_algo (inp, r_zipalgo); check = 1; } cdk_stream_seek (inp, 0); } return check; } static int is_armored (int ctb) { int pkttype = 0; if (!(ctb & 0x80)) { gnutls_assert (); return 1; /* invalid packet: assume it is armored */ } pkttype = ctb & 0x40 ? (ctb & 0x3f) : ((ctb >> 2) & 0xf); switch (pkttype) { case CDK_PKT_MARKER: case CDK_PKT_ONEPASS_SIG: case CDK_PKT_PUBLIC_KEY: case CDK_PKT_SECRET_KEY: case CDK_PKT_PUBKEY_ENC: case CDK_PKT_SIGNATURE: case CDK_PKT_LITERAL: case CDK_PKT_COMPRESSED: return 0; /* seems to be a regular packet: not armored */ } return 1; } static u32 update_crc (u32 crc, const byte * buf, size_t buflen) { unsigned int j; if (!crc) crc = CRCINIT; for (j = 0; j < buflen; j++) crc = (crc << 8) ^ crc_table[0xff & ((crc >> 16) ^ buf[j])]; crc &= 0xffffff; return crc; } static cdk_error_t armor_encode (void *data, FILE * in, FILE * out) { armor_filter_t *afx = data; struct stat statbuf; char crcbuf[5], buf[128], raw[49]; byte crcbuf2[3]; size_t nread = 0; const char *lf; if (!afx) { gnutls_assert (); return CDK_Inv_Value; } if (afx->idx < 0 || afx->idx > (int) DIM (armor_begin) || afx->idx2 < 0 || afx->idx2 > (int) DIM (armor_end)) { gnutls_assert (); return CDK_Inv_Value; } _gnutls_buffers_log ("armor filter: encode\n"); memset (crcbuf, 0, sizeof (crcbuf)); lf = afx->le ? afx->le : LF; fprintf (out, "-----%s-----%s", armor_begin[afx->idx], lf); fprintf (out, "Version: OpenPrivacy " PACKAGE_VERSION "%s", lf); if (afx->hdrlines) fwrite (afx->hdrlines, 1, strlen (afx->hdrlines), out); fprintf (out, "%s", lf); if (fstat (fileno (in), &statbuf)) { gnutls_assert (); return CDK_General_Error; } while (!feof (in)) { nread = fread (raw, 1, DIM (raw) - 1, in); if (!nread) break; if (ferror (in)) { gnutls_assert (); return CDK_File_Error; } afx->crc = update_crc (afx->crc, (byte *) raw, nread); base64_encode (buf, (byte *) raw, nread, DIM (buf) - 1); fprintf (out, "%s%s", buf, lf); } crcbuf2[0] = afx->crc >> 16; crcbuf2[1] = afx->crc >> 8; crcbuf2[2] = afx->crc; crcbuf[0] = b64chars[crcbuf2[0] >> 2]; crcbuf[1] = b64chars[((crcbuf2[0] << 4) & 0x30) | (crcbuf2[1] >> 4)]; crcbuf[2] = b64chars[((crcbuf2[1] << 2) & 0x3c) | (crcbuf2[2] >> 6)]; crcbuf[3] = b64chars[crcbuf2[2] & 0x3f]; fprintf (out, "=%s%s", crcbuf, lf); fprintf (out, "-----%s-----%s", armor_end[afx->idx2], lf); return 0; } /** * cdk_armor_filter_use: * @inp: the stream to check * * Check if the stream contains armored data. **/ int cdk_armor_filter_use (cdk_stream_t inp) { int c, check; int zipalgo; zipalgo = 0; c = cdk_stream_getc (inp); if (c == EOF) return 0; /* EOF, doesn't matter whether armored or not */ cdk_stream_seek (inp, 0); check = is_armored (c); if (check) { check = check_armor (inp, &zipalgo); if (zipalgo) _cdk_stream_set_compress_algo (inp, zipalgo); } return check; } static int search_header (const char *buf, const char **array) { const char *s; int i; if (strlen (buf) < 5 || strncmp (buf, "-----", 5)) { gnutls_assert (); return -1; } for (i = 0; (s = array[i]); i++) { if (!strncmp (s, buf + 5, strlen (s))) return i; } return -1; } const char * _cdk_armor_get_lineend (void) { return LF; } static cdk_error_t armor_decode (void *data, FILE * in, FILE * out) { armor_filter_t *afx = data; const char *s; char buf[127]; byte raw[128], crcbuf[4]; u32 crc2 = 0; ssize_t nread = 0; int i, pgp_data = 0; cdk_error_t rc = 0; int len; if (!afx) { gnutls_assert (); return CDK_Inv_Value; } _gnutls_buffers_log ("armor filter: decode\n"); fseek (in, 0, SEEK_SET); /* Search the begin of the message */ while (!feof (in) && !pgp_data) { s = fgets (buf, DIM (buf) - 1, in); if (!s) break; afx->idx = search_header (buf, armor_begin); if (afx->idx >= 0) pgp_data = 1; } if (feof (in) || !pgp_data) { gnutls_assert (); return CDK_Armor_Error; /* no data found */ } /* Parse header until the empty line is reached */ while (!feof (in)) { s = fgets (buf, DIM (buf) - 1, in); if (!s) return CDK_EOF; if (strcmp (s, LF) == 0 || strcmp (s, ALTLF) == 0) { rc = 0; break; /* empty line */ } /* From RFC2440: OpenPGP should consider improperly formatted Armor Headers to be corruption of the ASCII Armor. A colon and a single space separate the key and value. */ if (!strstr (buf, ": ")) { gnutls_assert (); return CDK_Armor_Error; } rc = CDK_General_Error; for (i = 0; (s = valid_headers[i]); i++) { if (!strncmp (s, buf, strlen (s))) rc = 0; } if (rc) { /* From RFC2440: Unknown keys should be reported to the user, but OpenPGP should continue to process the message. */ _cdk_log_info ("unknown header: `%s'\n", buf); rc = 0; } } /* Read the data body */ while (!feof (in)) { s = fgets (buf, DIM (buf) - 1, in); if (!s) break; len = strlen(buf); if (buf[len - 1] == '\n') buf[len - 1] = '\0'; if (buf[len - 1] == '\r') buf[len - 1] = '\0'; if (buf[0] == '=' && strlen (s) == 5) { /* CRC */ memset (crcbuf, 0, sizeof (crcbuf)); base64_decode (crcbuf, buf + 1); crc2 = (crcbuf[0] << 16) | (crcbuf[1] << 8) | crcbuf[2]; break; /* stop here */ } else { nread = base64_decode (raw, buf); if (nread == -1 || nread == 0) break; afx->crc = update_crc (afx->crc, raw, nread); fwrite (raw, 1, nread, out); } } /* Search the tail of the message */ s = fgets (buf, DIM (buf) - 1, in); if (s) { int len = strlen(buf); if (buf[len - 1] == '\n') buf[len - 1] = '\0'; if (buf[len - 1] == '\r') buf[len - 1] = '\0'; rc = CDK_General_Error; afx->idx2 = search_header (buf, armor_end); if (afx->idx2 >= 0) rc = 0; } /* This catches error when no tail was found or the header is different then the tail line. */ if (rc || afx->idx != afx->idx2) rc = CDK_Armor_Error; afx->crc_okay = (afx->crc == crc2) ? 1 : 0; if (!afx->crc_okay && !rc) { _gnutls_buffers_log ("file crc=%08X afx_crc=%08X\n", (unsigned int) crc2, (unsigned int) afx->crc); rc = CDK_Armor_CRC_Error; } return rc; } /** * cdk_file_armor: * @hd: Handle * @file: Name of the file to protect. * @output: Output filename. * * Protect a file with ASCII armor. **/ cdk_error_t cdk_file_armor (cdk_ctx_t hd, const char *file, const char *output) { cdk_stream_t inp, out; cdk_error_t rc; rc = _cdk_check_args (hd->opt.overwrite, file, output); if (rc) return rc; rc = cdk_stream_open (file, &inp); if (rc) { gnutls_assert (); return rc; } rc = cdk_stream_new (output, &out); if (rc) { cdk_stream_close (inp); gnutls_assert (); return rc; } cdk_stream_set_armor_flag (out, CDK_ARMOR_MESSAGE); if (hd->opt.compress) rc = cdk_stream_set_compress_flag (out, hd->compress.algo, hd->compress.level); if (!rc) rc = cdk_stream_set_literal_flag (out, 0, file); if (!rc) rc = cdk_stream_kick_off (inp, out); if (!rc) rc = _cdk_stream_get_errno (out); cdk_stream_close (out); cdk_stream_close (inp); return rc; } /** * cdk_file_dearmor: * @file: Name of the file to unprotect. * @output: Output filename. * * Remove ASCII armor from a file. **/ cdk_error_t cdk_file_dearmor (const char *file, const char *output) { cdk_stream_t inp, out; cdk_error_t rc; int zipalgo; rc = _cdk_check_args (1, file, output); if (rc) { gnutls_assert (); return rc; } rc = cdk_stream_open (file, &inp); if (rc) { gnutls_assert (); return rc; } rc = cdk_stream_create (output, &out); if (rc) { cdk_stream_close (inp); gnutls_assert (); return rc; } if (cdk_armor_filter_use (inp)) { rc = cdk_stream_set_literal_flag (inp, 0, NULL); zipalgo = cdk_stream_is_compressed (inp); if (zipalgo) rc = cdk_stream_set_compress_flag (inp, zipalgo, 0); if (!rc) rc = cdk_stream_set_armor_flag (inp, 0); if (!rc) rc = cdk_stream_kick_off (inp, out); if (!rc) rc = _cdk_stream_get_errno (inp); } cdk_stream_close (inp); cdk_stream_close (out); gnutls_assert (); return rc; } int _cdk_filter_armor (void *data, int ctl, FILE * in, FILE * out) { if (ctl == STREAMCTL_READ) return armor_decode (data, in, out); else if (ctl == STREAMCTL_WRITE) return armor_encode (data, in, out); else if (ctl == STREAMCTL_FREE) { armor_filter_t *afx = data; if (afx) { _gnutls_buffers_log ("free armor filter\n"); afx->idx = afx->idx2 = 0; afx->crc = afx->crc_okay = 0; return 0; } } gnutls_assert (); return CDK_Inv_Mode; } /** * cdk_armor_encode_buffer: * @inbuf: the raw input buffer * @inlen: raw buffer len * @outbuf: the destination buffer for the base64 output * @outlen: destination buffer len * @nwritten: actual length of the base64 data * @type: the base64 file type. * * Encode the given buffer into base64 format. The base64 * string will be null terminated but the null will * not be contained in the size. **/ cdk_error_t cdk_armor_encode_buffer (const byte * inbuf, size_t inlen, char *outbuf, size_t outlen, size_t * nwritten, int type) { const char *head, *tail, *le; byte tempbuf[48]; char tempout[128]; size_t pos, off, len, rest; if (!inbuf || !nwritten) { gnutls_assert (); return CDK_Inv_Value; } if (type > CDK_ARMOR_SIGNATURE) { gnutls_assert (); return CDK_Inv_Mode; } head = armor_begin[type]; tail = armor_end[type]; le = _cdk_armor_get_lineend (); pos = strlen (head) + 10 + 2 + 2 + strlen (tail) + 10 + 2 + 5 + 2 + 1; /* The output data is 4/3 times larger, plus a line end for each line. */ pos += (4 * inlen / 3) + 2 * (4 * inlen / 3 / 64) + 1; if (outbuf && outlen < pos) { gnutls_assert (); *nwritten = pos; return CDK_Too_Short; } /* Only return the size of the output. */ if (!outbuf) { *nwritten = pos; return 0; } pos = 0; memset (outbuf, 0, outlen); memcpy (outbuf + pos, "-----", 5); pos += 5; memcpy (outbuf + pos, head, strlen (head)); pos += strlen (head); memcpy (outbuf + pos, "-----", 5); pos += 5; memcpy (outbuf + pos, le, strlen (le)); pos += strlen (le); memcpy (outbuf + pos, le, strlen (le)); pos += strlen (le); rest = inlen; for (off = 0; off < inlen;) { if (rest > 48) { memcpy (tempbuf, inbuf + off, 48); off += 48; len = 48; } else { memcpy (tempbuf, inbuf + off, rest); off += rest; len = rest; } rest -= len; base64_encode (tempout, tempbuf, len, DIM (tempout) - 1); memcpy (outbuf + pos, tempout, strlen (tempout)); pos += strlen (tempout); memcpy (outbuf + pos, le, strlen (le)); pos += strlen (le); } memcpy (outbuf + pos, "-----", 5); pos += 5; memcpy (outbuf + pos, tail, strlen (tail)); pos += strlen (tail); memcpy (outbuf + pos, "-----", 5); pos += 5; memcpy (outbuf + pos, le, strlen (le)); pos += strlen (le); outbuf[pos] = 0; *nwritten = pos - 1; return 0; }
freedesktop-unofficial-mirror/gstreamer-sdk__gnutls
lib/opencdk/armor.c
C
gpl-3.0
21,279
// tutorial06.c // A pedagogical video player that really works! // // Code based on FFplay, Copyright (c) 2003 Fabrice Bellard, // and a tutorial by Martin Bohme (boehme@inb.uni-luebeckREMOVETHIS.de) // Tested on Gentoo, CVS version 5/01/07 compiled with GCC 4.1.1 // Use // // gcc -o tutorial02 tutorial02.c -lavutil -lavformat -lavcodec -lz -lm `sdl-config --cflags --libs` // to build (assuming libavformat and libavcodec are correctly installed, // and assuming you have sdl-config. Please refer to SDL docs for your installation.) // // Run using // tutorial06 myvideofile.mpg // // to play the video. #include <ffmpeg/avcodec.h> #include <ffmpeg/avformat.h> #include <SDL.h> #include <SDL_thread.h> #ifdef __MINGW32__ #undef main /* Prevents SDL from overriding main() */ #endif #include <stdio.h> #include <math.h> #define SDL_AUDIO_BUFFER_SIZE 1024 #define MAX_AUDIOQ_SIZE (5 * 16 * 1024) #define MAX_VIDEOQ_SIZE (5 * 256 * 1024) #define AV_SYNC_THRESHOLD 0.01 #define AV_NOSYNC_THRESHOLD 10.0 #define SAMPLE_CORRECTION_PERCENT_MAX 10 #define AUDIO_DIFF_AVG_NB 20 #define FF_ALLOC_EVENT (SDL_USEREVENT) #define FF_REFRESH_EVENT (SDL_USEREVENT + 1) #define FF_QUIT_EVENT (SDL_USEREVENT + 2) #define VIDEO_PICTURE_QUEUE_SIZE 1 #define DEFAULT_AV_SYNC_TYPE AV_SYNC_VIDEO_MASTER typedef struct PacketQueue { AVPacketList *first_pkt, *last_pkt; int nb_packets; int size; SDL_mutex *mutex; SDL_cond *cond; } PacketQueue; typedef struct VideoPicture { SDL_Overlay *bmp; int width, height; /* source height & width */ int allocated; double pts; } VideoPicture; typedef struct VideoState { AVFormatContext *pFormatCtx; int videoStream, audioStream; int av_sync_type; double external_clock; /* external clock base */ int64_t external_clock_time; double audio_clock; AVStream *audio_st; PacketQueue audioq; uint8_t audio_buf[(AVCODEC_MAX_AUDIO_FRAME_SIZE * 3) / 2]; unsigned int audio_buf_size; unsigned int audio_buf_index; AVPacket audio_pkt; uint8_t *audio_pkt_data; int audio_pkt_size; int audio_hw_buf_size; double audio_diff_cum; /* used for AV difference average computation */ double audio_diff_avg_coef; double audio_diff_threshold; int audio_diff_avg_count; double frame_timer; double frame_last_pts; double frame_last_delay; double video_clock; ///<pts of last decoded frame / predicted pts of next decoded frame double video_current_pts; ///<current displayed pts (different from video_clock if frame fifos are used) int64_t video_current_pts_time; ///<time (av_gettime) at which we updated video_current_pts - used to have running video pts AVStream *video_st; PacketQueue videoq; VideoPicture pictq[VIDEO_PICTURE_QUEUE_SIZE]; int pictq_size, pictq_rindex, pictq_windex; SDL_mutex *pictq_mutex; SDL_cond *pictq_cond; SDL_Thread *parse_tid; SDL_Thread *video_tid; char filename[1024]; int quit; } VideoState; enum { AV_SYNC_AUDIO_MASTER, AV_SYNC_VIDEO_MASTER, AV_SYNC_EXTERNAL_MASTER, }; SDL_Surface *screen; /* Since we only have one decoding thread, the Big Struct can be global in case we need it. */ VideoState *global_video_state; void packet_queue_init(PacketQueue *q) { memset(q, 0, sizeof(PacketQueue)); q->mutex = SDL_CreateMutex(); q->cond = SDL_CreateCond(); } int packet_queue_put(PacketQueue *q, AVPacket *pkt) { AVPacketList *pkt1; if(av_dup_packet(pkt) < 0) { return -1; } pkt1 = av_malloc(sizeof(AVPacketList)); if (!pkt1) return -1; pkt1->pkt = *pkt; pkt1->next = NULL; SDL_LockMutex(q->mutex); if (!q->last_pkt) q->first_pkt = pkt1; else q->last_pkt->next = pkt1; q->last_pkt = pkt1; q->nb_packets++; q->size += pkt1->pkt.size; SDL_CondSignal(q->cond); SDL_UnlockMutex(q->mutex); return 0; } static int packet_queue_get(PacketQueue *q, AVPacket *pkt, int block) { AVPacketList *pkt1; int ret; SDL_LockMutex(q->mutex); for(;;) { if(global_video_state->quit) { ret = -1; break; } pkt1 = q->first_pkt; if (pkt1) { q->first_pkt = pkt1->next; if (!q->first_pkt) q->last_pkt = NULL; q->nb_packets--; q->size -= pkt1->pkt.size; *pkt = pkt1->pkt; av_free(pkt1); ret = 1; break; } else if (!block) { ret = 0; break; } else { SDL_CondWait(q->cond, q->mutex); } } SDL_UnlockMutex(q->mutex); return ret; } double get_audio_clock(VideoState *is) { double pts; int hw_buf_size, bytes_per_sec, n; pts = is->audio_clock; /* maintained in the audio thread */ hw_buf_size = is->audio_buf_size - is->audio_buf_index; bytes_per_sec = 0; n = is->audio_st->codec->channels * 2; if(is->audio_st) { bytes_per_sec = is->audio_st->codec->sample_rate * n; } if(bytes_per_sec) { pts -= (double)hw_buf_size / bytes_per_sec; } return pts; } double get_video_clock(VideoState *is) { double delta; delta = (av_gettime() - is->video_current_pts_time) / 1000000.0; return is->video_current_pts + delta; } double get_external_clock(VideoState *is) { return av_gettime() / 1000000.0; } double get_master_clock(VideoState *is) { if(is->av_sync_type == AV_SYNC_VIDEO_MASTER) { return get_video_clock(is); } else if(is->av_sync_type == AV_SYNC_AUDIO_MASTER) { return get_audio_clock(is); } else { return get_external_clock(is); } } /* Add or subtract samples to get a better sync, return new audio buffer size */ int synchronize_audio(VideoState *is, short *samples, int samples_size, double pts) { int n; double ref_clock; n = 2 * is->audio_st->codec->channels; if(is->av_sync_type != AV_SYNC_AUDIO_MASTER) { double diff, avg_diff; int wanted_size, min_size, max_size, nb_samples; ref_clock = get_master_clock(is); diff = get_audio_clock(is) - ref_clock; if(diff < AV_NOSYNC_THRESHOLD) { // accumulate the diffs is->audio_diff_cum = diff + is->audio_diff_avg_coef * is->audio_diff_cum; if(is->audio_diff_avg_count < AUDIO_DIFF_AVG_NB) { is->audio_diff_avg_count++; } else { avg_diff = is->audio_diff_cum * (1.0 - is->audio_diff_avg_coef); if(fabs(avg_diff) >= is->audio_diff_threshold) { wanted_size = samples_size + ((int)(diff * is->audio_st->codec->sample_rate) * n); min_size = samples_size * ((100 - SAMPLE_CORRECTION_PERCENT_MAX) / 100); max_size = samples_size * ((100 + SAMPLE_CORRECTION_PERCENT_MAX) / 100); if(wanted_size < min_size) { wanted_size = min_size; } else if (wanted_size > max_size) { wanted_size = max_size; } if(wanted_size < samples_size) { /* remove samples */ samples_size = wanted_size; } else if(wanted_size > samples_size) { uint8_t *samples_end, *q; int nb; /* add samples by copying final sample*/ nb = (samples_size - wanted_size); samples_end = (uint8_t *)samples + samples_size - n; q = samples_end + n; while(nb > 0) { memcpy(q, samples_end, n); q += n; nb -= n; } samples_size = wanted_size; } } } } else { /* difference is TOO big; reset diff stuff */ is->audio_diff_avg_count = 0; is->audio_diff_cum = 0; } } return samples_size; } int audio_decode_frame(VideoState *is, uint8_t *audio_buf, int buf_size, double *pts_ptr) { int len1, data_size, n; AVPacket *pkt = &is->audio_pkt; double pts; for(;;) { while(is->audio_pkt_size > 0) { data_size = buf_size; len1 = avcodec_decode_audio2(is->audio_st->codec, (int16_t *)audio_buf, &data_size, is->audio_pkt_data, is->audio_pkt_size); if(len1 < 0) { /* if error, skip frame */ is->audio_pkt_size = 0; break; } is->audio_pkt_data += len1; is->audio_pkt_size -= len1; if(data_size <= 0) { /* No data yet, get more frames */ continue; } pts = is->audio_clock; *pts_ptr = pts; n = 2 * is->audio_st->codec->channels; is->audio_clock += (double)data_size / (double)(n * is->audio_st->codec->sample_rate); /* We have data, return it and come back for more later */ return data_size; } if(pkt->data) av_free_packet(pkt); if(is->quit) { return -1; } /* next packet */ if(packet_queue_get(&is->audioq, pkt, 1) < 0) { return -1; } is->audio_pkt_data = pkt->data; is->audio_pkt_size = pkt->size; /* if update, update the audio clock w/pts */ if(pkt->pts != AV_NOPTS_VALUE) { is->audio_clock = av_q2d(is->audio_st->time_base)*pkt->pts; } } } void audio_callback(void *userdata, Uint8 *stream, int len) { VideoState *is = (VideoState *)userdata; int len1, audio_size; double pts; while(len > 0) { if(is->audio_buf_index >= is->audio_buf_size) { /* We have already sent all our data; get more */ audio_size = audio_decode_frame(is, is->audio_buf, sizeof(is->audio_buf), &pts); if(audio_size < 0) { /* If error, output silence */ is->audio_buf_size = 1024; memset(is->audio_buf, 0, is->audio_buf_size); } else { audio_size = synchronize_audio(is, (int16_t *)is->audio_buf, audio_size, pts); is->audio_buf_size = audio_size; } is->audio_buf_index = 0; } len1 = is->audio_buf_size - is->audio_buf_index; if(len1 > len) len1 = len; memcpy(stream, (uint8_t *)is->audio_buf + is->audio_buf_index, len1); len -= len1; stream += len1; is->audio_buf_index += len1; } } static Uint32 sdl_refresh_timer_cb(Uint32 interval, void *opaque) { SDL_Event event; event.type = FF_REFRESH_EVENT; event.user.data1 = opaque; SDL_PushEvent(&event); return 0; /* 0 means stop timer */ } /* schedule a video refresh in 'delay' ms */ static void schedule_refresh(VideoState *is, int delay) { SDL_AddTimer(delay, sdl_refresh_timer_cb, is); } void video_display(VideoState *is) { SDL_Rect rect; VideoPicture *vp; AVPicture pict; float aspect_ratio; int w, h, x, y; int i; vp = &is->pictq[is->pictq_rindex]; if(vp->bmp) { if(is->video_st->codec->sample_aspect_ratio.num == 0) { aspect_ratio = 0; } else { aspect_ratio = av_q2d(is->video_st->codec->sample_aspect_ratio) * is->video_st->codec->width / is->video_st->codec->height; } if(aspect_ratio <= 0.0) { aspect_ratio = (float)is->video_st->codec->width / (float)is->video_st->codec->height; } h = screen->h; w = ((int)rint(h * aspect_ratio)) & -3; if(w > screen->w) { w = screen->w; h = ((int)rint(w / aspect_ratio)) & -3; } x = (screen->w - w) / 2; y = (screen->h - h) / 2; rect.x = x; rect.y = y; rect.w = w; rect.h = h; SDL_DisplayYUVOverlay(vp->bmp, &rect); } } void video_refresh_timer(void *userdata) { VideoState *is = (VideoState *)userdata; VideoPicture *vp; double actual_delay, delay, sync_threshold, ref_clock, diff; if(is->video_st) { if(is->pictq_size == 0) { schedule_refresh(is, 1); } else { vp = &is->pictq[is->pictq_rindex]; is->video_current_pts = vp->pts; is->video_current_pts_time = av_gettime(); delay = vp->pts - is->frame_last_pts; /* the pts from last time */ if(delay <= 0 || delay >= 1.0) { /* if incorrect delay, use previous one */ delay = is->frame_last_delay; } /* save for next time */ is->frame_last_delay = delay; is->frame_last_pts = vp->pts; /* update delay to sync to audio if not master source */ if(is->av_sync_type != AV_SYNC_VIDEO_MASTER) { ref_clock = get_master_clock(is); diff = vp->pts - ref_clock; /* Skip or repeat the frame. Take delay into account FFPlay still doesn't "know if this is the best guess." */ sync_threshold = (delay > AV_SYNC_THRESHOLD) ? delay : AV_SYNC_THRESHOLD; if(fabs(diff) < AV_NOSYNC_THRESHOLD) { if(diff <= -sync_threshold) { delay = 0; } else if(diff >= sync_threshold) { delay = 2 * delay; } } } is->frame_timer += delay; /* computer the REAL delay */ actual_delay = is->frame_timer - (av_gettime() / 1000000.0); if(actual_delay < 0.010) { /* Really it should skip the picture instead */ actual_delay = 0.010; } schedule_refresh(is, (int)(actual_delay * 1000 + 0.5)); /* show the picture! */ video_display(is); /* update queue for next picture! */ if(++is->pictq_rindex == VIDEO_PICTURE_QUEUE_SIZE) { is->pictq_rindex = 0; } SDL_LockMutex(is->pictq_mutex); is->pictq_size--; SDL_CondSignal(is->pictq_cond); SDL_UnlockMutex(is->pictq_mutex); } } else { schedule_refresh(is, 100); } } void alloc_picture(void *userdata) { VideoState *is = (VideoState *)userdata; VideoPicture *vp; vp = &is->pictq[is->pictq_windex]; if(vp->bmp) { // we already have one make another, bigger/smaller SDL_FreeYUVOverlay(vp->bmp); } // Allocate a place to put our YUV image on that screen vp->bmp = SDL_CreateYUVOverlay(is->video_st->codec->width, is->video_st->codec->height, SDL_YV12_OVERLAY, screen); vp->width = is->video_st->codec->width; vp->height = is->video_st->codec->height; SDL_LockMutex(is->pictq_mutex); vp->allocated = 1; SDL_CondSignal(is->pictq_cond); SDL_UnlockMutex(is->pictq_mutex); } int queue_picture(VideoState *is, AVFrame *pFrame, double pts) { VideoPicture *vp; int dst_pix_fmt; AVPicture pict; /* wait until we have space for a new pic */ SDL_LockMutex(is->pictq_mutex); while(is->pictq_size >= VIDEO_PICTURE_QUEUE_SIZE && !is->quit) { SDL_CondWait(is->pictq_cond, is->pictq_mutex); } SDL_UnlockMutex(is->pictq_mutex); if(is->quit) return -1; // windex is set to 0 initially vp = &is->pictq[is->pictq_windex]; /* allocate or resize the buffer! */ if(!vp->bmp || vp->width != is->video_st->codec->width || vp->height != is->video_st->codec->height) { SDL_Event event; vp->allocated = 0; /* we have to do it in the main thread */ event.type = FF_ALLOC_EVENT; event.user.data1 = is; SDL_PushEvent(&event); /* wait until we have a picture allocated */ SDL_LockMutex(is->pictq_mutex); while(!vp->allocated && !is->quit) { SDL_CondWait(is->pictq_cond, is->pictq_mutex); } SDL_UnlockMutex(is->pictq_mutex); if(is->quit) { return -1; } } /* We have a place to put our picture on the queue */ /* If we are skipping a frame, do we set this to null but still return vp->allocated = 1? */ if(vp->bmp) { SDL_LockYUVOverlay(vp->bmp); dst_pix_fmt = PIX_FMT_YUV420P; /* point pict at the queue */ pict.data[0] = vp->bmp->pixels[0]; pict.data[1] = vp->bmp->pixels[2]; pict.data[2] = vp->bmp->pixels[1]; pict.linesize[0] = vp->bmp->pitches[0]; pict.linesize[1] = vp->bmp->pitches[2]; pict.linesize[2] = vp->bmp->pitches[1]; // Convert the image into YUV format that SDL uses img_convert(&pict, dst_pix_fmt, (AVPicture *)pFrame, is->video_st->codec->pix_fmt, is->video_st->codec->width, is->video_st->codec->height); SDL_UnlockYUVOverlay(vp->bmp); vp->pts = pts; /* now we inform our display thread that we have a pic ready */ if(++is->pictq_windex == VIDEO_PICTURE_QUEUE_SIZE) { is->pictq_windex = 0; } SDL_LockMutex(is->pictq_mutex); is->pictq_size++; SDL_UnlockMutex(is->pictq_mutex); } return 0; } double synchronize_video(VideoState *is, AVFrame *src_frame, double pts) { double frame_delay; if(pts != 0) { /* if we have pts, set video clock to it */ is->video_clock = pts; } else { /* if we aren't given a pts, set it to the clock */ pts = is->video_clock; } /* update the video clock */ frame_delay = av_q2d(is->video_st->codec->time_base); /* if we are repeating a frame, adjust clock accordingly */ frame_delay += src_frame->repeat_pict * (frame_delay * 0.5); is->video_clock += frame_delay; return pts; } uint64_t global_video_pkt_pts = AV_NOPTS_VALUE; /* These are called whenever we allocate a frame * buffer. We use this to store the global_pts in * a frame at the time it is allocated. */ int our_get_buffer(struct AVCodecContext *c, AVFrame *pic) { int ret = avcodec_default_get_buffer(c, pic); uint64_t *pts = av_malloc(sizeof(uint64_t)); *pts = global_video_pkt_pts; pic->opaque = pts; return ret; } void our_release_buffer(struct AVCodecContext *c, AVFrame *pic) { if(pic) av_freep(&pic->opaque); avcodec_default_release_buffer(c, pic); } int video_thread(void *arg) { VideoState *is = (VideoState *)arg; AVPacket pkt1, *packet = &pkt1; int len1, frameFinished; AVFrame *pFrame; double pts; pFrame = avcodec_alloc_frame(); for(;;) { if(packet_queue_get(&is->videoq, packet, 1) < 0) { // means we quit getting packets break; } pts = 0; // Save global pts to be stored in pFrame in first call global_video_pkt_pts = packet->pts; // Decode video frame len1 = avcodec_decode_video(is->video_st->codec, pFrame, &frameFinished, packet->data, packet->size); if(packet->dts == AV_NOPTS_VALUE && pFrame->opaque && *(uint64_t*)pFrame->opaque != AV_NOPTS_VALUE) { pts = *(uint64_t *)pFrame->opaque; } else if(packet->dts != AV_NOPTS_VALUE) { pts = packet->dts; } else { pts = 0; } pts *= av_q2d(is->video_st->time_base); // Did we get a video frame? if(frameFinished) { pts = synchronize_video(is, pFrame, pts); if(queue_picture(is, pFrame, pts) < 0) { break; } } av_free_packet(packet); } av_free(pFrame); return 0; } int stream_component_open(VideoState *is, int stream_index) { AVFormatContext *pFormatCtx = is->pFormatCtx; AVCodecContext *codecCtx; AVCodec *codec; SDL_AudioSpec wanted_spec, spec; if(stream_index < 0 || stream_index >= pFormatCtx->nb_streams) { return -1; } // Get a pointer to the codec context for the video stream codecCtx = pFormatCtx->streams[stream_index]->codec; if(codecCtx->codec_type == CODEC_TYPE_AUDIO) { // Set audio settings from codec info wanted_spec.freq = codecCtx->sample_rate; wanted_spec.format = AUDIO_S16SYS; wanted_spec.channels = codecCtx->channels; wanted_spec.silence = 0; wanted_spec.samples = SDL_AUDIO_BUFFER_SIZE; wanted_spec.callback = audio_callback; wanted_spec.userdata = is; if(SDL_OpenAudio(&wanted_spec, &spec) < 0) { fprintf(stderr, "SDL_OpenAudio: %s\n", SDL_GetError()); return -1; } is->audio_hw_buf_size = spec.size; } codec = avcodec_find_decoder(codecCtx->codec_id); if(!codec || (avcodec_open(codecCtx, codec) < 0)) { fprintf(stderr, "Unsupported codec!\n"); return -1; } switch(codecCtx->codec_type) { case CODEC_TYPE_AUDIO: is->audioStream = stream_index; is->audio_st = pFormatCtx->streams[stream_index]; is->audio_buf_size = 0; is->audio_buf_index = 0; /* averaging filter for audio sync */ is->audio_diff_avg_coef = exp(log(0.01 / AUDIO_DIFF_AVG_NB)); is->audio_diff_avg_count = 0; /* Correct audio only if larger error than this */ is->audio_diff_threshold = 2.0 * SDL_AUDIO_BUFFER_SIZE / codecCtx->sample_rate; memset(&is->audio_pkt, 0, sizeof(is->audio_pkt)); packet_queue_init(&is->audioq); SDL_PauseAudio(0); break; case CODEC_TYPE_VIDEO: is->videoStream = stream_index; is->video_st = pFormatCtx->streams[stream_index]; is->frame_timer = (double)av_gettime() / 1000000.0; is->frame_last_delay = 40e-3; is->video_current_pts_time = av_gettime(); packet_queue_init(&is->videoq); is->video_tid = SDL_CreateThread(video_thread, is); codecCtx->get_buffer = our_get_buffer; codecCtx->release_buffer = our_release_buffer; break; default: break; } } int decode_interrupt_cb(void) { return (global_video_state && global_video_state->quit); } int decode_thread(void *arg) { VideoState *is = (VideoState *)arg; AVFormatContext *pFormatCtx; AVPacket pkt1, *packet = &pkt1; int video_index = -1; int audio_index = -1; int i; is->videoStream=-1; is->audioStream=-1; global_video_state = is; // will interrupt blocking functions if we quit! url_set_interrupt_cb(decode_interrupt_cb); // Open video file if(av_open_input_file(&pFormatCtx, is->filename, NULL, 0, NULL)!=0) return -1; // Couldn't open file is->pFormatCtx = pFormatCtx; // Retrieve stream information if(av_find_stream_info(pFormatCtx)<0) return -1; // Couldn't find stream information // Dump information about file onto standard error dump_format(pFormatCtx, 0, is->filename, 0); // Find the first video stream for(i=0; i<pFormatCtx->nb_streams; i++) { if(pFormatCtx->streams[i]->codec->codec_type==CODEC_TYPE_VIDEO && video_index < 0) { video_index=i; } if(pFormatCtx->streams[i]->codec->codec_type==CODEC_TYPE_AUDIO && audio_index < 0) { audio_index=i; } } if(audio_index >= 0) { stream_component_open(is, audio_index); } if(video_index >= 0) { stream_component_open(is, video_index); } if(is->videoStream < 0 || is->audioStream < 0) { fprintf(stderr, "%s: could not open codecs\n", is->filename); goto fail; } // main decode loop for(;;) { if(is->quit) { break; } // seek stuff goes here if(is->audioq.size > MAX_AUDIOQ_SIZE || is->videoq.size > MAX_VIDEOQ_SIZE) { SDL_Delay(10); continue; } if(av_read_frame(is->pFormatCtx, packet) < 0) { if(url_ferror(&pFormatCtx->pb) == 0) { SDL_Delay(100); /* no error; wait for user input */ continue; } else { break; } } // Is this a packet from the video stream? if(packet->stream_index == is->videoStream) { packet_queue_put(&is->videoq, packet); } else if(packet->stream_index == is->audioStream) { packet_queue_put(&is->audioq, packet); } else { av_free_packet(packet); } } /* all done - wait for it */ while(!is->quit) { SDL_Delay(100); } fail: { SDL_Event event; event.type = FF_QUIT_EVENT; event.user.data1 = is; SDL_PushEvent(&event); } return 0; } int main(int argc, char *argv[]) { SDL_Event event; VideoState *is; is = av_mallocz(sizeof(VideoState)); if(argc < 2) { fprintf(stderr, "Usage: test <file>\n"); exit(1); } // Register all formats and codecs av_register_all(); if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER)) { fprintf(stderr, "Could not initialize SDL - %s\n", SDL_GetError()); exit(1); } // Make a screen to put our video #ifndef __DARWIN__ screen = SDL_SetVideoMode(640, 480, 0, 0); #else screen = SDL_SetVideoMode(640, 480, 24, 0); #endif if(!screen) { fprintf(stderr, "SDL: could not set video mode - exiting\n"); exit(1); } pstrcpy(is->filename, sizeof(is->filename), argv[1]); is->pictq_mutex = SDL_CreateMutex(); is->pictq_cond = SDL_CreateCond(); schedule_refresh(is, 40); is->av_sync_type = DEFAULT_AV_SYNC_TYPE; is->parse_tid = SDL_CreateThread(decode_thread, is); if(!is->parse_tid) { av_free(is); return -1; } for(;;) { SDL_WaitEvent(&event); switch(event.type) { case FF_QUIT_EVENT: case SDL_QUIT: is->quit = 1; SDL_Quit(); exit(0); break; case FF_ALLOC_EVENT: alloc_picture(event.user.data1); break; case FF_REFRESH_EVENT: video_refresh_timer(event.user.data1); break; default: break; } } return 0; }
lopesivan/ffmpeg-with-c-and-cpp
tutorial/ffmpegtutorial/tutorial06.c
C
gpl-3.0
24,098
/* RetroArch - A frontend for libretro. * Copyright (C) 2010-2014 - Hans-Kristian Arntzen * Copyright (C) 2011-2017 - Daniel De Matteis * Copyright (C) 2016-2019 - Brad Parker * * RetroArch 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 Found- * ation, either version 3 of the License, or (at your option) any later version. * * RetroArch 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 RetroArch. * If not, see <http://www.gnu.org/licenses/>. */ /* SIXEL context. */ #ifdef HAVE_CONFIG_H #include "../../config.h" #endif #include "../../configuration.h" #include "../../dynamic.h" #include "../../retroarch.h" #include "../../verbosity.h" #include "../../ui/ui_companion_driver.h" #if defined(_WIN32) && !defined(_XBOX) #include "../common/win32_common.h" #endif static enum gfx_ctx_api sixel_ctx_api = GFX_CTX_NONE; static void gfx_ctx_sixel_check_window(void *data, bool *quit, bool *resize, unsigned *width, unsigned *height, bool is_shutdown) { } static bool gfx_ctx_sixel_set_resize(void *data, unsigned width, unsigned height) { (void)data; (void)width; (void)height; return false; } static void gfx_ctx_sixel_update_window_title(void *data, void *data2) { const settings_t *settings = config_get_ptr(); video_frame_info_t *video_info = (video_frame_info_t*)data2; #if defined(_WIN32) && !defined(_XBOX) const ui_window_t *window = ui_companion_driver_get_window_ptr(); char title[128]; title[0] = '\0'; if (settings->bools.video_memory_show) { uint64_t mem_bytes_used = frontend_driver_get_used_memory(); uint64_t mem_bytes_total = frontend_driver_get_total_memory(); char mem[128]; mem[0] = '\0'; snprintf( mem, sizeof(mem), " || MEM: %.2f/%.2fMB", mem_bytes_used / (1024.0f * 1024.0f), mem_bytes_total / (1024.0f * 1024.0f)); strlcat(video_info->fps_text, mem, sizeof(video_info->fps_text)); } video_driver_get_window_title(title, sizeof(title)); if (window && title[0]) window->set_title(&main_window, title); #endif } static void gfx_ctx_sixel_get_video_size(void *data, unsigned *width, unsigned *height) { (void)data; } static void *gfx_ctx_sixel_init( video_frame_info_t *video_info, void *video_driver) { (void)video_driver; return (void*)"sixel"; } static void gfx_ctx_sixel_destroy(void *data) { (void)data; } static bool gfx_ctx_sixel_set_video_mode(void *data, video_frame_info_t *video_info, unsigned width, unsigned height, bool fullscreen) { return true; } static void gfx_ctx_sixel_input_driver(void *data, const char *joypad_name, input_driver_t **input, void **input_data) { (void)data; #ifdef HAVE_UDEV *input_data = input_udev.init(joypad_name); if (*input_data) { *input = &input_udev; return; } #endif *input = NULL; *input_data = NULL; } static bool gfx_ctx_sixel_has_focus(void *data) { return true; } static bool gfx_ctx_sixel_suppress_screensaver(void *data, bool enable) { return true; } static bool gfx_ctx_sixel_get_metrics(void *data, enum display_metric_types type, float *value) { return false; } static enum gfx_ctx_api gfx_ctx_sixel_get_api(void *data) { return sixel_ctx_api; } static bool gfx_ctx_sixel_bind_api(void *data, enum gfx_ctx_api api, unsigned major, unsigned minor) { (void)data; return true; } static void gfx_ctx_sixel_show_mouse(void *data, bool state) { (void)data; } static void gfx_ctx_sixel_swap_interval(void *data, int interval) { (void)data; (void)interval; } static void gfx_ctx_sixel_set_flags(void *data, uint32_t flags) { (void)data; (void)flags; } static uint32_t gfx_ctx_sixel_get_flags(void *data) { uint32_t flags = 0; return flags; } static void gfx_ctx_sixel_swap_buffers(void *data, void *data2) { (void)data; } const gfx_ctx_driver_t gfx_ctx_sixel = { gfx_ctx_sixel_init, gfx_ctx_sixel_destroy, gfx_ctx_sixel_get_api, gfx_ctx_sixel_bind_api, gfx_ctx_sixel_swap_interval, gfx_ctx_sixel_set_video_mode, gfx_ctx_sixel_get_video_size, NULL, /* get_refresh_rate */ NULL, /* get_video_output_size */ NULL, /* get_video_output_prev */ NULL, /* get_video_output_next */ gfx_ctx_sixel_get_metrics, NULL, gfx_ctx_sixel_update_window_title, gfx_ctx_sixel_check_window, gfx_ctx_sixel_set_resize, gfx_ctx_sixel_has_focus, gfx_ctx_sixel_suppress_screensaver, true, /* has_windowed */ gfx_ctx_sixel_swap_buffers, gfx_ctx_sixel_input_driver, NULL, NULL, NULL, gfx_ctx_sixel_show_mouse, "sixel", gfx_ctx_sixel_get_flags, gfx_ctx_sixel_set_flags, NULL, NULL, NULL };
RobLoach/RetroArch
gfx/drivers_context/sixel_ctx.c
C
gpl-3.0
5,106
/* * Vortex OpenSplice * * This software and documentation are Copyright 2006 to TO_YEAR ADLINK * Technology Limited, its affiliated companies and licensors. All rights * reserved. * * Licensed under the ADLINK Software License Agreement Rev 2.7 2nd October * 2014 (the "License"); you may not use this file except in compliance with * the License. * You may obtain a copy of the License at: * $OSPL_HOME/LICENSE * * See the License for the specific language governing permissions and * limitations under the License. * */ /** \file os/linux/code/os_time.c * \brief Linux time management * * Implements time management for Linux * by including the generic Linux implementation */ #include "../linux/code/os_time.c"
PrismTech/opensplice
src/abstraction/os/lynxos5/code/os_time.c
C
gpl-3.0
802
/* Copyright (c) 2008, 2009 * Juergen Weigert (jnweiger@immd4.informatik.uni-erlangen.de) * Michael Schroeder (mlschroe@immd4.informatik.uni-erlangen.de) * Micah Cowan (micah@cowan.name) * Sadrul Habib Chowdhury (sadrul@users.sourceforge.net) * Copyright (c) 1993-2002, 2003, 2005, 2006, 2007 * Juergen Weigert (jnweiger@immd4.informatik.uni-erlangen.de) * Michael Schroeder (mlschroe@immd4.informatik.uni-erlangen.de) * Copyright (c) 1987 Oliver Laumann * * 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 3, or (at your option) * any later version. * * This program 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 this program (see the file COPYING); if not, see * http://www.gnu.org/licenses/, or contact Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02111-1301 USA * **************************************************************** */ #include <sys/types.h> #include <sys/socket.h> #include <fcntl.h> #include <netdb.h> #include <stdio.h> #include "config.h" #ifdef BUILTIN_TELNET #include "screen.h" extern Window *fore; extern Layer *flayer; extern int visual_bell; extern char screenterm[]; extern int af; static void TelReply(Window *, char *, int); static void TelDocmd(Window *, int, int); static void TelDosub(Window *); // why TEL_DEFPORT has " #define TEL_DEFPORT "23" #define TEL_CONNECTING (-2) #define TC_IAC 255 #define TC_DONT 254 #define TC_DO 253 #define TC_WONT 252 #define TC_WILL 251 #define TC_SB 250 #define TC_BREAK 243 #define TC_SE 240 #define TC_S "S b swWdDc" #define TO_BINARY 0 #define TO_ECHO 1 #define TO_SGA 3 #define TO_TM 6 #define TO_TTYPE 24 #define TO_NAWS 31 #define TO_TSPEED 32 #define TO_LFLOW 33 #define TO_LINEMODE 34 #define TO_XDISPLOC 35 #define TO_NEWENV 39 #define TO_S "be c t wsf xE E" static unsigned char tn_init[] = { TC_IAC, TC_DO, TO_SGA, TC_IAC, TC_WILL, TO_TTYPE, TC_IAC, TC_WILL, TO_NAWS, TC_IAC, TC_WILL, TO_LFLOW, }; static void tel_connev_fn(Event *ev, char *data) { Window *p = (Window *)data; if (connect(p->w_ptyfd, (struct sockaddr *)&p->w_telsa, sizeof(p->w_telsa)) && errno != EISCONN) { char buf[1024]; buf[0] = ' '; strncpy(buf + 1, strerror(errno), sizeof(buf) - 2); buf[sizeof(buf) - 1] = 0; WriteString(p, buf, strlen(buf)); WindowDied(p, 0, 0); return; } WriteString(p, "connected.\r\n", 12); evdeq(&p->w_telconnev); p->w_telstate = 0; } int TelOpenAndConnect(Window *p) { int fd, on = 1; char buf[256]; struct addrinfo hints, *res0, *res; if (!(p->w_cmdargs[1])) { Msg(0, "Usage: screen //telnet host [port]"); return -1; } memset(&hints, 0, sizeof(hints)); hints.ai_family = af; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; if (getaddrinfo(p->w_cmdargs[1], p->w_cmdargs[2] ? p->w_cmdargs[2] : TEL_DEFPORT, &hints, &res0)) { Msg(0, "unknown host: %s", p->w_cmdargs[1]); return -1; } for (res = res0; res; res = res->ai_next) { if ((fd = socket(res->ai_family, res->ai_socktype, res->ai_protocol)) == -1) { if (res->ai_next) continue; else { Msg(errno, "TelOpenAndConnect: socket"); freeaddrinfo(res0); return -1; } } if (setsockopt(fd, SOL_SOCKET, SO_OOBINLINE, (char *)&on, sizeof(on))) Msg(errno, "TelOpenAndConnect: setsockopt SO_OOBINLINE"); if (p->w_cmdargs[2] && strcmp(p->w_cmdargs[2], TEL_DEFPORT)) snprintf(buf, 256, "Trying %s %s...", p->w_cmdargs[1], p->w_cmdargs[2]); else snprintf(buf, 256, "Trying %s...", p->w_cmdargs[1]); WriteString(p, buf, strlen(buf)); if (connect(fd, res->ai_addr, res->ai_addrlen)) { if (errno == EINPROGRESS) { p->w_telstate = TEL_CONNECTING; p->w_telconnev.fd = fd; p->w_telconnev.handler = tel_connev_fn; p->w_telconnev.data = (char *)p; p->w_telconnev.type = EV_WRITE; p->w_telconnev.priority = 1; evenq(&p->w_telconnev); } else { close(fd); if (res->ai_next) continue; else { Msg(errno, "TelOpenAndConnect: connect"); freeaddrinfo(res0); return -1; } } } else WriteString(p, "connected.\r\n", 12); if (!(p->w_cmdargs[2] && strcmp(p->w_cmdargs[2], TEL_DEFPORT))) TelReply(p, (char *)tn_init, sizeof(tn_init)); p->w_ptyfd = fd; memcpy(&p->w_telsa, &res->ai_addr, sizeof(res->ai_addr)); freeaddrinfo(res0); return 0; } return -1; } int TelIsline(Window *p) { return !fore->w_telropts[TO_SGA]; } void TelProcessLine(char **bufpp, int *lenp) { int echo = !fore->w_telropts[TO_ECHO]; unsigned char c; char *tb; int tl; char *buf = *bufpp; int l = *lenp; while (l--) { c = *(unsigned char *)buf++; if (fore->w_telbufl + 2 >= IOSIZE) { WBell(fore, visual_bell); continue; } if (c == '\r') { if (echo) WriteString(fore, "\r\n", 2); fore->w_telbuf[fore->w_telbufl++] = '\r'; fore->w_telbuf[fore->w_telbufl++] = '\n'; tb = fore->w_telbuf; tl = fore->w_telbufl; LayProcess(&tb, &tl); fore->w_telbufl = 0; continue; } if (c == '\b' && fore->w_telbufl > 0) { if (echo) { WriteString(fore, (char *)&c, 1); WriteString(fore, " ", 1); WriteString(fore, (char *)&c, 1); } fore->w_telbufl--; } if ((c >= 0x20 && c <= 0x7e) || c >= 0xa0) { if (echo) WriteString(fore, (char *)&c, 1); fore->w_telbuf[fore->w_telbufl++] = c; } } *lenp = 0; } int DoTelnet(char *buf, int *lenp, int f) { int echo = !fore->w_telropts[TO_ECHO]; int cmode = fore->w_telropts[TO_SGA]; int bin = fore->w_telropts[TO_BINARY]; char *p = buf, *sbuf; int trunc = 0; int c; int l = *lenp; sbuf = p; while (l-- > 0) { c = *(unsigned char *)p++; if (c == TC_IAC || (c == '\r' && (l == 0 || *p != '\n') && cmode && !bin)) { if (cmode && echo) { WriteString(fore, sbuf, p - sbuf); sbuf = p; } if (f-- <= 0) { trunc++; l--; } if (l < 0) { p--; /* drop char */ break; } if (l) bcopy(p, p + 1, l); if (c == TC_IAC) *p++ = c; else if (c == '\r') *p++ = 0; else if (c == '\n') { p[-1] = '\r'; *p++ = '\n'; } } } *lenp = p - buf; return trunc; } /* modifies data in-place, returns new length */ int TelIn(Window *p, char *buf, int len, int free) { char *rp, *wp; int c; rp = wp = buf; while (len-- > 0) { c = *(unsigned char *)rp++; if (p->w_telstate >= TC_WILL && p->w_telstate <= TC_DONT) { TelDocmd(p, p->w_telstate, c); p->w_telstate = 0; continue; } if (p->w_telstate == TC_SB || p->w_telstate == TC_SE) { if (p->w_telstate == TC_SE && c == TC_IAC) p->w_telsubidx--; if (p->w_telstate == TC_SE && c == TC_SE) { p->w_telsubidx--; TelDosub(p); p->w_telstate = 0; continue; } if (p->w_telstate == TC_SB && c == TC_IAC) p->w_telstate = TC_SE; else p->w_telstate = TC_SB; p->w_telsubbuf[p->w_telsubidx] = c; if (p->w_telsubidx < sizeof(p->w_telsubbuf) - 1) p->w_telsubidx++; continue; } if (p->w_telstate == TC_IAC) { if ((c >= TC_WILL && c <= TC_DONT) || c == TC_SB) { p->w_telsubidx = 0; p->w_telstate = c; continue; } p->w_telstate = 0; if (c != TC_IAC) continue; } else if (c == TC_IAC) { p->w_telstate = c; continue; } if (p->w_telstate == '\r') { p->w_telstate = 0; if (c == 0) continue; /* suppress trailing \0 */ } else if (c == '\n' && !p->w_telropts[TO_SGA]) { /* oops... simulate terminal line mode: insert \r */ if (wp + 1 == rp) { if (free-- > 0) { if (len) bcopy(rp, rp + 1, len); rp++; *wp++ = '\r'; } } else *wp++ = '\r'; } if (c == '\r') p->w_telstate = c; *wp++ = c; } return wp - buf; } static void TelReply(Window *p, char *str, int len) { if (len <= 0) return; if (p->w_inlen + len > IOSIZE) { Msg(0, "Warning: telnet protocol overrun!"); return; } bcopy(str, p->w_inbuf + p->w_inlen, len); p->w_inlen += len; } static void TelDocmd(Window *p, int cmd, int opt) { unsigned char b[3]; int repl = 0; switch (cmd) { case TC_WILL: if (p->w_telropts[opt] || opt == TO_TM) return; repl = TC_DONT; if (opt == TO_ECHO || opt == TO_SGA || opt == TO_BINARY) { p->w_telropts[opt] = 1; /* setcon(); */ repl = TC_DO; } break; case TC_WONT: if (!p->w_telropts[opt] || opt == TO_TM) return; repl = TC_DONT; p->w_telropts[opt] = 0; break; case TC_DO: if (p->w_telmopts[opt]) return; repl = TC_WONT; if (opt == TO_TTYPE || opt == TO_SGA || opt == TO_BINARY || opt == TO_NAWS || opt == TO_TM || opt == TO_LFLOW) { repl = TC_WILL; p->w_telmopts[opt] = 1; } p->w_telmopts[TO_TM] = 0; break; case TC_DONT: if (!p->w_telmopts[opt]) return; repl = TC_WONT; p->w_telmopts[opt] = 0; break; } b[0] = TC_IAC; b[1] = repl; b[2] = opt; TelReply(p, (char *)b, 3); if (cmd == TC_DO && opt == TO_NAWS) TelWindowSize(p); } static void TelDosub(Window *p) { char trepl[20 + 6 + 1]; int l; switch (p->w_telsubbuf[0]) { case TO_TTYPE: if (p->w_telsubidx != 2 || p->w_telsubbuf[1] != 1) return; l = strlen(screenterm); if (l >= 20) break; sprintf(trepl, "%c%c%c%c%s%c%c", TC_IAC, TC_SB, TO_TTYPE, 0, screenterm, TC_IAC, TC_SE); TelReply(p, trepl, l + 6); break; case TO_LFLOW: if (p->w_telsubidx != 2) return; break; default: break; } } void TelBreak(Window *p) { static unsigned char tel_break[] = { TC_IAC, TC_BREAK }; TelReply(p, (char *)tel_break, 2); } void TelWindowSize(Window *p) { char s[20], trepl[20], *t; int i; if (p->w_width == 0 || p->w_height == 0 || !p->w_telmopts[TO_NAWS]) return; sprintf(s, "%c%c%c%c%c%c%c%c%c", TC_SB, TC_SB, TO_NAWS, p->w_width / 256, p->w_width & 255, p->w_height / 256, p->w_height & 255, TC_SE, TC_SE); t = trepl; for (i = 0; i < 9; i++) if ((unsigned char)(*t++ = s[i]) == TC_IAC) *t++ = TC_IAC; trepl[0] = TC_IAC; t[-2] = TC_IAC; TelReply(p, trepl, t - trepl); } static char tc_s[] = TC_S; static char to_s[] = TO_S; void TelStatus(Window *p, char *buf, int l) { int i; *buf++ = '['; for (i = 0; to_s[i]; i++) { if (to_s[i] == ' ' || p->w_telmopts[i] == 0) continue; *buf++ = to_s[i]; } *buf++ = ':'; for (i = 0; to_s[i]; i++) { if (to_s[i] == ' ' || p->w_telropts[i] == 0) continue; *buf++ = to_s[i]; } if (p->w_telstate == TEL_CONNECTING) buf[-1] = 'C'; else if (p->w_telstate && p->w_telstate != '\r') { *buf++ = ':'; *buf++ = tc_s[p->w_telstate - TC_SE]; } *buf++ = ']'; *buf = 0; return; } #endif /* BUILTIN_TELNET */
maire/screen
src/teln.c
C
gpl-3.0
11,094
/* str*()-like functions for raw memory "lines" (non-NUL terminated strings). * * Especially when we're parsing input in an ESL_BUFFER, we need to be * able to parse non-writable raw memory buffers. Because an * ESL_BUFFER may have memory mapped a file, we cannot assume that the * input is NUL-terminated, and we can't even assume it's writable (so * we can't NUL-terminate it ourselves). These functions provide * a set of utilities for parsing raw memory (in terms of a char * pointer * and a length in bytes; <char *p>, <esl_pos_t n> by convention). * * Contents: * 1. The esl_mem*() API. * 2. Unit tests. * 3. Test driver. * 4. Copyright and license. */ #include "esl_config.h" #include <string.h> #include <ctype.h> #include "easel.h" /***************************************************************** *# 1. The esl_mem*() API. *****************************************************************/ /* Function: esl_mem_strtoi32() * Synopsis: Convert a chunk of text memory to an int32_t. * * Purpose: Convert the text starting at <p> to an <int32_t>, converting * no more than <n> characters (the valid length of non-<NUL> * terminated memory buffer <p>). Interpret the text as * base <base> (2 or 10, for example). <base> must be 2..36, * or 0. 0 is treated specially as base 8, 10, or 16, autodetected * according to the leading characters of the number format. * * Any leading whitespace is skipped. The next letter may * be a '-' for a negative number. If <base> is 0 or 16, * the next two characters may be "0x", in which case hex base * 16 is assumed. Else if <base> is 0 and the next * character is '0', octal base 8 is assumed. All subsequent * characters are converted to a number, until an invalid * character is reached. Upper or lower case letters are * accepted, starting at A or a, for bases over 10. For * example, In base 16, characters A-F or a-f are accepted. * The base of the representation is limited to 36 because * 'Z' or 'z' represents 35. * * The converted value is optionally returned in <*opt_val>. * The number of characters parsed (up to the first invalid * character, or <n>, whichever comes first) is optionally * returned in <*opt_nc>. The caller can reposition a parser * to <p + *opt_nc> to exactly skip past the parsed number. * * If no valid digit is found (including pathological cases * of leader-only, such as "0x" or "-"), then return <eslEINVAL>, * and <*opt_nc> and <*opt_val> are both 0. * * This syntax is essentially identical to <strtol()>, * except that we can operate on a non-NUL-terminated * memory buffer of maximum length <n>, rather than on a * NUL-terminated string. * * Args: p - pointer to text buffer to convert to int32_t * n - maximum number of chars to parse in <p>: p[0..n-1] are valid. * base - integer base. Often 10, 2, 8, or 16. Must be * <2..36>, or 0. 0 means base 8, 10, or 16 depending on * autodetected format. * *opt_nc - optRETURN: number of valid chars parsed from p. * First invalid char is p[*opt_nc]. * *opt_val - optRETURN: parsed value. * * Returns: <eslOK> on success. * * <eslEFORMAT> if no valid integer digits are found. Now * <*opt_val> and <*opt_nc> are 0. * * <eslERANGE> on an overflow error. In this case * <*opt_val> is <INT32_MAX> or <INT32_MIN> for an * overflow or underflow, respectively. <*opt_nc> is * set to the number of characters parsed INCLUDING * the digit that caused the overflow. * * Throws: <eslEINVAL> if <base> isn't in range <0..36>. Now * <*opt_nc> and <*opt_val> are 0. * * Note: An example of why you need this instead of * strtol(): suppose you've mmap()'ed a file to memory, * and it ends in ... "12345". You can't strtol the * end of the mmap'ed memory buffer because it is not * a NUL-terminated string. (Same goes anywhere in the file, * though elsewhere in the file you could overwrite * a NUL where you need it. At EOF of an mmap'ed() buffer, * you can't even do that.) * * sscanf() doesn't work either - I don't see a way to * limit it to a buffer of at most <n> chars. * * I could copy <p> to a temporary allocated string that I * NUL-terminate, then use strtol() or suchlike, but that's * just as awful as what I've done here (rewriting * strtol()). Plus, here I get complete control of the integer * type (<int32_t>) whereas strtol() gives me the less satisfying * <long>. */ int esl_mem_strtoi32(char *p, esl_pos_t n, int base, int *opt_nc, int32_t *opt_val) { esl_pos_t i = 0; int32_t sign = 1; int32_t currval = 0; int32_t digit = 0; int ndigits = 0; if (base < 0 || base == 1 || base > 36) ESL_EXCEPTION(eslEINVAL, "base must be 2..36 or 0"); while (i < n && isspace(p[i])) i++; /* skip leading whitespace */ if (i < n && p[i] == '-') { sign = -1; i++; } if ((base == 0 || base == 16) && i < n-1 && p[i] == '0' && p[i+1] == 'x') { i += 2; base = 16; } else if (base == 0 && i < n && p[i] == '0') { i += 1; base = 8; } else if (base == 0) { base = 10; } for (ndigits = 0; i < n; i++, ndigits++) { if (isdigit(p[i])) digit = p[i] - '0'; else if (isupper(p[i])) digit = 10 + (p[i] - 'A'); else if (islower(p[i])) digit = 10 + (p[i] - 'a'); else break; if (digit >= base) break; if (sign == 1) { if (currval > (INT32_MAX - digit) / base) { if (opt_val) *opt_val = INT32_MAX; if (opt_nc) *opt_nc = i+1; return eslERANGE; } currval = currval * base + digit; } else { if (currval < (INT32_MIN + digit) / base) { if (opt_val) *opt_val = INT32_MIN; if (opt_nc) *opt_nc = i+1; return eslERANGE; } currval = currval * base - digit; } } if (opt_nc) { *opt_nc = (ndigits ? i : 0); } if (opt_val) { *opt_val = currval; } return (ndigits ? eslOK : eslEFORMAT); } /* Function: esl_memnewline() * Synopsis: Find next newline in memory. * * Purpose: Given a memory buffer <*m> of <n> bytes, delimit a * next line by finding the next newline character(s). * Store the number of bytes in the line (exclusive of * the newline character(s)) in <*ret_nline>. Store * the number of bytes in the newline in <*ret_nterm>. * * If no newline is found, <nline=n> and <nterm=0>, and the * return status is <eslEOD>. * * Currently we assume newlines are either UNIX-style \verb+\n+ * or Windows-style \verb+\r\n+, in this implementation. * * Caller should not rely on this, though. Caller may only * assume that a newline is an arbitrary one- or two-byte * code. * * For example, if <*m> = \verb+"line one\r\nline two"+, <nline> * is 8 and <nterm> is 2. If <*m> = \verb+"try two\ntry three"+, * <nline> is 7 and <nterm> is 1. If <*m> = "attempt * four", <nline> is 12 and <nterm> is 0. * * In cases where the caller may have an incompletely read * buffer, it should be careful of cases where one possible * newline may be a prefix of another; for example, suppose * a file has \verb+"line one\r\nline two"+, but we only input the * buffer \verb+"line one\r"+ at first. The \verb+"\r"+ looks like an old * MacOS newline. Now we read more input, and we think the * buffer is \verb+"\nline two"+. Now we think the \verb+"\n"+ is a UNIX * newline. The result is that we read two newlines where * there's only one. Instead, caller should check for the * case of nterm==1 at the end of its buffer, and try to * extend the buffer. See <esl_buffer_GetLine()> for an * example. * * Args: m - ptr to memory buffer * n - length of p in bytes * *ret_nline - length of line found starting at p[0], exclusive of newline; up to n * *ret_nterm - # of bytes in newline code: 1 or 2, or 0 if no newline found * * Returns: <eslOK> on success. Now <*ret_nline> is the number of * bytes in the next line (exclusive of newline) and * <*ret_nterm> is the number of bytes in the newline code * (1 or 2). Thus the next line is <m[0..nline-1]>, and * the line after this starts at <m[nline+nterm]>. * * <eslEOD> if no newline is found. Now <*ret_nline> is <n>, * and <*ret_nterm> is 0. * * Xref: http://en.wikipedia.org/wiki/Newline */ int esl_memnewline(const char *m, esl_pos_t n, esl_pos_t *ret_nline, int *ret_nterm) { char *ptr = memchr(m, '\n', n); if (ptr == NULL) { *ret_nline = n; *ret_nterm = 0; } else if (ptr > m && *(ptr-1) == '\r') { *ret_nline = ptr-m-1; *ret_nterm = 2; } else { *ret_nline = ptr-m; *ret_nterm = 1; } return eslOK; } /* Function: esl_memtok() * Synopsis: Get next delimited token from a line. * * Purpose: Given references to a line and its length, <*p> and <*n>, * find the next token delimited by any of the characters * in the string <delim>. Set <*ret_tok> to point at the * start of the token, and <*ret_toklen> to its length. * Increment <*p> to point to the next non-delim character * that follows, and decrement <*n> by the same, * so that <*p> and <*n> are ready for another * call to <esl_memtok()>. * * Three differences between <esl_strtok()> and <esl_memtok()>: * first, <esl_strtok()> expects a NUL-terminated string, * whereas <esl_memtok()>'s line does not need to be * NUL-terminated; second, <esl_memtok()> does not modify * the string, whereas <esl_strtok()> writes NUL bytes * to delimit tokens; third, <esl_memtok()> skips trailing * <delim> characters as well as leading ones. * * Args: *p - pointer to line; * will be incremented to next byte after token. * *n - pointer to line length, in bytes; * will be decremented * delim - delimiter chars (example: " \t\r\n") * *ret_tok - RETURN: ptr to token found in <*p> * *ret_toklen - RETURN: length of token * * Returns: <eslOK> if a delimited token is found. * <eslEOL> if not; now <*ret_tok> is <NULL> and <*ret_toklen> is <0>. * */ int esl_memtok(char **p, esl_pos_t *n, const char *delim, char **ret_tok, esl_pos_t *ret_toklen) { char *s = *p; esl_pos_t so, xo, eo; for (so = 0; so < *n; so++) if (strchr(delim, s[so]) == NULL) break; for (xo = so; xo < *n; xo++) if (strchr(delim, s[xo]) != NULL) break; for (eo = xo; eo < *n; eo++) if (strchr(delim, s[eo]) == NULL) break; if (so == *n) { *ret_tok = NULL; *ret_toklen = 0; return eslEOL; } else { *p += eo; *n -= eo; *ret_tok = s + so; *ret_toklen = xo - so; return eslOK; } } /* Function: esl_memspn() * Synopsis: Finds length of prefix consisting only of given chars * * Purpose: For line <p> of length <n>, return the length of * a prefix that consists only of characters in the * string <allow>. * * A commonly used idiom for "buffer is all whitespace" * is <esl_memspn(p, n, " \t\r\n") == n>. */ esl_pos_t esl_memspn(char *p, esl_pos_t n, const char *allow) { esl_pos_t so; for (so = 0; so < n; so++) if (strchr(allow, p[so]) == NULL) break; return so; } /* Function: esl_memcspn() * Synopsis: Finds length of prefix consisting of anything other than given chars * * Purpose: For line <p> of length <n>, return the length of * a prefix that consists only of characters NOT in the * string <disallow>. */ esl_pos_t esl_memcspn(char *p, esl_pos_t n, const char *disallow) { esl_pos_t so; for (so = 0; so < n; so++) if (strchr(disallow, p[so]) != NULL) break; return so; } /* Function: esl_memstrcmp() * Synopsis: Compare a memory line and string for equality. * * Purpose: Compare line <p> of length <n> to a NUL-terminated * string <s>, and return TRUE if they are exactly * equal: <strlen(s) == n> and <p[0..n-1] == s[0..n-1]>. * Else, return FALSE. */ int esl_memstrcmp(const char *p, esl_pos_t n, const char *s) { esl_pos_t pos; if (p == NULL && n == 0 && (s == NULL || s[0] == '\0')) return TRUE; if (!p || !s) return FALSE; for (pos = 0; pos < n && s[pos] != '\0'; pos++) if (p[pos] != s[pos]) return FALSE; if (pos != n) return FALSE; if (s[pos] != '\0') return FALSE; return TRUE; } /* Function: esl_memstrpfx() * Synopsis: Return TRUE if memory line starts with string. * * Purpose: Compare line <p> of length <n> to a NUL-terminated * string <s>. Return TRUE if the prefix of <p> exactly * matches <s> up to its NUL sentinel byte. Else, * return FALSE. */ int esl_memstrpfx(const char *p, esl_pos_t n, const char *s) { esl_pos_t pos; if (!p || !s) return FALSE; for (pos = 0; pos < n && s[pos] != '\0'; pos++) if (p[pos] != s[pos]) return FALSE; if (s[pos] != '\0') return FALSE; return TRUE; } /* Function: esl_memstrcontains() * Synopsis: Return TRUE if memory line matches a string. * * Purpose: Compare line <p> of length <n> to NUL-terminated * string <s>. Return <TRUE> if <p> contains an exact * match to <s> at any position. */ int esl_memstrcontains(const char *p, esl_pos_t n, const char *s) { esl_pos_t s0, pos; if (! p || ! s) return FALSE; for (s0 = 0; s0 < n; s0++) { for (pos = 0; s0+pos < n && s[pos] != '\0'; pos++) if (p[s0+pos] != s[pos]) break; if (s[pos] == '\0') return TRUE; } return FALSE; } /* Function: esl_memstrdup() * Synopsis: Duplicate a memory line as a NUL-terminated string. * * Purpose: Given memory line <p> of length <n>, duplicate it * as a NUL-terminated string; return the new string * in <*ret_s>. * * Returns: <eslOK> on success. * * Throws: <eslEMEM> on allocation failure; now <*ret_s> is <NULL>. */ int esl_memstrdup(const char *p, esl_pos_t n, char **ret_s) { char *s = NULL; int status; if (! p) { *ret_s = NULL; return eslOK; } ESL_ALLOC(s, sizeof(char) * (n+1)); memcpy(s, p, n); s[n] = '\0'; *ret_s = s; return eslOK; ERROR: *ret_s = NULL; return status; } /* Function: esl_memstrcpy() * Synopsis: Copy a memory line as a string. * * Purpose: Given memory line <p> of length <n>, copy * it to <dest> and NUL-terminate it. Caller must * be sure that <s> is already allocated for * at least <n+1> bytes. * * Returns: <eslOK> on success. */ int esl_memstrcpy(const char *p, esl_pos_t n, char *dest) { memcpy(dest, p, n); dest[n] = '\0'; return eslOK; } /* Function: esl_memtod() * Synopsis: esl_mem equivalent to strtod(). * * Purpose: Given a buffer <p> of length <n>, convert it to a * double-precision floating point value, just as * <strtod()> would do for a NUL-terminated string. * * Returns: <eslOK> on success, and <*ret_val> contains the * converted value. * * Throws: <eslEMEM> on allocation error, and <*ret_val> is 0. */ int esl_memtod(const char *p, esl_pos_t n, double *ret_val) { char fixedbuf[128]; char *bigbuf = NULL; int status; if (n < 128) { memcpy(fixedbuf, p, sizeof(char) * n); fixedbuf[n] = '\0'; *ret_val = strtod(fixedbuf, NULL); return eslOK; } else { ESL_ALLOC(bigbuf, sizeof(char) * (n+1)); memcpy(bigbuf, p, sizeof(char) * n); bigbuf[n] = '\0'; *ret_val = strtod(fixedbuf, NULL); free(bigbuf); return eslOK; } ERROR: *ret_val = 0.; return status; } /* Function: esl_memtof() * Synopsis: esl_mem equivalent to strtod(), for a float * * Purpose: Given a buffer <p> of length <n>, convert it to a * single-precision floating point value, just as * <strtod()> would do for a NUL-terminated string. * * Returns: <eslOK> on success, and <*ret_val> contains the * converted value. * * Throws: <eslEMEM> on allocation error, and <*ret_val> is 0. */ int esl_memtof(const char *p, esl_pos_t n, float *ret_val) { char fixedbuf[128]; char *bigbuf = NULL; int status; if (n < 128) { memcpy(fixedbuf, p, sizeof(char) * n); fixedbuf[n] = '\0'; *ret_val = (float) strtod(fixedbuf, NULL); return eslOK; } else { ESL_ALLOC(bigbuf, sizeof(char) * (n+1)); memcpy(bigbuf, p, sizeof(char) * n); bigbuf[n] = '\0'; *ret_val = (float) strtod(fixedbuf, NULL); free(bigbuf); return eslOK; } ERROR: *ret_val = 0.; return status; } /* Function: esl_mem_IsReal() * Synopsis: Return TRUE if <p> is a real number; else FALSE. * * Purpose: If the memory <p> of <n> bytes is convertible * to a floating point real number by the rules of * atof(), return TRUE; else return FALSE. * * Xref: easel.c::esl_str_IsReal() for string version. */ int esl_mem_IsReal(const char *p, esl_pos_t n) { int gotdecimal = 0; int gotexp = 0; int gotreal = 0; if (!p || !n) return FALSE; while (n && isspace((int) *p)) { p++; n--; } /* skip leading whitespace */ if (n && (*p == '-' || *p == '+')) { p++; n--; } /* skip leading sign */ /* Examine remainder for garbage. Allowed one '.' and * one 'e' or 'E'; if both '.' and e/E occur, '.' * must be first. */ while (n) { if (isdigit((int) (*p))) gotreal++; else if (*p == '.') { if (gotdecimal) return FALSE; /* can't have two */ if (gotexp) return FALSE; /* e/E preceded . */ else gotdecimal++; } else if (*p == 'e' || *p == 'E') { if (gotexp) return FALSE; /* can't have two */ else gotexp++; } else if (isspace((int) (*p))) break; p++; n--; } while (n && isspace((int) *p)) { p++; n--; } /* skip trailing whitespace */ return ( (n == 0 && gotreal) ? TRUE : FALSE); } /*----------------- end, esl_mem*() API ------------------------*/ /***************************************************************** * 2. Benchmark driver. *****************************************************************/ #ifdef eslMEM_BENCHMARK #include "esl_config.h" #include <stdio.h> #include "easel.h" #include "esl_buffer.h" #include "esl_getopts.h" #include "esl_stopwatch.h" static ESL_OPTIONS options[] = { /* name type default env range togs reqs incomp help docgrp */ {"-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show help and usage", 0}, { 0,0,0,0,0,0,0,0,0,0}, }; static char usage[] = "[-options] <infile>"; static char banner[] = "benchmark driver for mem module"; int main(int argc, char **argv) { ESL_GETOPTS *go = esl_getopts_CreateDefaultApp(options, 1, argc, argv, banner, usage); ESL_STOPWATCH *w = esl_stopwatch_Create(); char *infile = esl_opt_GetArg(go, 1); ESL_BUFFER *bf = NULL; int64_t nlines = 0; int64_t ntokens = 0; int64_t nchar = 0; char *p, *tok; esl_pos_t n, toklen; int status; esl_stopwatch_Start(w); if ( esl_buffer_Open(infile, NULL, &bf) != eslOK) esl_fatal("open failed"); while ( (status = esl_buffer_GetLine(bf, &p, &n)) == eslOK) { nlines++; while ( (status = esl_memtok(&p, &n, " \t", &tok, &toklen)) == eslOK) { ntokens++; nchar += toklen; } if (status != eslEOL) esl_fatal("memtok failure"); } if (status != eslEOF) esl_fatal("GetLine failure"); esl_stopwatch_Stop(w); esl_stopwatch_Display(stdout, w, NULL); printf("lines = %" PRId64 "\n", nlines); printf("tokens = %" PRId64 "\n", ntokens); printf("chars = %" PRId64 "\n", nchar); esl_buffer_Close(bf); esl_stopwatch_Destroy(w); esl_getopts_Destroy(go); return 0; } #endif /*eslMEM_BENCHMARK*/ /*---------------- end, benchmark driver ------------------------*/ /***************************************************************** * 2. Unit tests *****************************************************************/ #ifdef eslMEM_TESTDRIVE static void utest_mem_strtoi32(void) { char msg[] = "esl_mem_strtoi32() unit test failed"; int nc; int32_t val; int status; if ( (status = esl_mem_strtoi32("-1234", 5, 10, &nc, &val)) != eslOK || nc != 5 || val != -1234) esl_fatal(msg); if ( (status = esl_mem_strtoi32("\t -1234", 8, 10, &nc, &val)) != eslOK || nc != 8 || val != -1234) esl_fatal(msg); if ( (status = esl_mem_strtoi32("1234", 4, 0, &nc, &val)) != eslOK || nc != 4 || val != 1234) esl_fatal(msg); if ( (status = esl_mem_strtoi32("12345", 4, 0, &nc, &val)) != eslOK || nc != 4 || val != 1234) esl_fatal(msg); if ( (status = esl_mem_strtoi32(" 0xff", 5, 0, &nc, &val)) != eslOK || nc != 5 || val != 255) esl_fatal(msg); if ( (status = esl_mem_strtoi32(" 0777", 4, 0, &nc, &val)) != eslOK || nc != 4 || val != 63) esl_fatal(msg); if ( (status = esl_mem_strtoi32("FFGG", 4, 16, &nc, &val)) != eslOK || nc != 2 || val != 255) esl_fatal(msg); if ( (status = esl_mem_strtoi32("0xffff", 6, 0, &nc, &val)) != eslOK || nc != 6 || val != 65535) esl_fatal(msg); if ( (status = esl_mem_strtoi32("0xffffff", 8, 0, &nc, &val)) != eslOK || nc != 8 || val != 16777215) esl_fatal(msg); if ( (status = esl_mem_strtoi32(" 2147483647", 11, 0, &nc, &val)) != eslOK || nc != 11 || val != INT32_MAX) esl_fatal(msg); if ( (status = esl_mem_strtoi32("-2147483648", 11, 0, &nc, &val)) != eslOK || nc != 11 || val != INT32_MIN) esl_fatal(msg); if ( (status = esl_mem_strtoi32(" 2147483648", 11, 0, &nc, &val)) != eslERANGE || nc != 11 || val != INT32_MAX) esl_fatal(msg); if ( (status = esl_mem_strtoi32("-2147483649", 11, 0, &nc, &val)) != eslERANGE || nc != 11 || val != INT32_MIN) esl_fatal(msg); if ( (status = esl_mem_strtoi32(" 214748364800", 13, 0, &nc, &val)) != eslERANGE || nc != 11 || val != INT32_MAX) esl_fatal(msg); if ( (status = esl_mem_strtoi32("-214748364900", 13, 0, &nc, &val)) != eslERANGE || nc != 11 || val != INT32_MIN) esl_fatal(msg); if ( (status = esl_mem_strtoi32(" 0x1234", 3, 16, &nc, &val)) != eslEFORMAT || nc != 0 || val != 0) esl_fatal(msg); if ( (status = esl_mem_strtoi32("09999999", 7, 0, &nc, &val)) != eslEFORMAT || nc != 0 || val != 0) esl_fatal(msg); return; } static void utest_memtok(void) { char msg[] = "esl_memtok() unit test failed"; char *teststring; esl_pos_t n; char *s; char *tok; esl_pos_t toklen; if (esl_strdup("This is\t a sentence.", -1, &teststring) != eslOK) esl_fatal(msg); s = teststring; n = strlen(teststring); if (esl_memtok(&s, &n, " ", &tok, &toklen) != eslOK) esl_fatal(msg); if (toklen != 4) esl_fatal(msg); if (memcmp(tok, "This", toklen) != 0) esl_fatal(msg); if (*s != 'i') esl_fatal(msg); if (esl_memtok(&s, &n, " \t", &tok, &toklen) != eslOK) esl_fatal(msg); if (toklen != 2) esl_fatal(msg); if (memcmp(tok, "is", toklen) != 0) esl_fatal(msg); if (*s != 'a') esl_fatal(msg); if (esl_memtok(&s, &n, "\n", &tok, &toklen) != eslOK) esl_fatal(msg); if (toklen != 11) esl_fatal(msg); if (memcmp(tok, "a sentence.", toklen) != 0) esl_fatal(msg); if (*s != '\0') esl_fatal(msg); if (n != 0) esl_fatal(msg); if (esl_memtok(&s, &n, "\n", &tok, &toklen) != eslEOL) esl_fatal(msg); if (toklen != 0) esl_fatal(msg); if (tok != NULL) esl_fatal(msg); free(teststring); return; } /* memspn, memcspn() */ static void utest_memspn_memcspn(void) { char msg[] = "memspn/memcspn unit test failed"; char test1[] = " this is a test"; char *p; esl_pos_t n; p = test1; n = 13; /* so the memory is " this is a t" */ if (esl_memspn (p, n, " \t\n\r") != 2) esl_fatal(msg); if (esl_memcspn(p, n, " \t\n\r") != 0) esl_fatal(msg); p = test1+2; n = 11; /* "this is a t" */ if (esl_memspn (p, n, " \t\n\r") != 0) esl_fatal(msg); if (esl_memcspn(p, n, " \t\n\r") != 4) esl_fatal(msg); p = test1; n = 2; if (esl_memspn (p, n, " \t\n\r") != 2) esl_fatal(msg); if (esl_memcspn(p, n, " \t\n\r") != 0) esl_fatal(msg); p = test1+2; n = 4; if (esl_memspn (p, n, " \t\n\r") != 0) esl_fatal(msg); if (esl_memcspn(p, n, " \t\n\r") != 4) esl_fatal(msg); } /* memstrcmp/memstrpfx */ static void utest_memstrcmp_memstrpfx(void) { char msg[] = "memstrcmp/memstrpfx unit test failed"; char test[] = "this is a test"; char *p; esl_pos_t n; p = test; n = strlen(p); if (! esl_memstrcmp(p, n, test)) esl_fatal(msg); if ( esl_memstrcmp(p, n, "this")) esl_fatal(msg); if (! esl_memstrpfx(p, n, "this")) esl_fatal(msg); if ( esl_memstrpfx(p, n, "that")) esl_fatal(msg); p = test; n = 2; /* now p is just "th" */ if (! esl_memstrcmp(p, n, "th")) esl_fatal(msg); if ( esl_memstrcmp(p, n, test)) esl_fatal(msg); if (! esl_memstrpfx(p, n, "th")) esl_fatal(msg); if ( esl_memstrpfx(p, n, "this")) esl_fatal(msg); /* special cases involving NULLs */ p = test; n = strlen(p); if (! esl_memstrcmp(NULL, 0, NULL)) esl_fatal(msg); if ( esl_memstrcmp(NULL, 0, test)) esl_fatal(msg); if ( esl_memstrcmp(p, n, NULL)) esl_fatal(msg); if ( esl_memstrpfx(NULL, 0, NULL)) esl_fatal(msg); if ( esl_memstrpfx(NULL, 0, "this")) esl_fatal(msg); if ( esl_memstrpfx(p, n, NULL)) esl_fatal(msg); } static void utest_memstrcontains(void) { char msg[] = "memstrcontains unit test failed"; char test[] = "CLUSTAL W (1.83) multiple sequence alignment"; char *p; esl_pos_t n; p = test; n = strlen(p); if (! esl_memstrcontains(p, n, "multiple sequence alignment")) esl_fatal(msg); if (! esl_memstrcontains(p, n, "CLUSTAL")) esl_fatal(msg); if ( esl_memstrcontains(p, n, "alignmentx")) esl_fatal(msg); } #endif /*eslMEM_TESTDRIVE*/ /*------------------ end, unit tests ----------------------------*/ /***************************************************************** * 3. Test driver *****************************************************************/ #ifdef eslMEM_TESTDRIVE #include "esl_config.h" #include <stdio.h> #include "easel.h" #include "esl_mem.h" #include "esl_getopts.h" static ESL_OPTIONS options[] = { /* name type default env range togs reqs incomp help docgrp */ {"-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show help and usage", 0}, { 0,0,0,0,0,0,0,0,0,0}, }; static char usage[] = "[-options]"; static char banner[] = "test driver for mem module"; int main(int argc, char **argv) { ESL_GETOPTS *go = esl_getopts_CreateDefaultApp(options, 0, argc, argv, banner, usage); utest_mem_strtoi32(); utest_memtok(); utest_memspn_memcspn(); utest_memstrcmp_memstrpfx(); utest_memstrcontains(); esl_getopts_Destroy(go); return 0; } #endif /* eslMEM_TESTDRIVE */ /*------------------ end, test driver ---------------------------*/ /***************************************************************** * @LICENSE@ * * SVN $Id$ * SVN $URL$ *****************************************************************/
Janelia-Farm-Xfam/Bio-HMM-Logo
src/easel/esl_mem.c
C
gpl-3.0
29,498
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* A 32-bit implementation of the NIST P-256 elliptic curve. */ #include <string.h> #include "prtypes.h" #include "mpi.h" #include "mpi-priv.h" #include "ecp.h" typedef PRUint8 u8; typedef PRUint32 u32; typedef PRUint64 u64; /* Our field elements are represented as nine, unsigned 32-bit words. Freebl's * MPI library calls them digits, but here they are called limbs, which is * GMP's terminology. * * The value of an felem (field element) is: * x[0] + (x[1] * 2**29) + (x[2] * 2**57) + ... + (x[8] * 2**228) * * That is, each limb is alternately 29 or 28-bits wide in little-endian * order. * * This means that an felem hits 2**257, rather than 2**256 as we would like. A * 28, 29, ... pattern would cause us to hit 2**256, but that causes problems * when multiplying as terms end up one bit short of a limb which would require * much bit-shifting to correct. * * Finally, the values stored in an felem are in Montgomery form. So the value * |y| is stored as (y*R) mod p, where p is the P-256 prime and R is 2**257. */ typedef u32 limb; #define NLIMBS 9 typedef limb felem[NLIMBS]; static const limb kBottom28Bits = 0xfffffff; static const limb kBottom29Bits = 0x1fffffff; /* kOne is the number 1 as an felem. It's 2**257 mod p split up into 29 and * 28-bit words. */ static const felem kOne = { 2, 0, 0, 0xffff800, 0x1fffffff, 0xfffffff, 0x1fbfffff, 0x1ffffff, 0 }; static const felem kZero = {0}; static const felem kP = { 0x1fffffff, 0xfffffff, 0x1fffffff, 0x3ff, 0, 0, 0x200000, 0xf000000, 0xfffffff }; static const felem k2P = { 0x1ffffffe, 0xfffffff, 0x1fffffff, 0x7ff, 0, 0, 0x400000, 0xe000000, 0x1fffffff }; /* kPrecomputed contains precomputed values to aid the calculation of scalar * multiples of the base point, G. It's actually two, equal length, tables * concatenated. * * The first table contains (x,y) felem pairs for 16 multiples of the base * point, G. * * Index | Index (binary) | Value * 0 | 0000 | 0G (all zeros, omitted) * 1 | 0001 | G * 2 | 0010 | 2**64G * 3 | 0011 | 2**64G + G * 4 | 0100 | 2**128G * 5 | 0101 | 2**128G + G * 6 | 0110 | 2**128G + 2**64G * 7 | 0111 | 2**128G + 2**64G + G * 8 | 1000 | 2**192G * 9 | 1001 | 2**192G + G * 10 | 1010 | 2**192G + 2**64G * 11 | 1011 | 2**192G + 2**64G + G * 12 | 1100 | 2**192G + 2**128G * 13 | 1101 | 2**192G + 2**128G + G * 14 | 1110 | 2**192G + 2**128G + 2**64G * 15 | 1111 | 2**192G + 2**128G + 2**64G + G * * The second table follows the same style, but the terms are 2**32G, * 2**96G, 2**160G, 2**224G. * * This is ~2KB of data. */ static const limb kPrecomputed[NLIMBS * 2 * 15 * 2] = { 0x11522878, 0xe730d41, 0xdb60179, 0x4afe2ff, 0x12883add, 0xcaddd88, 0x119e7edc, 0xd4a6eab, 0x3120bee, 0x1d2aac15, 0xf25357c, 0x19e45cdd, 0x5c721d0, 0x1992c5a5, 0xa237487, 0x154ba21, 0x14b10bb, 0xae3fe3, 0xd41a576, 0x922fc51, 0x234994f, 0x60b60d3, 0x164586ae, 0xce95f18, 0x1fe49073, 0x3fa36cc, 0x5ebcd2c, 0xb402f2f, 0x15c70bf, 0x1561925c, 0x5a26704, 0xda91e90, 0xcdc1c7f, 0x1ea12446, 0xe1ade1e, 0xec91f22, 0x26f7778, 0x566847e, 0xa0bec9e, 0x234f453, 0x1a31f21a, 0xd85e75c, 0x56c7109, 0xa267a00, 0xb57c050, 0x98fb57, 0xaa837cc, 0x60c0792, 0xcfa5e19, 0x61bab9e, 0x589e39b, 0xa324c5, 0x7d6dee7, 0x2976e4b, 0x1fc4124a, 0xa8c244b, 0x1ce86762, 0xcd61c7e, 0x1831c8e0, 0x75774e1, 0x1d96a5a9, 0x843a649, 0xc3ab0fa, 0x6e2e7d5, 0x7673a2a, 0x178b65e8, 0x4003e9b, 0x1a1f11c2, 0x7816ea, 0xf643e11, 0x58c43df, 0xf423fc2, 0x19633ffa, 0x891f2b2, 0x123c231c, 0x46add8c, 0x54700dd, 0x59e2b17, 0x172db40f, 0x83e277d, 0xb0dd609, 0xfd1da12, 0x35c6e52, 0x19ede20c, 0xd19e0c0, 0x97d0f40, 0xb015b19, 0x449e3f5, 0xe10c9e, 0x33ab581, 0x56a67ab, 0x577734d, 0x1dddc062, 0xc57b10d, 0x149b39d, 0x26a9e7b, 0xc35df9f, 0x48764cd, 0x76dbcca, 0xca4b366, 0xe9303ab, 0x1a7480e7, 0x57e9e81, 0x1e13eb50, 0xf466cf3, 0x6f16b20, 0x4ba3173, 0xc168c33, 0x15cb5439, 0x6a38e11, 0x73658bd, 0xb29564f, 0x3f6dc5b, 0x53b97e, 0x1322c4c0, 0x65dd7ff, 0x3a1e4f6, 0x14e614aa, 0x9246317, 0x1bc83aca, 0xad97eed, 0xd38ce4a, 0xf82b006, 0x341f077, 0xa6add89, 0x4894acd, 0x9f162d5, 0xf8410ef, 0x1b266a56, 0xd7f223, 0x3e0cb92, 0xe39b672, 0x6a2901a, 0x69a8556, 0x7e7c0, 0x9b7d8d3, 0x309a80, 0x1ad05f7f, 0xc2fb5dd, 0xcbfd41d, 0x9ceb638, 0x1051825c, 0xda0cf5b, 0x812e881, 0x6f35669, 0x6a56f2c, 0x1df8d184, 0x345820, 0x1477d477, 0x1645db1, 0xbe80c51, 0xc22be3e, 0xe35e65a, 0x1aeb7aa0, 0xc375315, 0xf67bc99, 0x7fdd7b9, 0x191fc1be, 0x61235d, 0x2c184e9, 0x1c5a839, 0x47a1e26, 0xb7cb456, 0x93e225d, 0x14f3c6ed, 0xccc1ac9, 0x17fe37f3, 0x4988989, 0x1a90c502, 0x2f32042, 0xa17769b, 0xafd8c7c, 0x8191c6e, 0x1dcdb237, 0x16200c0, 0x107b32a1, 0x66c08db, 0x10d06a02, 0x3fc93, 0x5620023, 0x16722b27, 0x68b5c59, 0x270fcfc, 0xfad0ecc, 0xe5de1c2, 0xeab466b, 0x2fc513c, 0x407f75c, 0xbaab133, 0x9705fe9, 0xb88b8e7, 0x734c993, 0x1e1ff8f, 0x19156970, 0xabd0f00, 0x10469ea7, 0x3293ac0, 0xcdc98aa, 0x1d843fd, 0xe14bfe8, 0x15be825f, 0x8b5212, 0xeb3fb67, 0x81cbd29, 0xbc62f16, 0x2b6fcc7, 0xf5a4e29, 0x13560b66, 0xc0b6ac2, 0x51ae690, 0xd41e271, 0xf3e9bd4, 0x1d70aab, 0x1029f72, 0x73e1c35, 0xee70fbc, 0xad81baf, 0x9ecc49a, 0x86c741e, 0xfe6be30, 0x176752e7, 0x23d416, 0x1f83de85, 0x27de188, 0x66f70b8, 0x181cd51f, 0x96b6e4c, 0x188f2335, 0xa5df759, 0x17a77eb6, 0xfeb0e73, 0x154ae914, 0x2f3ec51, 0x3826b59, 0xb91f17d, 0x1c72949, 0x1362bf0a, 0xe23fddf, 0xa5614b0, 0xf7d8f, 0x79061, 0x823d9d2, 0x8213f39, 0x1128ae0b, 0xd095d05, 0xb85c0c2, 0x1ecb2ef, 0x24ddc84, 0xe35e901, 0x18411a4a, 0xf5ddc3d, 0x3786689, 0x52260e8, 0x5ae3564, 0x542b10d, 0x8d93a45, 0x19952aa4, 0x996cc41, 0x1051a729, 0x4be3499, 0x52b23aa, 0x109f307e, 0x6f5b6bb, 0x1f84e1e7, 0x77a0cfa, 0x10c4df3f, 0x25a02ea, 0xb048035, 0xe31de66, 0xc6ecaa3, 0x28ea335, 0x2886024, 0x1372f020, 0xf55d35, 0x15e4684c, 0xf2a9e17, 0x1a4a7529, 0xcb7beb1, 0xb2a78a1, 0x1ab21f1f, 0x6361ccf, 0x6c9179d, 0xb135627, 0x1267b974, 0x4408bad, 0x1cbff658, 0xe3d6511, 0xc7d76f, 0x1cc7a69, 0xe7ee31b, 0x54fab4f, 0x2b914f, 0x1ad27a30, 0xcd3579e, 0xc50124c, 0x50daa90, 0xb13f72, 0xb06aa75, 0x70f5cc6, 0x1649e5aa, 0x84a5312, 0x329043c, 0x41c4011, 0x13d32411, 0xb04a838, 0xd760d2d, 0x1713b532, 0xbaa0c03, 0x84022ab, 0x6bcf5c1, 0x2f45379, 0x18ae070, 0x18c9e11e, 0x20bca9a, 0x66f496b, 0x3eef294, 0x67500d2, 0xd7f613c, 0x2dbbeb, 0xb741038, 0xe04133f, 0x1582968d, 0xbe985f7, 0x1acbc1a, 0x1a6a939f, 0x33e50f6, 0xd665ed4, 0xb4b7bd6, 0x1e5a3799, 0x6b33847, 0x17fa56ff, 0x65ef930, 0x21dc4a, 0x2b37659, 0x450fe17, 0xb357b65, 0xdf5efac, 0x15397bef, 0x9d35a7f, 0x112ac15f, 0x624e62e, 0xa90ae2f, 0x107eecd2, 0x1f69bbe, 0x77d6bce, 0x5741394, 0x13c684fc, 0x950c910, 0x725522b, 0xdc78583, 0x40eeabb, 0x1fde328a, 0xbd61d96, 0xd28c387, 0x9e77d89, 0x12550c40, 0x759cb7d, 0x367ef34, 0xae2a960, 0x91b8bdc, 0x93462a9, 0xf469ef, 0xb2e9aef, 0xd2ca771, 0x54e1f42, 0x7aaa49, 0x6316abb, 0x2413c8e, 0x5425bf9, 0x1bed3e3a, 0xf272274, 0x1f5e7326, 0x6416517, 0xea27072, 0x9cedea7, 0x6e7633, 0x7c91952, 0xd806dce, 0x8e2a7e1, 0xe421e1a, 0x418c9e1, 0x1dbc890, 0x1b395c36, 0xa1dc175, 0x1dc4ef73, 0x8956f34, 0xe4b5cf2, 0x1b0d3a18, 0x3194a36, 0x6c2641f, 0xe44124c, 0xa2f4eaa, 0xa8c25ba, 0xf927ed7, 0x627b614, 0x7371cca, 0xba16694, 0x417bc03, 0x7c0a7e3, 0x9c35c19, 0x1168a205, 0x8b6b00d, 0x10e3edc9, 0x9c19bf2, 0x5882229, 0x1b2b4162, 0xa5cef1a, 0x1543622b, 0x9bd433e, 0x364e04d, 0x7480792, 0x5c9b5b3, 0xe85ff25, 0x408ef57, 0x1814cfa4, 0x121b41b, 0xd248a0f, 0x3b05222, 0x39bb16a, 0xc75966d, 0xa038113, 0xa4a1769, 0x11fbc6c, 0x917e50e, 0xeec3da8, 0x169d6eac, 0x10c1699, 0xa416153, 0xf724912, 0x15cd60b7, 0x4acbad9, 0x5efc5fa, 0xf150ed7, 0x122b51, 0x1104b40a, 0xcb7f442, 0xfbb28ff, 0x6ac53ca, 0x196142cc, 0x7bf0fa9, 0x957651, 0x4e0f215, 0xed439f8, 0x3f46bd5, 0x5ace82f, 0x110916b6, 0x6db078, 0xffd7d57, 0xf2ecaac, 0xca86dec, 0x15d6b2da, 0x965ecc9, 0x1c92b4c2, 0x1f3811, 0x1cb080f5, 0x2d8b804, 0x19d1c12d, 0xf20bd46, 0x1951fa7, 0xa3656c3, 0x523a425, 0xfcd0692, 0xd44ddc8, 0x131f0f5b, 0xaf80e4a, 0xcd9fc74, 0x99bb618, 0x2db944c, 0xa673090, 0x1c210e1, 0x178c8d23, 0x1474383, 0x10b8743d, 0x985a55b, 0x2e74779, 0x576138, 0x9587927, 0x133130fa, 0xbe05516, 0x9f4d619, 0xbb62570, 0x99ec591, 0xd9468fe, 0x1d07782d, 0xfc72e0b, 0x701b298, 0x1863863b, 0x85954b8, 0x121a0c36, 0x9e7fedf, 0xf64b429, 0x9b9d71e, 0x14e2f5d8, 0xf858d3a, 0x942eea8, 0xda5b765, 0x6edafff, 0xa9d18cc, 0xc65e4ba, 0x1c747e86, 0xe4ea915, 0x1981d7a1, 0x8395659, 0x52ed4e2, 0x87d43b7, 0x37ab11b, 0x19d292ce, 0xf8d4692, 0x18c3053f, 0x8863e13, 0x4c146c0, 0x6bdf55a, 0x4e4457d, 0x16152289, 0xac78ec2, 0x1a59c5a2, 0x2028b97, 0x71c2d01, 0x295851f, 0x404747b, 0x878558d, 0x7d29aa4, 0x13d8341f, 0x8daefd7, 0x139c972d, 0x6b7ea75, 0xd4a9dde, 0xff163d8, 0x81d55d7, 0xa5bef68, 0xb7b30d8, 0xbe73d6f, 0xaa88141, 0xd976c81, 0x7e7a9cc, 0x18beb771, 0xd773cbd, 0x13f51951, 0x9d0c177, 0x1c49a78, }; /* Field element operations: */ /* NON_ZERO_TO_ALL_ONES returns: * 0xffffffff for 0 < x <= 2**31 * 0 for x == 0 or x > 2**31. * * x must be a u32 or an equivalent type such as limb. */ #define NON_ZERO_TO_ALL_ONES(x) ((((u32)(x) - 1) >> 31) - 1) /* felem_reduce_carry adds a multiple of p in order to cancel |carry|, * which is a term at 2**257. * * On entry: carry < 2**3, inout[0,2,...] < 2**29, inout[1,3,...] < 2**28. * On exit: inout[0,2,..] < 2**30, inout[1,3,...] < 2**29. */ static void felem_reduce_carry(felem inout, limb carry) { const u32 carry_mask = NON_ZERO_TO_ALL_ONES(carry); inout[0] += carry << 1; inout[3] += 0x10000000 & carry_mask; /* carry < 2**3 thus (carry << 11) < 2**14 and we added 2**28 in the * previous line therefore this doesn't underflow. */ inout[3] -= carry << 11; inout[4] += (0x20000000 - 1) & carry_mask; inout[5] += (0x10000000 - 1) & carry_mask; inout[6] += (0x20000000 - 1) & carry_mask; inout[6] -= carry << 22; /* This may underflow if carry is non-zero but, if so, we'll fix it in the * next line. */ inout[7] -= 1 & carry_mask; inout[7] += carry << 25; } /* felem_sum sets out = in+in2. * * On entry, in[i]+in2[i] must not overflow a 32-bit word. * On exit: out[0,2,...] < 2**30, out[1,3,...] < 2**29 */ static void felem_sum(felem out, const felem in, const felem in2) { limb carry = 0; unsigned int i; for (i = 0;; i++) { out[i] = in[i] + in2[i]; out[i] += carry; carry = out[i] >> 29; out[i] &= kBottom29Bits; i++; if (i == NLIMBS) break; out[i] = in[i] + in2[i]; out[i] += carry; carry = out[i] >> 28; out[i] &= kBottom28Bits; } felem_reduce_carry(out, carry); } #define two31m3 (((limb)1) << 31) - (((limb)1) << 3) #define two30m2 (((limb)1) << 30) - (((limb)1) << 2) #define two30p13m2 (((limb)1) << 30) + (((limb)1) << 13) - (((limb)1) << 2) #define two31m2 (((limb)1) << 31) - (((limb)1) << 2) #define two31p24m2 (((limb)1) << 31) + (((limb)1) << 24) - (((limb)1) << 2) #define two30m27m2 (((limb)1) << 30) - (((limb)1) << 27) - (((limb)1) << 2) /* zero31 is 0 mod p. */ static const felem zero31 = { two31m3, two30m2, two31m2, two30p13m2, two31m2, two30m2, two31p24m2, two30m27m2, two31m2 }; /* felem_diff sets out = in-in2. * * On entry: in[0,2,...] < 2**30, in[1,3,...] < 2**29 and * in2[0,2,...] < 2**30, in2[1,3,...] < 2**29. * On exit: out[0,2,...] < 2**30, out[1,3,...] < 2**29. */ static void felem_diff(felem out, const felem in, const felem in2) { limb carry = 0; unsigned int i; for (i = 0;; i++) { out[i] = in[i] - in2[i]; out[i] += zero31[i]; out[i] += carry; carry = out[i] >> 29; out[i] &= kBottom29Bits; i++; if (i == NLIMBS) break; out[i] = in[i] - in2[i]; out[i] += zero31[i]; out[i] += carry; carry = out[i] >> 28; out[i] &= kBottom28Bits; } felem_reduce_carry(out, carry); } /* felem_reduce_degree sets out = tmp/R mod p where tmp contains 64-bit words * with the same 29,28,... bit positions as an felem. * * The values in felems are in Montgomery form: x*R mod p where R = 2**257. * Since we just multiplied two Montgomery values together, the result is * x*y*R*R mod p. We wish to divide by R in order for the result also to be * in Montgomery form. * * On entry: tmp[i] < 2**64 * On exit: out[0,2,...] < 2**30, out[1,3,...] < 2**29 */ static void felem_reduce_degree(felem out, u64 tmp[17]) { /* The following table may be helpful when reading this code: * * Limb number: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10... * Width (bits): 29| 28| 29| 28| 29| 28| 29| 28| 29| 28| 29 * Start bit: 0 | 29| 57| 86|114|143|171|200|228|257|285 * (odd phase): 0 | 28| 57| 85|114|142|171|199|228|256|285 */ limb tmp2[18], carry, x, xMask; unsigned int i; /* tmp contains 64-bit words with the same 29,28,29-bit positions as an * felem. So the top of an element of tmp might overlap with another * element two positions down. The following loop eliminates this * overlap. */ tmp2[0] = tmp[0] & kBottom29Bits; /* In the following we use "(limb) tmp[x]" and "(limb) (tmp[x]>>32)" to try * and hint to the compiler that it can do a single-word shift by selecting * the right register rather than doing a double-word shift and truncating * afterwards. */ tmp2[1] = ((limb) tmp[0]) >> 29; tmp2[1] |= (((limb) (tmp[0] >> 32)) << 3) & kBottom28Bits; tmp2[1] += ((limb) tmp[1]) & kBottom28Bits; carry = tmp2[1] >> 28; tmp2[1] &= kBottom28Bits; for (i = 2; i < 17; i++) { tmp2[i] = ((limb) (tmp[i - 2] >> 32)) >> 25; tmp2[i] += ((limb) (tmp[i - 1])) >> 28; tmp2[i] += (((limb) (tmp[i - 1] >> 32)) << 4) & kBottom29Bits; tmp2[i] += ((limb) tmp[i]) & kBottom29Bits; tmp2[i] += carry; carry = tmp2[i] >> 29; tmp2[i] &= kBottom29Bits; i++; if (i == 17) break; tmp2[i] = ((limb) (tmp[i - 2] >> 32)) >> 25; tmp2[i] += ((limb) (tmp[i - 1])) >> 29; tmp2[i] += (((limb) (tmp[i - 1] >> 32)) << 3) & kBottom28Bits; tmp2[i] += ((limb) tmp[i]) & kBottom28Bits; tmp2[i] += carry; carry = tmp2[i] >> 28; tmp2[i] &= kBottom28Bits; } tmp2[17] = ((limb) (tmp[15] >> 32)) >> 25; tmp2[17] += ((limb) (tmp[16])) >> 29; tmp2[17] += (((limb) (tmp[16] >> 32)) << 3); tmp2[17] += carry; /* Montgomery elimination of terms: * * Since R is 2**257, we can divide by R with a bitwise shift if we can * ensure that the right-most 257 bits are all zero. We can make that true * by adding multiplies of p without affecting the value. * * So we eliminate limbs from right to left. Since the bottom 29 bits of p * are all ones, then by adding tmp2[0]*p to tmp2 we'll make tmp2[0] == 0. * We can do that for 8 further limbs and then right shift to eliminate the * extra factor of R. */ for (i = 0;; i += 2) { tmp2[i + 1] += tmp2[i] >> 29; x = tmp2[i] & kBottom29Bits; xMask = NON_ZERO_TO_ALL_ONES(x); tmp2[i] = 0; /* The bounds calculations for this loop are tricky. Each iteration of * the loop eliminates two words by adding values to words to their * right. * * The following table contains the amounts added to each word (as an * offset from the value of i at the top of the loop). The amounts are * accounted for from the first and second half of the loop separately * and are written as, for example, 28 to mean a value <2**28. * * Word: 3 4 5 6 7 8 9 10 * Added in top half: 28 11 29 21 29 28 * 28 29 * 29 * Added in bottom half: 29 10 28 21 28 28 * 29 * * The value that is currently offset 7 will be offset 5 for the next * iteration and then offset 3 for the iteration after that. Therefore * the total value added will be the values added at 7, 5 and 3. * * The following table accumulates these values. The sums at the bottom * are written as, for example, 29+28, to mean a value < 2**29+2**28. * * Word: 3 4 5 6 7 8 9 10 11 12 13 * 28 11 10 29 21 29 28 28 28 28 28 * 29 28 11 28 29 28 29 28 29 28 * 29 28 21 21 29 21 29 21 * 10 29 28 21 28 21 28 * 28 29 28 29 28 29 28 * 11 10 29 10 29 10 * 29 28 11 28 11 * 29 29 * -------------------------------------------- * 30+ 31+ 30+ 31+ 30+ * 28+ 29+ 28+ 29+ 21+ * 21+ 28+ 21+ 28+ 10 * 10 21+ 10 21+ * 11 11 * * So the greatest amount is added to tmp2[10] and tmp2[12]. If * tmp2[10/12] has an initial value of <2**29, then the maximum value * will be < 2**31 + 2**30 + 2**28 + 2**21 + 2**11, which is < 2**32, * as required. */ tmp2[i + 3] += (x << 10) & kBottom28Bits; tmp2[i + 4] += (x >> 18); tmp2[i + 6] += (x << 21) & kBottom29Bits; tmp2[i + 7] += x >> 8; /* At position 200, which is the starting bit position for word 7, we * have a factor of 0xf000000 = 2**28 - 2**24. */ tmp2[i + 7] += 0x10000000 & xMask; /* Word 7 is 28 bits wide, so the 2**28 term exactly hits word 8. */ tmp2[i + 8] += (x - 1) & xMask; tmp2[i + 7] -= (x << 24) & kBottom28Bits; tmp2[i + 8] -= x >> 4; tmp2[i + 8] += 0x20000000 & xMask; tmp2[i + 8] -= x; tmp2[i + 8] += (x << 28) & kBottom29Bits; tmp2[i + 9] += ((x >> 1) - 1) & xMask; if (i+1 == NLIMBS) break; tmp2[i + 2] += tmp2[i + 1] >> 28; x = tmp2[i + 1] & kBottom28Bits; xMask = NON_ZERO_TO_ALL_ONES(x); tmp2[i + 1] = 0; tmp2[i + 4] += (x << 11) & kBottom29Bits; tmp2[i + 5] += (x >> 18); tmp2[i + 7] += (x << 21) & kBottom28Bits; tmp2[i + 8] += x >> 7; /* At position 199, which is the starting bit of the 8th word when * dealing with a context starting on an odd word, we have a factor of * 0x1e000000 = 2**29 - 2**25. Since we have not updated i, the 8th * word from i+1 is i+8. */ tmp2[i + 8] += 0x20000000 & xMask; tmp2[i + 9] += (x - 1) & xMask; tmp2[i + 8] -= (x << 25) & kBottom29Bits; tmp2[i + 9] -= x >> 4; tmp2[i + 9] += 0x10000000 & xMask; tmp2[i + 9] -= x; tmp2[i + 10] += (x - 1) & xMask; } /* We merge the right shift with a carry chain. The words above 2**257 have * widths of 28,29,... which we need to correct when copying them down. */ carry = 0; for (i = 0; i < 8; i++) { /* The maximum value of tmp2[i + 9] occurs on the first iteration and * is < 2**30+2**29+2**28. Adding 2**29 (from tmp2[i + 10]) is * therefore safe. */ out[i] = tmp2[i + 9]; out[i] += carry; out[i] += (tmp2[i + 10] << 28) & kBottom29Bits; carry = out[i] >> 29; out[i] &= kBottom29Bits; i++; out[i] = tmp2[i + 9] >> 1; out[i] += carry; carry = out[i] >> 28; out[i] &= kBottom28Bits; } out[8] = tmp2[17]; out[8] += carry; carry = out[8] >> 29; out[8] &= kBottom29Bits; felem_reduce_carry(out, carry); } /* felem_square sets out=in*in. * * On entry: in[0,2,...] < 2**30, in[1,3,...] < 2**29. * On exit: out[0,2,...] < 2**30, out[1,3,...] < 2**29. */ static void felem_square(felem out, const felem in) { u64 tmp[17]; tmp[0] = ((u64) in[0]) * in[0]; tmp[1] = ((u64) in[0]) * (in[1] << 1); tmp[2] = ((u64) in[0]) * (in[2] << 1) + ((u64) in[1]) * (in[1] << 1); tmp[3] = ((u64) in[0]) * (in[3] << 1) + ((u64) in[1]) * (in[2] << 1); tmp[4] = ((u64) in[0]) * (in[4] << 1) + ((u64) in[1]) * (in[3] << 2) + ((u64) in[2]) * in[2]; tmp[5] = ((u64) in[0]) * (in[5] << 1) + ((u64) in[1]) * (in[4] << 1) + ((u64) in[2]) * (in[3] << 1); tmp[6] = ((u64) in[0]) * (in[6] << 1) + ((u64) in[1]) * (in[5] << 2) + ((u64) in[2]) * (in[4] << 1) + ((u64) in[3]) * (in[3] << 1); tmp[7] = ((u64) in[0]) * (in[7] << 1) + ((u64) in[1]) * (in[6] << 1) + ((u64) in[2]) * (in[5] << 1) + ((u64) in[3]) * (in[4] << 1); /* tmp[8] has the greatest value of 2**61 + 2**60 + 2**61 + 2**60 + 2**60, * which is < 2**64 as required. */ tmp[8] = ((u64) in[0]) * (in[8] << 1) + ((u64) in[1]) * (in[7] << 2) + ((u64) in[2]) * (in[6] << 1) + ((u64) in[3]) * (in[5] << 2) + ((u64) in[4]) * in[4]; tmp[9] = ((u64) in[1]) * (in[8] << 1) + ((u64) in[2]) * (in[7] << 1) + ((u64) in[3]) * (in[6] << 1) + ((u64) in[4]) * (in[5] << 1); tmp[10] = ((u64) in[2]) * (in[8] << 1) + ((u64) in[3]) * (in[7] << 2) + ((u64) in[4]) * (in[6] << 1) + ((u64) in[5]) * (in[5] << 1); tmp[11] = ((u64) in[3]) * (in[8] << 1) + ((u64) in[4]) * (in[7] << 1) + ((u64) in[5]) * (in[6] << 1); tmp[12] = ((u64) in[4]) * (in[8] << 1) + ((u64) in[5]) * (in[7] << 2) + ((u64) in[6]) * in[6]; tmp[13] = ((u64) in[5]) * (in[8] << 1) + ((u64) in[6]) * (in[7] << 1); tmp[14] = ((u64) in[6]) * (in[8] << 1) + ((u64) in[7]) * (in[7] << 1); tmp[15] = ((u64) in[7]) * (in[8] << 1); tmp[16] = ((u64) in[8]) * in[8]; felem_reduce_degree(out, tmp); } /* felem_mul sets out=in*in2. * * On entry: in[0,2,...] < 2**30, in[1,3,...] < 2**29 and * in2[0,2,...] < 2**30, in2[1,3,...] < 2**29. * On exit: out[0,2,...] < 2**30, out[1,3,...] < 2**29. */ static void felem_mul(felem out, const felem in, const felem in2) { u64 tmp[17]; tmp[0] = ((u64) in[0]) * in2[0]; tmp[1] = ((u64) in[0]) * (in2[1] << 0) + ((u64) in[1]) * (in2[0] << 0); tmp[2] = ((u64) in[0]) * (in2[2] << 0) + ((u64) in[1]) * (in2[1] << 1) + ((u64) in[2]) * (in2[0] << 0); tmp[3] = ((u64) in[0]) * (in2[3] << 0) + ((u64) in[1]) * (in2[2] << 0) + ((u64) in[2]) * (in2[1] << 0) + ((u64) in[3]) * (in2[0] << 0); tmp[4] = ((u64) in[0]) * (in2[4] << 0) + ((u64) in[1]) * (in2[3] << 1) + ((u64) in[2]) * (in2[2] << 0) + ((u64) in[3]) * (in2[1] << 1) + ((u64) in[4]) * (in2[0] << 0); tmp[5] = ((u64) in[0]) * (in2[5] << 0) + ((u64) in[1]) * (in2[4] << 0) + ((u64) in[2]) * (in2[3] << 0) + ((u64) in[3]) * (in2[2] << 0) + ((u64) in[4]) * (in2[1] << 0) + ((u64) in[5]) * (in2[0] << 0); tmp[6] = ((u64) in[0]) * (in2[6] << 0) + ((u64) in[1]) * (in2[5] << 1) + ((u64) in[2]) * (in2[4] << 0) + ((u64) in[3]) * (in2[3] << 1) + ((u64) in[4]) * (in2[2] << 0) + ((u64) in[5]) * (in2[1] << 1) + ((u64) in[6]) * (in2[0] << 0); tmp[7] = ((u64) in[0]) * (in2[7] << 0) + ((u64) in[1]) * (in2[6] << 0) + ((u64) in[2]) * (in2[5] << 0) + ((u64) in[3]) * (in2[4] << 0) + ((u64) in[4]) * (in2[3] << 0) + ((u64) in[5]) * (in2[2] << 0) + ((u64) in[6]) * (in2[1] << 0) + ((u64) in[7]) * (in2[0] << 0); /* tmp[8] has the greatest value but doesn't overflow. See logic in * felem_square. */ tmp[8] = ((u64) in[0]) * (in2[8] << 0) + ((u64) in[1]) * (in2[7] << 1) + ((u64) in[2]) * (in2[6] << 0) + ((u64) in[3]) * (in2[5] << 1) + ((u64) in[4]) * (in2[4] << 0) + ((u64) in[5]) * (in2[3] << 1) + ((u64) in[6]) * (in2[2] << 0) + ((u64) in[7]) * (in2[1] << 1) + ((u64) in[8]) * (in2[0] << 0); tmp[9] = ((u64) in[1]) * (in2[8] << 0) + ((u64) in[2]) * (in2[7] << 0) + ((u64) in[3]) * (in2[6] << 0) + ((u64) in[4]) * (in2[5] << 0) + ((u64) in[5]) * (in2[4] << 0) + ((u64) in[6]) * (in2[3] << 0) + ((u64) in[7]) * (in2[2] << 0) + ((u64) in[8]) * (in2[1] << 0); tmp[10] = ((u64) in[2]) * (in2[8] << 0) + ((u64) in[3]) * (in2[7] << 1) + ((u64) in[4]) * (in2[6] << 0) + ((u64) in[5]) * (in2[5] << 1) + ((u64) in[6]) * (in2[4] << 0) + ((u64) in[7]) * (in2[3] << 1) + ((u64) in[8]) * (in2[2] << 0); tmp[11] = ((u64) in[3]) * (in2[8] << 0) + ((u64) in[4]) * (in2[7] << 0) + ((u64) in[5]) * (in2[6] << 0) + ((u64) in[6]) * (in2[5] << 0) + ((u64) in[7]) * (in2[4] << 0) + ((u64) in[8]) * (in2[3] << 0); tmp[12] = ((u64) in[4]) * (in2[8] << 0) + ((u64) in[5]) * (in2[7] << 1) + ((u64) in[6]) * (in2[6] << 0) + ((u64) in[7]) * (in2[5] << 1) + ((u64) in[8]) * (in2[4] << 0); tmp[13] = ((u64) in[5]) * (in2[8] << 0) + ((u64) in[6]) * (in2[7] << 0) + ((u64) in[7]) * (in2[6] << 0) + ((u64) in[8]) * (in2[5] << 0); tmp[14] = ((u64) in[6]) * (in2[8] << 0) + ((u64) in[7]) * (in2[7] << 1) + ((u64) in[8]) * (in2[6] << 0); tmp[15] = ((u64) in[7]) * (in2[8] << 0) + ((u64) in[8]) * (in2[7] << 0); tmp[16] = ((u64) in[8]) * (in2[8] << 0); felem_reduce_degree(out, tmp); } static void felem_assign(felem out, const felem in) { memcpy(out, in, sizeof(felem)); } /* felem_inv calculates |out| = |in|^{-1} * * Based on Fermat's Little Theorem: * a^p = a (mod p) * a^{p-1} = 1 (mod p) * a^{p-2} = a^{-1} (mod p) */ static void felem_inv(felem out, const felem in) { felem ftmp, ftmp2; /* each e_I will hold |in|^{2^I - 1} */ felem e2, e4, e8, e16, e32, e64; unsigned int i; felem_square(ftmp, in); /* 2^1 */ felem_mul(ftmp, in, ftmp); /* 2^2 - 2^0 */ felem_assign(e2, ftmp); felem_square(ftmp, ftmp); /* 2^3 - 2^1 */ felem_square(ftmp, ftmp); /* 2^4 - 2^2 */ felem_mul(ftmp, ftmp, e2); /* 2^4 - 2^0 */ felem_assign(e4, ftmp); felem_square(ftmp, ftmp); /* 2^5 - 2^1 */ felem_square(ftmp, ftmp); /* 2^6 - 2^2 */ felem_square(ftmp, ftmp); /* 2^7 - 2^3 */ felem_square(ftmp, ftmp); /* 2^8 - 2^4 */ felem_mul(ftmp, ftmp, e4); /* 2^8 - 2^0 */ felem_assign(e8, ftmp); for (i = 0; i < 8; i++) { felem_square(ftmp, ftmp); } /* 2^16 - 2^8 */ felem_mul(ftmp, ftmp, e8); /* 2^16 - 2^0 */ felem_assign(e16, ftmp); for (i = 0; i < 16; i++) { felem_square(ftmp, ftmp); } /* 2^32 - 2^16 */ felem_mul(ftmp, ftmp, e16); /* 2^32 - 2^0 */ felem_assign(e32, ftmp); for (i = 0; i < 32; i++) { felem_square(ftmp, ftmp); } /* 2^64 - 2^32 */ felem_assign(e64, ftmp); felem_mul(ftmp, ftmp, in); /* 2^64 - 2^32 + 2^0 */ for (i = 0; i < 192; i++) { felem_square(ftmp, ftmp); } /* 2^256 - 2^224 + 2^192 */ felem_mul(ftmp2, e64, e32); /* 2^64 - 2^0 */ for (i = 0; i < 16; i++) { felem_square(ftmp2, ftmp2); } /* 2^80 - 2^16 */ felem_mul(ftmp2, ftmp2, e16); /* 2^80 - 2^0 */ for (i = 0; i < 8; i++) { felem_square(ftmp2, ftmp2); } /* 2^88 - 2^8 */ felem_mul(ftmp2, ftmp2, e8); /* 2^88 - 2^0 */ for (i = 0; i < 4; i++) { felem_square(ftmp2, ftmp2); } /* 2^92 - 2^4 */ felem_mul(ftmp2, ftmp2, e4); /* 2^92 - 2^0 */ felem_square(ftmp2, ftmp2); /* 2^93 - 2^1 */ felem_square(ftmp2, ftmp2); /* 2^94 - 2^2 */ felem_mul(ftmp2, ftmp2, e2); /* 2^94 - 2^0 */ felem_square(ftmp2, ftmp2); /* 2^95 - 2^1 */ felem_square(ftmp2, ftmp2); /* 2^96 - 2^2 */ felem_mul(ftmp2, ftmp2, in); /* 2^96 - 3 */ felem_mul(out, ftmp2, ftmp); /* 2^256 - 2^224 + 2^192 + 2^96 - 3 */ } /* felem_scalar_3 sets out=3*out. * * On entry: out[0,2,...] < 2**30, out[1,3,...] < 2**29. * On exit: out[0,2,...] < 2**30, out[1,3,...] < 2**29. */ static void felem_scalar_3(felem out) { limb carry = 0; unsigned int i; for (i = 0;; i++) { out[i] *= 3; out[i] += carry; carry = out[i] >> 29; out[i] &= kBottom29Bits; i++; if (i == NLIMBS) break; out[i] *= 3; out[i] += carry; carry = out[i] >> 28; out[i] &= kBottom28Bits; } felem_reduce_carry(out, carry); } /* felem_scalar_4 sets out=4*out. * * On entry: out[0,2,...] < 2**30, out[1,3,...] < 2**29. * On exit: out[0,2,...] < 2**30, out[1,3,...] < 2**29. */ static void felem_scalar_4(felem out) { limb carry = 0, next_carry; unsigned int i; for (i = 0;; i++) { next_carry = out[i] >> 27; out[i] <<= 2; out[i] &= kBottom29Bits; out[i] += carry; carry = next_carry + (out[i] >> 29); out[i] &= kBottom29Bits; i++; if (i == NLIMBS) break; next_carry = out[i] >> 26; out[i] <<= 2; out[i] &= kBottom28Bits; out[i] += carry; carry = next_carry + (out[i] >> 28); out[i] &= kBottom28Bits; } felem_reduce_carry(out, carry); } /* felem_scalar_8 sets out=8*out. * * On entry: out[0,2,...] < 2**30, out[1,3,...] < 2**29. * On exit: out[0,2,...] < 2**30, out[1,3,...] < 2**29. */ static void felem_scalar_8(felem out) { limb carry = 0, next_carry; unsigned int i; for (i = 0;; i++) { next_carry = out[i] >> 26; out[i] <<= 3; out[i] &= kBottom29Bits; out[i] += carry; carry = next_carry + (out[i] >> 29); out[i] &= kBottom29Bits; i++; if (i == NLIMBS) break; next_carry = out[i] >> 25; out[i] <<= 3; out[i] &= kBottom28Bits; out[i] += carry; carry = next_carry + (out[i] >> 28); out[i] &= kBottom28Bits; } felem_reduce_carry(out, carry); } /* felem_is_zero_vartime returns 1 iff |in| == 0. It takes a variable amount of * time depending on the value of |in|. */ static char felem_is_zero_vartime(const felem in) { limb carry; int i; limb tmp[NLIMBS]; felem_assign(tmp, in); /* First, reduce tmp to a minimal form. */ do { carry = 0; for (i = 0;; i++) { tmp[i] += carry; carry = tmp[i] >> 29; tmp[i] &= kBottom29Bits; i++; if (i == NLIMBS) break; tmp[i] += carry; carry = tmp[i] >> 28; tmp[i] &= kBottom28Bits; } felem_reduce_carry(tmp, carry); } while (carry); /* tmp < 2**257, so the only possible zero values are 0, p and 2p. */ return memcmp(tmp, kZero, sizeof(tmp)) == 0 || memcmp(tmp, kP, sizeof(tmp)) == 0 || memcmp(tmp, k2P, sizeof(tmp)) == 0; } /* Group operations: * * Elements of the elliptic curve group are represented in Jacobian * coordinates: (x, y, z). An affine point (x', y') is x'=x/z**2, y'=y/z**3 in * Jacobian form. */ /* point_double sets {x_out,y_out,z_out} = 2*{x,y,z}. * * See http://www.hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#doubling-dbl-2009-l */ static void point_double(felem x_out, felem y_out, felem z_out, const felem x, const felem y, const felem z) { felem delta, gamma, alpha, beta, tmp, tmp2; felem_square(delta, z); felem_square(gamma, y); felem_mul(beta, x, gamma); felem_sum(tmp, x, delta); felem_diff(tmp2, x, delta); felem_mul(alpha, tmp, tmp2); felem_scalar_3(alpha); felem_sum(tmp, y, z); felem_square(tmp, tmp); felem_diff(tmp, tmp, gamma); felem_diff(z_out, tmp, delta); felem_scalar_4(beta); felem_square(x_out, alpha); felem_diff(x_out, x_out, beta); felem_diff(x_out, x_out, beta); felem_diff(tmp, beta, x_out); felem_mul(tmp, alpha, tmp); felem_square(tmp2, gamma); felem_scalar_8(tmp2); felem_diff(y_out, tmp, tmp2); } /* point_add_mixed sets {x_out,y_out,z_out} = {x1,y1,z1} + {x2,y2,1}. * (i.e. the second point is affine.) * * See http://www.hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#addition-add-2007-bl * * Note that this function does not handle P+P, infinity+P nor P+infinity * correctly. */ static void point_add_mixed(felem x_out, felem y_out, felem z_out, const felem x1, const felem y1, const felem z1, const felem x2, const felem y2) { felem z1z1, z1z1z1, s2, u2, h, i, j, r, rr, v, tmp; felem_square(z1z1, z1); felem_sum(tmp, z1, z1); felem_mul(u2, x2, z1z1); felem_mul(z1z1z1, z1, z1z1); felem_mul(s2, y2, z1z1z1); felem_diff(h, u2, x1); felem_sum(i, h, h); felem_square(i, i); felem_mul(j, h, i); felem_diff(r, s2, y1); felem_sum(r, r, r); felem_mul(v, x1, i); felem_mul(z_out, tmp, h); felem_square(rr, r); felem_diff(x_out, rr, j); felem_diff(x_out, x_out, v); felem_diff(x_out, x_out, v); felem_diff(tmp, v, x_out); felem_mul(y_out, tmp, r); felem_mul(tmp, y1, j); felem_diff(y_out, y_out, tmp); felem_diff(y_out, y_out, tmp); } /* point_add sets {x_out,y_out,z_out} = {x1,y1,z1} + {x2,y2,z2}. * * See http://www.hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#addition-add-2007-bl * * Note that this function does not handle P+P, infinity+P nor P+infinity * correctly. */ static void point_add(felem x_out, felem y_out, felem z_out, const felem x1, const felem y1, const felem z1, const felem x2, const felem y2, const felem z2) { felem z1z1, z1z1z1, z2z2, z2z2z2, s1, s2, u1, u2, h, i, j, r, rr, v, tmp; felem_square(z1z1, z1); felem_square(z2z2, z2); felem_mul(u1, x1, z2z2); felem_sum(tmp, z1, z2); felem_square(tmp, tmp); felem_diff(tmp, tmp, z1z1); felem_diff(tmp, tmp, z2z2); felem_mul(z2z2z2, z2, z2z2); felem_mul(s1, y1, z2z2z2); felem_mul(u2, x2, z1z1); felem_mul(z1z1z1, z1, z1z1); felem_mul(s2, y2, z1z1z1); felem_diff(h, u2, u1); felem_sum(i, h, h); felem_square(i, i); felem_mul(j, h, i); felem_diff(r, s2, s1); felem_sum(r, r, r); felem_mul(v, u1, i); felem_mul(z_out, tmp, h); felem_square(rr, r); felem_diff(x_out, rr, j); felem_diff(x_out, x_out, v); felem_diff(x_out, x_out, v); felem_diff(tmp, v, x_out); felem_mul(y_out, tmp, r); felem_mul(tmp, s1, j); felem_diff(y_out, y_out, tmp); felem_diff(y_out, y_out, tmp); } /* point_add_or_double_vartime sets {x_out,y_out,z_out} = {x1,y1,z1} + * {x2,y2,z2}. * * See http://www.hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#addition-add-2007-bl * * This function handles the case where {x1,y1,z1}={x2,y2,z2}. */ static void point_add_or_double_vartime( felem x_out, felem y_out, felem z_out, const felem x1, const felem y1, const felem z1, const felem x2, const felem y2, const felem z2) { felem z1z1, z1z1z1, z2z2, z2z2z2, s1, s2, u1, u2, h, i, j, r, rr, v, tmp; char x_equal, y_equal; felem_square(z1z1, z1); felem_square(z2z2, z2); felem_mul(u1, x1, z2z2); felem_sum(tmp, z1, z2); felem_square(tmp, tmp); felem_diff(tmp, tmp, z1z1); felem_diff(tmp, tmp, z2z2); felem_mul(z2z2z2, z2, z2z2); felem_mul(s1, y1, z2z2z2); felem_mul(u2, x2, z1z1); felem_mul(z1z1z1, z1, z1z1); felem_mul(s2, y2, z1z1z1); felem_diff(h, u2, u1); x_equal = felem_is_zero_vartime(h); felem_sum(i, h, h); felem_square(i, i); felem_mul(j, h, i); felem_diff(r, s2, s1); y_equal = felem_is_zero_vartime(r); if (x_equal && y_equal) { point_double(x_out, y_out, z_out, x1, y1, z1); return; } felem_sum(r, r, r); felem_mul(v, u1, i); felem_mul(z_out, tmp, h); felem_square(rr, r); felem_diff(x_out, rr, j); felem_diff(x_out, x_out, v); felem_diff(x_out, x_out, v); felem_diff(tmp, v, x_out); felem_mul(y_out, tmp, r); felem_mul(tmp, s1, j); felem_diff(y_out, y_out, tmp); felem_diff(y_out, y_out, tmp); } /* copy_conditional sets out=in if mask = 0xffffffff in constant time. * * On entry: mask is either 0 or 0xffffffff. */ static void copy_conditional(felem out, const felem in, limb mask) { int i; for (i = 0; i < NLIMBS; i++) { const limb tmp = mask & (in[i] ^ out[i]); out[i] ^= tmp; } } /* select_affine_point sets {out_x,out_y} to the index'th entry of table. * On entry: index < 16, table[0] must be zero. */ static void select_affine_point(felem out_x, felem out_y, const limb *table, limb index) { limb i, j; memset(out_x, 0, sizeof(felem)); memset(out_y, 0, sizeof(felem)); for (i = 1; i < 16; i++) { limb mask = i ^ index; mask |= mask >> 2; mask |= mask >> 1; mask &= 1; mask--; for (j = 0; j < NLIMBS; j++, table++) { out_x[j] |= *table & mask; } for (j = 0; j < NLIMBS; j++, table++) { out_y[j] |= *table & mask; } } } /* select_jacobian_point sets {out_x,out_y,out_z} to the index'th entry of * table. On entry: index < 16, table[0] must be zero. */ static void select_jacobian_point(felem out_x, felem out_y, felem out_z, const limb *table, limb index) { limb i, j; memset(out_x, 0, sizeof(felem)); memset(out_y, 0, sizeof(felem)); memset(out_z, 0, sizeof(felem)); /* The implicit value at index 0 is all zero. We don't need to perform that * iteration of the loop because we already set out_* to zero. */ table += 3*NLIMBS; for (i = 1; i < 16; i++) { limb mask = i ^ index; mask |= mask >> 2; mask |= mask >> 1; mask &= 1; mask--; for (j = 0; j < NLIMBS; j++, table++) { out_x[j] |= *table & mask; } for (j = 0; j < NLIMBS; j++, table++) { out_y[j] |= *table & mask; } for (j = 0; j < NLIMBS; j++, table++) { out_z[j] |= *table & mask; } } } /* get_bit returns the bit'th bit of scalar. */ static char get_bit(const u8 scalar[32], int bit) { return ((scalar[bit >> 3]) >> (bit & 7)) & 1; } /* scalar_base_mult sets {nx,ny,nz} = scalar*G where scalar is a little-endian * number. Note that the value of scalar must be less than the order of the * group. */ static void scalar_base_mult(felem nx, felem ny, felem nz, const u8 scalar[32]) { int i, j; limb n_is_infinity_mask = -1, p_is_noninfinite_mask, mask; u32 table_offset; felem px, py; felem tx, ty, tz; memset(nx, 0, sizeof(felem)); memset(ny, 0, sizeof(felem)); memset(nz, 0, sizeof(felem)); /* The loop adds bits at positions 0, 64, 128 and 192, followed by * positions 32,96,160 and 224 and does this 32 times. */ for (i = 0; i < 32; i++) { if (i) { point_double(nx, ny, nz, nx, ny, nz); } table_offset = 0; for (j = 0; j <= 32; j += 32) { char bit0 = get_bit(scalar, 31 - i + j); char bit1 = get_bit(scalar, 95 - i + j); char bit2 = get_bit(scalar, 159 - i + j); char bit3 = get_bit(scalar, 223 - i + j); limb index = bit0 | (bit1 << 1) | (bit2 << 2) | (bit3 << 3); select_affine_point(px, py, kPrecomputed + table_offset, index); table_offset += 30 * NLIMBS; /* Since scalar is less than the order of the group, we know that * {nx,ny,nz} != {px,py,1}, unless both are zero, which we handle * below. */ point_add_mixed(tx, ty, tz, nx, ny, nz, px, py); /* The result of point_add_mixed is incorrect if {nx,ny,nz} is zero * (a.k.a. the point at infinity). We handle that situation by * copying the point from the table. */ copy_conditional(nx, px, n_is_infinity_mask); copy_conditional(ny, py, n_is_infinity_mask); copy_conditional(nz, kOne, n_is_infinity_mask); /* Equally, the result is also wrong if the point from the table is * zero, which happens when the index is zero. We handle that by * only copying from {tx,ty,tz} to {nx,ny,nz} if index != 0. */ p_is_noninfinite_mask = NON_ZERO_TO_ALL_ONES(index); mask = p_is_noninfinite_mask & ~n_is_infinity_mask; copy_conditional(nx, tx, mask); copy_conditional(ny, ty, mask); copy_conditional(nz, tz, mask); /* If p was not zero, then n is now non-zero. */ n_is_infinity_mask &= ~p_is_noninfinite_mask; } } } /* point_to_affine converts a Jacobian point to an affine point. If the input * is the point at infinity then it returns (0, 0) in constant time. */ static void point_to_affine(felem x_out, felem y_out, const felem nx, const felem ny, const felem nz) { felem z_inv, z_inv_sq; felem_inv(z_inv, nz); felem_square(z_inv_sq, z_inv); felem_mul(x_out, nx, z_inv_sq); felem_mul(z_inv, z_inv, z_inv_sq); felem_mul(y_out, ny, z_inv); } /* scalar_mult sets {nx,ny,nz} = scalar*{x,y}. */ static void scalar_mult(felem nx, felem ny, felem nz, const felem x, const felem y, const u8 scalar[32]) { int i; felem px, py, pz, tx, ty, tz; felem precomp[16][3]; limb n_is_infinity_mask, index, p_is_noninfinite_mask, mask; /* We precompute 0,1,2,... times {x,y}. */ memset(precomp, 0, sizeof(felem) * 3); memcpy(&precomp[1][0], x, sizeof(felem)); memcpy(&precomp[1][1], y, sizeof(felem)); memcpy(&precomp[1][2], kOne, sizeof(felem)); for (i = 2; i < 16; i += 2) { point_double(precomp[i][0], precomp[i][1], precomp[i][2], precomp[i / 2][0], precomp[i / 2][1], precomp[i / 2][2]); point_add_mixed(precomp[i + 1][0], precomp[i + 1][1], precomp[i + 1][2], precomp[i][0], precomp[i][1], precomp[i][2], x, y); } memset(nx, 0, sizeof(felem)); memset(ny, 0, sizeof(felem)); memset(nz, 0, sizeof(felem)); n_is_infinity_mask = -1; /* We add in a window of four bits each iteration and do this 64 times. */ for (i = 0; i < 64; i++) { if (i) { point_double(nx, ny, nz, nx, ny, nz); point_double(nx, ny, nz, nx, ny, nz); point_double(nx, ny, nz, nx, ny, nz); point_double(nx, ny, nz, nx, ny, nz); } index = scalar[31 - i / 2]; if ((i & 1) == 1) { index &= 15; } else { index >>= 4; } /* See the comments in scalar_base_mult about handling infinities. */ select_jacobian_point(px, py, pz, precomp[0][0], index); point_add(tx, ty, tz, nx, ny, nz, px, py, pz); copy_conditional(nx, px, n_is_infinity_mask); copy_conditional(ny, py, n_is_infinity_mask); copy_conditional(nz, pz, n_is_infinity_mask); p_is_noninfinite_mask = NON_ZERO_TO_ALL_ONES(index); mask = p_is_noninfinite_mask & ~n_is_infinity_mask; copy_conditional(nx, tx, mask); copy_conditional(ny, ty, mask); copy_conditional(nz, tz, mask); n_is_infinity_mask &= ~p_is_noninfinite_mask; } } /* Interface with Freebl: */ /* BYTESWAP_MP_DIGIT_TO_LE swaps the bytes of a mp_digit to * little-endian order. */ #ifdef IS_BIG_ENDIAN #ifdef __APPLE__ #include <libkern/OSByteOrder.h> #define BYTESWAP32(x) OSSwapInt32(x) #define BYTESWAP64(x) OSSwapInt64(x) #else #define BYTESWAP32(x) \ (((x) >> 24) | (((x) >> 8) & 0xff00) | (((x) & 0xff00) << 8) | ((x) << 24)) #define BYTESWAP64(x) \ (((x) >> 56) | (((x) >> 40) & 0xff00) | \ (((x) >> 24) & 0xff0000) | (((x) >> 8) & 0xff000000) | \ (((x) & 0xff000000) << 8) | (((x) & 0xff0000) << 24) | \ (((x) & 0xff00) << 40) | ((x) << 56)) #endif #ifdef MP_USE_UINT_DIGIT #define BYTESWAP_MP_DIGIT_TO_LE(x) BYTESWAP32(x) #else #define BYTESWAP_MP_DIGIT_TO_LE(x) BYTESWAP64(x) #endif #endif /* IS_BIG_ENDIAN */ #ifdef MP_USE_UINT_DIGIT static const mp_digit kRInvDigits[8] = { 0x80000000, 1, 0xffffffff, 0, 0x80000001, 0xfffffffe, 1, 0x7fffffff }; #else static const mp_digit kRInvDigits[4] = { PR_UINT64(0x180000000), 0xffffffff, PR_UINT64(0xfffffffe80000001), PR_UINT64(0x7fffffff00000001) }; #endif #define MP_DIGITS_IN_256_BITS (32/sizeof(mp_digit)) static const mp_int kRInv = { MP_ZPOS, MP_DIGITS_IN_256_BITS, MP_DIGITS_IN_256_BITS, (mp_digit*) kRInvDigits }; static const limb kTwo28 = 0x10000000; static const limb kTwo29 = 0x20000000; /* to_montgomery sets out = R*in. */ static mp_err to_montgomery(felem out, const mp_int *in, const ECGroup *group) { /* There are no MPI functions for bitshift operations and we wish to shift * in 257 bits left so we move the digits 256-bits left and then multiply * by two. */ mp_int in_shifted; int i; mp_err res; mp_init(&in_shifted); s_mp_pad(&in_shifted, MP_USED(in) + MP_DIGITS_IN_256_BITS); memcpy(&MP_DIGIT(&in_shifted, MP_DIGITS_IN_256_BITS), MP_DIGITS(in), MP_USED(in)*sizeof(mp_digit)); mp_mul_2(&in_shifted, &in_shifted); MP_CHECKOK(group->meth->field_mod(&in_shifted, &in_shifted, group->meth)); for (i = 0;; i++) { out[i] = MP_DIGIT(&in_shifted, 0) & kBottom29Bits; mp_div_d(&in_shifted, kTwo29, &in_shifted, NULL); i++; if (i == NLIMBS) break; out[i] = MP_DIGIT(&in_shifted, 0) & kBottom28Bits; mp_div_d(&in_shifted, kTwo28, &in_shifted, NULL); } CLEANUP: mp_clear(&in_shifted); return res; } /* from_montgomery sets out=in/R. */ static mp_err from_montgomery(mp_int *out, const felem in, const ECGroup *group) { mp_int result, tmp; mp_err res; int i; mp_init(&result); mp_init(&tmp); MP_CHECKOK(mp_add_d(&tmp, in[NLIMBS-1], &result)); for (i = NLIMBS-2; i >= 0; i--) { if ((i & 1) == 0) { MP_CHECKOK(mp_mul_d(&result, kTwo29, &tmp)); } else { MP_CHECKOK(mp_mul_d(&result, kTwo28, &tmp)); } MP_CHECKOK(mp_add_d(&tmp, in[i], &result)); } MP_CHECKOK(mp_mul(&result, &kRInv, out)); MP_CHECKOK(group->meth->field_mod(out, out, group->meth)); CLEANUP: mp_clear(&result); mp_clear(&tmp); return res; } /* scalar_from_mp_int sets out_scalar=n, where n < the group order. */ static void scalar_from_mp_int(u8 out_scalar[32], const mp_int *n) { /* We require that |n| is less than the order of the group and therefore it * will fit into |out_scalar|. However, these is a timing side-channel here * that we cannot avoid: if |n| is sufficiently small it may be one or more * words too short and we'll copy less data. */ memset(out_scalar, 0, 32); #ifdef IS_LITTLE_ENDIAN memcpy(out_scalar, MP_DIGITS(n), MP_USED(n) * sizeof(mp_digit)); #else { mp_size i; mp_digit swapped[MP_DIGITS_IN_256_BITS]; for (i = 0; i < MP_USED(n); i++) { swapped[i] = BYTESWAP_MP_DIGIT_TO_LE(MP_DIGIT(n, i)); } memcpy(out_scalar, swapped, MP_USED(n) * sizeof(mp_digit)); } #endif } /* ec_GFp_nistp256_base_point_mul sets {out_x,out_y} = nG, where n is < the * order of the group. */ static mp_err ec_GFp_nistp256_base_point_mul(const mp_int *n, mp_int *out_x, mp_int *out_y, const ECGroup *group) { u8 scalar[32]; felem x, y, z, x_affine, y_affine; mp_err res; /* FIXME(agl): test that n < order. */ scalar_from_mp_int(scalar, n); scalar_base_mult(x, y, z, scalar); point_to_affine(x_affine, y_affine, x, y, z); MP_CHECKOK(from_montgomery(out_x, x_affine, group)); MP_CHECKOK(from_montgomery(out_y, y_affine, group)); CLEANUP: return res; } /* ec_GFp_nistp256_point_mul sets {out_x,out_y} = n*{in_x,in_y}, where n is < * the order of the group. */ static mp_err ec_GFp_nistp256_point_mul(const mp_int *n, const mp_int *in_x, const mp_int *in_y, mp_int *out_x, mp_int *out_y, const ECGroup *group) { u8 scalar[32]; felem x, y, z, x_affine, y_affine, px, py; mp_err res; scalar_from_mp_int(scalar, n); MP_CHECKOK(to_montgomery(px, in_x, group)); MP_CHECKOK(to_montgomery(py, in_y, group)); scalar_mult(x, y, z, px, py, scalar); point_to_affine(x_affine, y_affine, x, y, z); MP_CHECKOK(from_montgomery(out_x, x_affine, group)); MP_CHECKOK(from_montgomery(out_y, y_affine, group)); CLEANUP: return res; } /* ec_GFp_nistp256_point_mul_vartime sets {out_x,out_y} = n1*G + * n2*{in_x,in_y}, where n1 and n2 are < the order of the group. * * As indicated by the name, this function operates in variable time. This * is safe because it's used for signature validation which doesn't deal * with secrets. */ static mp_err ec_GFp_nistp256_points_mul_vartime( const mp_int *n1, const mp_int *n2, const mp_int *in_x, const mp_int *in_y, mp_int *out_x, mp_int *out_y, const ECGroup *group) { u8 scalar1[32], scalar2[32]; felem x1, y1, z1, x2, y2, z2, x_affine, y_affine, px, py; mp_err res = MP_OKAY; /* If n2 == NULL, this is just a base-point multiplication. */ if (n2 == NULL) { return ec_GFp_nistp256_base_point_mul(n1, out_x, out_y, group); } /* If n1 == nULL, this is just an arbitary-point multiplication. */ if (n1 == NULL) { return ec_GFp_nistp256_point_mul(n2, in_x, in_y, out_x, out_y, group); } /* If both scalars are zero, then the result is the point at infinity. */ if (mp_cmp_z(n1) == 0 && mp_cmp_z(n2) == 0) { mp_zero(out_x); mp_zero(out_y); return res; } scalar_from_mp_int(scalar1, n1); scalar_from_mp_int(scalar2, n2); MP_CHECKOK(to_montgomery(px, in_x, group)); MP_CHECKOK(to_montgomery(py, in_y, group)); scalar_base_mult(x1, y1, z1, scalar1); scalar_mult(x2, y2, z2, px, py, scalar2); if (mp_cmp_z(n2) == 0) { /* If n2 == 0, then {x2,y2,z2} is zero and the result is just * {x1,y1,z1}. */ } else if (mp_cmp_z(n1) == 0) { /* If n1 == 0, then {x1,y1,z1} is zero and the result is just * {x2,y2,z2}. */ memcpy(x1, x2, sizeof(x2)); memcpy(y1, y2, sizeof(y2)); memcpy(z1, z2, sizeof(z2)); } else { /* This function handles the case where {x1,y1,z1} == {x2,y2,z2}. */ point_add_or_double_vartime(x1, y1, z1, x1, y1, z1, x2, y2, z2); } point_to_affine(x_affine, y_affine, x1, y1, z1); MP_CHECKOK(from_montgomery(out_x, x_affine, group)); MP_CHECKOK(from_montgomery(out_y, y_affine, group)); CLEANUP: return res; } /* Wire in fast point multiplication for named curves. */ mp_err ec_group_set_gfp256_32(ECGroup *group, ECCurveName name) { if (name == ECCurve_NIST_P256) { group->base_point_mul = &ec_GFp_nistp256_base_point_mul; group->point_mul = &ec_GFp_nistp256_point_mul; group->points_mul = &ec_GFp_nistp256_points_mul_vartime; } return MP_OKAY; }
thespooler/nss
lib/freebl/ecl/ecp_256_32.c
C
mpl-2.0
50,400
/* This file is part of SUPPL - the supplemental library for DOS Copyright (C) 1996-2000 Steffen Kaiser This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* $RCSfile: eestrcon.c,v $ $Locker: $ $Name: $ $State: Exp $ char *EStrConcat(int argcnt, ...) Concats up to argcnt strings together and malloc() a buffer that will receive the result. If one of the string == NULL, this string is ignored. On failure, the program is terminated with the "out of memory" error. Return: the malloc'ed buffer ob(ject): EStrConcat su(bsystem): error ty(pe): H sh(ort description): Concat several strings together lo(ng description): Concats several strings together, by using the \tok{StrConcat()} function, and terminates the program on failure with the error message: "Out of memory" pr(erequistes): re(lated to): StrConcat se(condary subsystems): dynstr in(itialized by): wa(rning): bu(gs): va(lue): constructed dynamic string fi(le): eestrcon.c */ #include "initsupl.loc" #ifndef _MICROC_ #include <string.h> #include <stdarg.h> #include <stdlib.h> #endif #include "dynstr.h" #include "msgs.h" #include "suppldbg.h" #ifdef RCS_Version static char const rcsid[] = "$Id: eestrcon.c,v 1.1 2006/06/17 03:25:02 blairdude Exp $"; #endif #ifdef _MICROC_ register char *EStrConcat(int argcnt) { unsigned cnt, *poi; unsigned Xcnt, *Xpoi; unsigned length; char *h, *p; DBG_ENTER1 cnt = nargs(); DBG_ENTER2("EStrConcat", "error") DBG_ARGUMENTS( ("argcnt=%u cnt=%u", argcnt, cnt) ) Xpoi = poi = cnt * 2 - 2 + &argcnt; Xcnt = cnt = min(cnt, *poi); for(length = 1; cnt--;) if(*--poi) length += strlen(*poi); chkHeap if((h = p = malloc(length)) == 0) Esuppl_noMem(); chkHeap while(Xcnt--) if(*--Xpoi) p = stpcpy(p, *Xpoi); chkHeap DBG_RETURN_S( h) } #else /* !_MICROC_ */ char *EStrConcat(int argcnt, ...) { va_list strings; char *p, *s; size_t length, l; DBG_ENTER("EStrConcat", Suppl_error) DBG_ARGUMENTS( ("argcnt=%u cnt=%u", argcnt, argcnt) ) va_start(strings, argcnt); chkHeap p = Estrdup(""); chkHeap length = 1; while(argcnt--) { s = va_arg(strings, char *); if(s && *s) { l = length - 1; Eresize(p, length += strlen(s)); strcpy(p + l, s); } } va_end(strings); chkHeap DBG_RETURN_S( p) } #endif /* _MICROC_ */
joyent/sdcboot
freedos/source/command/suppl/src/eestrcon.c
C
mpl-2.0
2,977
/* Swfdec * Copyright (C) 2007-2008 Benjamin Otte <otte@gnome.org> * * 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., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "swfdec_video.h" #include "swfdec_as_internal.h" #include "swfdec_as_strings.h" #include "swfdec_debug.h" #include "swfdec_net_stream.h" #include "swfdec_player_internal.h" #include "swfdec_sandbox.h" SWFDEC_AS_NATIVE (667, 1, swfdec_video_attach_video) void swfdec_video_attach_video (SwfdecAsContext *cx, SwfdecAsObject *object, guint argc, SwfdecAsValue *argv, SwfdecAsValue *rval) { SwfdecVideoMovie *video; SwfdecAsObject *o; SWFDEC_AS_CHECK (SWFDEC_TYPE_VIDEO_MOVIE, &video, "O", &o); if (o == NULL || !SWFDEC_IS_VIDEO_PROVIDER (o->relay)) { SWFDEC_WARNING ("calling attachVideo without a NetStream object"); swfdec_video_movie_set_provider (video, NULL); return; } swfdec_video_movie_set_provider (video, SWFDEC_VIDEO_PROVIDER (o->relay)); } SWFDEC_AS_NATIVE (667, 2, swfdec_video_clear) void swfdec_video_clear (SwfdecAsContext *cx, SwfdecAsObject *object, guint argc, SwfdecAsValue *argv, SwfdecAsValue *rval) { SwfdecVideoMovie *video; SWFDEC_AS_CHECK (SWFDEC_TYPE_VIDEO_MOVIE, &video, ""); swfdec_video_movie_clear (video); } static void swfdec_video_get_width (SwfdecAsContext *cx, SwfdecAsObject *object, guint argc, SwfdecAsValue *argv, SwfdecAsValue *rval) { SwfdecVideoMovie *video; guint w; SWFDEC_AS_CHECK (SWFDEC_TYPE_VIDEO_MOVIE, &video, ""); if (video->provider) { w = swfdec_video_provider_get_width (video->provider); } else { w = 0; } *rval = swfdec_as_value_from_integer (cx, w); } static void swfdec_video_get_height (SwfdecAsContext *cx, SwfdecAsObject *object, guint argc, SwfdecAsValue *argv, SwfdecAsValue *rval) { SwfdecVideoMovie *video; guint h; SWFDEC_AS_CHECK (SWFDEC_TYPE_VIDEO_MOVIE, &video, ""); if (video->provider) { h = swfdec_video_provider_get_height (video->provider); } else { h = 0; } *rval = swfdec_as_value_from_integer (cx, h); } static void swfdec_video_get_deblocking (SwfdecAsContext *cx, SwfdecAsObject *object, guint argc, SwfdecAsValue *argv, SwfdecAsValue *rval) { SWFDEC_STUB ("Video.deblocking (get)"); *rval = swfdec_as_value_from_integer (cx, 0); } static void swfdec_video_set_deblocking (SwfdecAsContext *cx, SwfdecAsObject *object, guint argc, SwfdecAsValue *argv, SwfdecAsValue *rval) { SWFDEC_STUB ("Video.deblocking (set)"); } static void swfdec_video_get_smoothing (SwfdecAsContext *cx, SwfdecAsObject *object, guint argc, SwfdecAsValue *argv, SwfdecAsValue *rval) { SWFDEC_STUB ("Video.smoothing (get)"); SWFDEC_AS_VALUE_SET_BOOLEAN (rval, TRUE); } static void swfdec_video_set_smoothing (SwfdecAsContext *cx, SwfdecAsObject *object, guint argc, SwfdecAsValue *argv, SwfdecAsValue *rval) { SWFDEC_STUB ("Video.smoothing (set)"); } void swfdec_video_movie_init_properties (SwfdecAsContext *cx) { SwfdecAsValue val; SwfdecAsObject *video, *proto; // FIXME: We should only initialize if the prototype Object has not been // initialized by any object's constructor with native properties // (TextField, TextFormat, XML, XMLNode at least) g_return_if_fail (SWFDEC_IS_AS_CONTEXT (cx)); swfdec_as_object_get_variable (cx->global, SWFDEC_AS_STR_Video, &val); if (!SWFDEC_AS_VALUE_IS_OBJECT (val)) return; video = SWFDEC_AS_VALUE_GET_OBJECT (val); swfdec_as_object_get_variable (video, SWFDEC_AS_STR_prototype, &val); if (!SWFDEC_AS_VALUE_IS_OBJECT (val)) return; proto = SWFDEC_AS_VALUE_GET_OBJECT (val); swfdec_as_object_add_native_variable (proto, SWFDEC_AS_STR_width, swfdec_video_get_width, NULL); swfdec_as_object_add_native_variable (proto, SWFDEC_AS_STR_height, swfdec_video_get_height, NULL); swfdec_as_object_add_native_variable (proto, SWFDEC_AS_STR_deblocking, swfdec_video_get_deblocking, swfdec_video_set_deblocking); swfdec_as_object_add_native_variable (proto, SWFDEC_AS_STR_smoothing, swfdec_video_get_smoothing, swfdec_video_set_smoothing); }
freedesktop-unofficial-mirror/swfdec__swfdec
swfdec/swfdec_video_movie_as.c
C
lgpl-2.1
4,812
/* GTK - The GIMP Toolkit * Copyright (C) 2011 Benjamin Otte <otte@gnome.org> * * 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 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, see <http://www.gnu.org/licenses/>. */ #include "config.h" #include "gtkcssselectorprivate.h" #include <stdlib.h> #include <string.h> #include "gtkcssprovider.h" #include "gtkstylecontextprivate.h" typedef struct _GtkCssSelectorClass GtkCssSelectorClass; typedef gboolean (* GtkCssSelectorForeachFunc) (const GtkCssSelector *selector, const GtkCssMatcher *matcher, gpointer data); struct _GtkCssSelectorClass { const char *name; void (* print) (const GtkCssSelector *selector, GString *string); /* NULL or an iterator that calls func with each submatcher of @matcher. * Potentially no submatcher exissts. * If any @invocation of @func returns %TRUE, the function will immediately * return %TRUE itself. If @func never returns %TRUE (or isn't called at all), * %FALSE will be returned. */ gboolean (* foreach_matcher) (const GtkCssSelector *selector, const GtkCssMatcher *matcher, GtkCssSelectorForeachFunc func, gpointer data); gboolean (* match_one) (const GtkCssSelector *selector, const GtkCssMatcher *matcher); GtkCssChange (* get_change) (const GtkCssSelector *selector, GtkCssChange previous_change); void (* add_specificity) (const GtkCssSelector *selector, guint *ids, guint *classes, guint *elements); guint (* hash_one) (const GtkCssSelector *selector); int (* compare_one) (const GtkCssSelector *a, const GtkCssSelector *b); guint is_simple :1; }; typedef struct { GType type; const char *name; } TypeReference; typedef enum { POSITION_FORWARD, POSITION_BACKWARD, POSITION_ONLY, POSITION_SORTED } PositionType; #define POSITION_TYPE_BITS 4 #define POSITION_NUMBER_BITS ((sizeof (gpointer) * 8 - POSITION_TYPE_BITS) / 2) union _GtkCssSelector { const GtkCssSelectorClass *class; /* type of check this selector does */ struct { const GtkCssSelectorClass *class; const char *name; /* interned */ } id; struct { const GtkCssSelectorClass *class; const char *name; /* interned */ GtkRegionFlags flags; } region; struct { const GtkCssSelectorClass *class; GQuark style_class; } style_class; struct { const GtkCssSelectorClass *class; const TypeReference *reference; } name; struct { const GtkCssSelectorClass *class; GtkStateFlags state; } state; struct { const GtkCssSelectorClass *class; PositionType type :POSITION_TYPE_BITS; gssize a :POSITION_NUMBER_BITS; gssize b :POSITION_NUMBER_BITS; } position; }; #define GTK_CSS_SELECTOR_TREE_EMPTY_OFFSET G_MAXINT32 struct _GtkCssSelectorTree { GtkCssSelector selector; gint32 parent_offset; gint32 previous_offset; gint32 sibling_offset; gint32 matches_offset; /* pointers that we return as matches if selector matches */ }; static gboolean gtk_css_selector_equal (const GtkCssSelector *a, const GtkCssSelector *b) { return a->class == b->class && a->class->compare_one (a, b) == 0; } static guint gtk_css_selector_hash_one (const GtkCssSelector *selector) { return GPOINTER_TO_UINT (selector->class) ^ selector->class->hash_one (selector); } static gpointer * gtk_css_selector_tree_get_matches (const GtkCssSelectorTree *tree) { if (tree->matches_offset == GTK_CSS_SELECTOR_TREE_EMPTY_OFFSET) return NULL; return (gpointer *) ((guint8 *)tree + tree->matches_offset); } static void gtk_css_selector_tree_found_match (const GtkCssSelectorTree *tree, GHashTable *res) { int i; gpointer *matches; matches = gtk_css_selector_tree_get_matches (tree); if (matches) { for (i = 0; matches[i] != NULL; i++) g_hash_table_insert (res, matches[i], matches[i]); } } static gboolean gtk_css_selector_match (const GtkCssSelector *selector, const GtkCssMatcher *matcher) { return selector->class->match_one (selector, matcher); } static gboolean gtk_css_selector_foreach (const GtkCssSelector *selector, const GtkCssMatcher *matcher, GtkCssSelectorForeachFunc func, gpointer data) { return selector->class->foreach_matcher (selector, matcher, func, data); } static int gtk_css_selector_compare_one (const GtkCssSelector *a, const GtkCssSelector *b) { if (a->class != b->class) return strcmp (a->class->name, b->class->name); else return a->class->compare_one (a, b); } static const GtkCssSelector * gtk_css_selector_previous (const GtkCssSelector *selector) { selector = selector + 1; return selector->class ? selector : NULL; } static const GtkCssSelectorTree * gtk_css_selector_tree_at_offset (const GtkCssSelectorTree *tree, gint32 offset) { if (offset == GTK_CSS_SELECTOR_TREE_EMPTY_OFFSET) return NULL; return (GtkCssSelectorTree *) ((guint8 *)tree + offset); } static const GtkCssSelectorTree * gtk_css_selector_tree_get_parent (const GtkCssSelectorTree *tree) { return gtk_css_selector_tree_at_offset (tree, tree->parent_offset); } static const GtkCssSelectorTree * gtk_css_selector_tree_get_previous (const GtkCssSelectorTree *tree) { return gtk_css_selector_tree_at_offset (tree, tree->previous_offset); } static const GtkCssSelectorTree * gtk_css_selector_tree_get_sibling (const GtkCssSelectorTree *tree) { return gtk_css_selector_tree_at_offset (tree, tree->sibling_offset); } /* DEFAULTS */ static void gtk_css_selector_default_add_specificity (const GtkCssSelector *selector, guint *ids, guint *classes, guint *elements) { /* no specificity changes */ } static gboolean gtk_css_selector_default_foreach_matcher (const GtkCssSelector *selector, const GtkCssMatcher *matcher, GtkCssSelectorForeachFunc func, gpointer data) { return func (selector, matcher, data); } static gboolean gtk_css_selector_default_match_one (const GtkCssSelector *selector, const GtkCssMatcher *matcher) { return TRUE; } static guint gtk_css_selector_default_hash_one (const GtkCssSelector *selector) { return 0; } static int gtk_css_selector_default_compare_one (const GtkCssSelector *a, const GtkCssSelector *b) { return 0; } /* DESCENDANT */ static void gtk_css_selector_descendant_print (const GtkCssSelector *selector, GString *string) { g_string_append_c (string, ' '); } static gboolean gtk_css_selector_descendant_foreach_matcher (const GtkCssSelector *selector, const GtkCssMatcher *matcher, GtkCssSelectorForeachFunc func, gpointer data) { GtkCssMatcher ancestor; while (_gtk_css_matcher_get_parent (&ancestor, matcher)) { matcher = &ancestor; if (func (selector, &ancestor, data)) return TRUE; /* any matchers are dangerous here, as we may loop forever, but we can terminate now as all possible matches have already been added */ if (_gtk_css_matcher_matches_any (matcher)) break; } return FALSE; } static GtkCssChange gtk_css_selector_descendant_get_change (const GtkCssSelector *selector, GtkCssChange previous_change) { return _gtk_css_change_for_child (previous_change); } static const GtkCssSelectorClass GTK_CSS_SELECTOR_DESCENDANT = { "descendant", gtk_css_selector_descendant_print, gtk_css_selector_descendant_foreach_matcher, gtk_css_selector_default_match_one, gtk_css_selector_descendant_get_change, gtk_css_selector_default_add_specificity, gtk_css_selector_default_hash_one, gtk_css_selector_default_compare_one, FALSE }; /* DESCENDANT FOR REGION */ static void gtk_css_selector_descendant_for_region_print (const GtkCssSelector *selector, GString *string) { g_string_append_c (string, ' '); } static gboolean gtk_css_selector_descendant_for_region_foreach_matcher (const GtkCssSelector *selector, const GtkCssMatcher *matcher, GtkCssSelectorForeachFunc func, gpointer data) { GtkCssMatcher ancestor; if (_gtk_css_matcher_has_regions (matcher)) { if (func (selector, matcher, data)) return TRUE; } while (_gtk_css_matcher_get_parent (&ancestor, matcher)) { matcher = &ancestor; if (func (selector, matcher, data)) return TRUE; /* any matchers are dangerous here, as we may loop forever, but we can terminate now as all possible matches have already been added */ if (_gtk_css_matcher_matches_any (matcher)) break; } return FALSE; } static GtkCssChange gtk_css_selector_descendant_for_region_get_change (const GtkCssSelector *selector, GtkCssChange previous_change) { return previous_change | _gtk_css_change_for_child (previous_change); } static const GtkCssSelectorClass GTK_CSS_SELECTOR_DESCENDANT_FOR_REGION = { "descendant_for_region", gtk_css_selector_descendant_for_region_print, gtk_css_selector_descendant_for_region_foreach_matcher, gtk_css_selector_default_match_one, gtk_css_selector_descendant_for_region_get_change, gtk_css_selector_default_add_specificity, gtk_css_selector_default_hash_one, gtk_css_selector_default_compare_one, FALSE }; /* CHILD */ static void gtk_css_selector_child_print (const GtkCssSelector *selector, GString *string) { g_string_append (string, " > "); } static gboolean gtk_css_selector_child_foreach_matcher (const GtkCssSelector *selector, const GtkCssMatcher *matcher, GtkCssSelectorForeachFunc func, gpointer data) { GtkCssMatcher parent; if (!_gtk_css_matcher_get_parent (&parent, matcher)) return FALSE; return func (selector, &parent, data); } static GtkCssChange gtk_css_selector_child_get_change (const GtkCssSelector *selector, GtkCssChange previous_change) { return _gtk_css_change_for_child (previous_change); } static const GtkCssSelectorClass GTK_CSS_SELECTOR_CHILD = { "child", gtk_css_selector_child_print, gtk_css_selector_child_foreach_matcher, gtk_css_selector_default_match_one, gtk_css_selector_child_get_change, gtk_css_selector_default_add_specificity, gtk_css_selector_default_hash_one, gtk_css_selector_default_compare_one, FALSE }; /* SIBLING */ static void gtk_css_selector_sibling_print (const GtkCssSelector *selector, GString *string) { g_string_append (string, " ~ "); } static gboolean gtk_css_selector_sibling_foreach_matcher (const GtkCssSelector *selector, const GtkCssMatcher *matcher, GtkCssSelectorForeachFunc func, gpointer data) { GtkCssMatcher previous; while (_gtk_css_matcher_get_previous (&previous, matcher)) { matcher = &previous; if (func (selector, matcher, data)) return TRUE; /* any matchers are dangerous here, as we may loop forever, but we can terminate now as all possible matches have already been added */ if (_gtk_css_matcher_matches_any (matcher)) break; } return FALSE; } static GtkCssChange gtk_css_selector_sibling_get_change (const GtkCssSelector *selector, GtkCssChange previous_change) { return _gtk_css_change_for_sibling (previous_change); } static const GtkCssSelectorClass GTK_CSS_SELECTOR_SIBLING = { "sibling", gtk_css_selector_sibling_print, gtk_css_selector_sibling_foreach_matcher, gtk_css_selector_default_match_one, gtk_css_selector_sibling_get_change, gtk_css_selector_default_add_specificity, gtk_css_selector_default_hash_one, gtk_css_selector_default_compare_one, FALSE }; /* ADJACENT */ static void gtk_css_selector_adjacent_print (const GtkCssSelector *selector, GString *string) { g_string_append (string, " + "); } static gboolean gtk_css_selector_adjacent_foreach_matcher (const GtkCssSelector *selector, const GtkCssMatcher *matcher, GtkCssSelectorForeachFunc func, gpointer data) { GtkCssMatcher previous; if (!_gtk_css_matcher_get_previous (&previous, matcher)) return FALSE; return func (selector, &previous, data); } static GtkCssChange gtk_css_selector_adjacent_get_change (const GtkCssSelector *selector, GtkCssChange previous_change) { return _gtk_css_change_for_sibling (previous_change); } static const GtkCssSelectorClass GTK_CSS_SELECTOR_ADJACENT = { "adjacent", gtk_css_selector_adjacent_print, gtk_css_selector_adjacent_foreach_matcher, gtk_css_selector_default_match_one, gtk_css_selector_adjacent_get_change, gtk_css_selector_default_add_specificity, gtk_css_selector_default_hash_one, gtk_css_selector_default_compare_one, FALSE }; /* SIMPLE SELECTOR DEFINE */ #define DEFINE_SIMPLE_SELECTOR(n, \ c, \ print_func, \ match_func, \ hash_func, \ comp_func, \ increase_id_specificity, \ increase_class_specificity, \ increase_element_specificity) \ static void \ gtk_css_selector_ ## n ## _print (const GtkCssSelector *selector, \ GString *string) \ { \ print_func (selector, string); \ } \ \ static void \ gtk_css_selector_not_ ## n ## _print (const GtkCssSelector *selector, \ GString *string) \ { \ g_string_append (string, ":not("); \ print_func (selector, string); \ g_string_append (string, ")"); \ } \ \ static gboolean \ gtk_css_selector_not_ ## n ## _match_one (const GtkCssSelector *selector, \ const GtkCssMatcher *matcher) \ { \ return !match_func (selector, matcher); \ } \ \ static GtkCssChange \ gtk_css_selector_ ## n ## _get_change (const GtkCssSelector *selector, GtkCssChange previous_change) \ { \ return previous_change | GTK_CSS_CHANGE_ ## c; \ } \ \ static void \ gtk_css_selector_ ## n ## _add_specificity (const GtkCssSelector *selector, \ guint *ids, \ guint *classes, \ guint *elements) \ { \ if (increase_id_specificity) \ (*ids)++; \ if (increase_class_specificity) \ (*classes)++; \ if (increase_element_specificity) \ (*elements)++; \ } \ \ static const GtkCssSelectorClass GTK_CSS_SELECTOR_ ## c = { \ G_STRINGIFY(n), \ gtk_css_selector_ ## n ## _print, \ gtk_css_selector_default_foreach_matcher, \ match_func, \ gtk_css_selector_ ## n ## _get_change, \ gtk_css_selector_ ## n ## _add_specificity, \ hash_func, \ comp_func, \ TRUE \ };\ \ static const GtkCssSelectorClass GTK_CSS_SELECTOR_NOT_ ## c = { \ "not_" G_STRINGIFY(n), \ gtk_css_selector_not_ ## n ## _print, \ gtk_css_selector_default_foreach_matcher, \ gtk_css_selector_not_ ## n ## _match_one, \ gtk_css_selector_ ## n ## _get_change, \ gtk_css_selector_ ## n ## _add_specificity, \ hash_func, \ comp_func, \ TRUE \ }; /* ANY */ static void print_any (const GtkCssSelector *selector, GString *string) { g_string_append_c (string, '*'); } static gboolean match_any (const GtkCssSelector *selector, const GtkCssMatcher *matcher) { return TRUE; } #undef GTK_CSS_CHANGE_ANY #define GTK_CSS_CHANGE_ANY 0 DEFINE_SIMPLE_SELECTOR(any, ANY, print_any, match_any, gtk_css_selector_default_hash_one, gtk_css_selector_default_compare_one, FALSE, FALSE, FALSE) #undef GTK_CSS_CHANGE_ANY /* NAME */ static GHashTable *type_refs_ht = NULL; static guint type_refs_last_serial = 0; static TypeReference * get_type_reference (const char *name) { TypeReference *ref; if (type_refs_ht == NULL) type_refs_ht = g_hash_table_new (g_str_hash, g_str_equal); ref = g_hash_table_lookup (type_refs_ht, name); if (ref != NULL) return ref; ref = g_slice_new (TypeReference); ref->name = g_intern_string (name); ref->type = g_type_from_name (ref->name); g_hash_table_insert (type_refs_ht, (gpointer)ref->name, ref); return ref; } static void update_type_references (void) { GHashTableIter iter; guint serial; gpointer value; serial = g_type_get_type_registration_serial (); if (serial == type_refs_last_serial) return; type_refs_last_serial = serial; if (type_refs_ht == NULL) return; g_hash_table_iter_init (&iter, type_refs_ht); while (g_hash_table_iter_next (&iter, NULL, &value)) { TypeReference *ref = value; if (ref->type == G_TYPE_INVALID) ref->type = g_type_from_name (ref->name); } } static void print_name (const GtkCssSelector *selector, GString *string) { g_string_append (string, selector->name.reference->name); } static gboolean match_name (const GtkCssSelector *selector, const GtkCssMatcher *matcher) { return _gtk_css_matcher_has_type (matcher, selector->name.reference->type); } static guint hash_name (const GtkCssSelector *a) { return g_str_hash (a->name.reference->name); } static int comp_name (const GtkCssSelector *a, const GtkCssSelector *b) { return strcmp (a->name.reference->name, b->name.reference->name); } DEFINE_SIMPLE_SELECTOR(name, NAME, print_name, match_name, hash_name, comp_name, FALSE, FALSE, TRUE) /* REGION */ static void gtk_css_selector_region_print (const GtkCssSelector *selector, GString *string) { char *region_names[] = { "even", "odd", "first-child", "last-child", "only-child", "sorted" }; guint i; g_string_append (string, selector->region.name); for (i = 0; i < G_N_ELEMENTS (region_names); i++) { if (selector->region.flags & (1 << i)) { g_string_append_c (string, ':'); g_string_append (string, region_names[i]); } } } static gboolean gtk_css_selector_region_match_one (const GtkCssSelector *selector, const GtkCssMatcher *matcher) { return _gtk_css_matcher_has_region (matcher, selector->region.name, selector->region.flags); } static GtkCssChange gtk_css_selector_region_get_change (const GtkCssSelector *selector, GtkCssChange previous_change) { return previous_change | GTK_CSS_CHANGE_REGION; } static guint count_bits (guint n) { guint result = 0; for (result = 0; n != 0; result++) n &= n - 1; return result; } static void gtk_css_selector_region_add_specificity (const GtkCssSelector *selector, guint *ids, guint *classes, guint *elements) { (*elements)++; (*classes) += count_bits (selector->region.flags); } static guint gtk_css_selector_region_hash_one (const GtkCssSelector *a) { return g_str_hash (a->region.name) ^ a->region.flags; } static int gtk_css_selector_region_compare_one (const GtkCssSelector *a, const GtkCssSelector *b) { int diff; diff = strcmp (a->region.name, b->region.name); if (diff) return diff; return a->region.flags - b->region.flags; } static const GtkCssSelectorClass GTK_CSS_SELECTOR_REGION = { "region", gtk_css_selector_region_print, gtk_css_selector_default_foreach_matcher, gtk_css_selector_region_match_one, gtk_css_selector_region_get_change, gtk_css_selector_region_add_specificity, gtk_css_selector_region_hash_one, gtk_css_selector_region_compare_one, TRUE }; /* CLASS */ static void print_class (const GtkCssSelector *selector, GString *string) { g_string_append_c (string, '.'); g_string_append (string, g_quark_to_string (selector->style_class.style_class)); } static gboolean match_class (const GtkCssSelector *selector, const GtkCssMatcher *matcher) { return _gtk_css_matcher_has_class (matcher, selector->style_class.style_class); } static guint hash_class (const GtkCssSelector *a) { return g_str_hash (g_quark_to_string (a->style_class.style_class)); } static int comp_class (const GtkCssSelector *a, const GtkCssSelector *b) { return strcmp (g_quark_to_string (a->style_class.style_class), g_quark_to_string (b->style_class.style_class)); } DEFINE_SIMPLE_SELECTOR(class, CLASS, print_class, match_class, hash_class, comp_class, FALSE, TRUE, FALSE) /* ID */ static void print_id (const GtkCssSelector *selector, GString *string) { g_string_append_c (string, '#'); g_string_append (string, selector->id.name); } static gboolean match_id (const GtkCssSelector *selector, const GtkCssMatcher *matcher) { return _gtk_css_matcher_has_id (matcher, selector->id.name); } static guint hash_id (const GtkCssSelector *a) { return g_str_hash (a->id.name); } static int comp_id (const GtkCssSelector *a, const GtkCssSelector *b) { return strcmp (a->id.name, b->id.name); } DEFINE_SIMPLE_SELECTOR(id, ID, print_id, match_id, hash_id, comp_id, TRUE, FALSE, FALSE) /* PSEUDOCLASS FOR STATE */ static void print_pseudoclass_state (const GtkCssSelector *selector, GString *string) { static const char * state_names[] = { "active", "hover", "selected", "insensitive", "inconsistent", "focus", "backdrop", "dir(ltr)", "dir(rtl)", "link", "visited", "checked" }; guint i; g_string_append_c (string, ':'); for (i = 0; i < G_N_ELEMENTS (state_names); i++) { if (selector->state.state == (1 << i)) { g_string_append (string, state_names[i]); return; } } g_assert_not_reached (); } static gboolean match_pseudoclass_state (const GtkCssSelector *selector, const GtkCssMatcher *matcher) { return (_gtk_css_matcher_get_state (matcher) & selector->state.state) == selector->state.state; } static guint hash_pseudoclass_state (const GtkCssSelector *selector) { return selector->state.state; } static int comp_pseudoclass_state (const GtkCssSelector *a, const GtkCssSelector *b) { return a->state.state - b->state.state; } #define GTK_CSS_CHANGE_PSEUDOCLASS_STATE GTK_CSS_CHANGE_STATE DEFINE_SIMPLE_SELECTOR(pseudoclass_state, PSEUDOCLASS_STATE, print_pseudoclass_state, match_pseudoclass_state, hash_pseudoclass_state, comp_pseudoclass_state, FALSE, TRUE, FALSE) #undef GTK_CSS_CHANGE_PSEUDOCLASS_STATE /* PSEUDOCLASS FOR POSITION */ static void print_pseudoclass_position (const GtkCssSelector *selector, GString *string) { switch (selector->position.type) { case POSITION_FORWARD: if (selector->position.a == 0) { if (selector->position.b == 1) g_string_append (string, ":first-child"); else g_string_append_printf (string, ":nth-child(%d)", selector->position.b); } else if (selector->position.a == 2 && selector->position.b == 0) g_string_append (string, ":nth-child(even)"); else if (selector->position.a == 2 && selector->position.b == 1) g_string_append (string, ":nth-child(odd)"); else { g_string_append (string, ":nth-child("); if (selector->position.a == 1) g_string_append (string, "n"); else if (selector->position.a == -1) g_string_append (string, "-n"); else g_string_append_printf (string, "%dn", selector->position.a); if (selector->position.b > 0) g_string_append_printf (string, "+%d)", selector->position.b); else if (selector->position.b < 0) g_string_append_printf (string, "%d)", selector->position.b); else g_string_append (string, ")"); } break; case POSITION_BACKWARD: if (selector->position.a == 0) { if (selector->position.b == 1) g_string_append (string, ":last-child"); else g_string_append_printf (string, ":nth-last-child(%d)", selector->position.b); } else if (selector->position.a == 2 && selector->position.b == 0) g_string_append (string, ":nth-last-child(even)"); else if (selector->position.a == 2 && selector->position.b == 1) g_string_append (string, ":nth-last-child(odd)"); else { g_string_append (string, ":nth-last-child("); if (selector->position.a == 1) g_string_append (string, "n"); else if (selector->position.a == -1) g_string_append (string, "-n"); else g_string_append_printf (string, "%dn", selector->position.a); if (selector->position.b > 0) g_string_append_printf (string, "+%d)", selector->position.b); else if (selector->position.b < 0) g_string_append_printf (string, "%d)", selector->position.b); else g_string_append (string, ")"); } break; case POSITION_ONLY: g_string_append (string, ":only-child"); break; case POSITION_SORTED: g_string_append (string, ":sorted"); break; default: g_assert_not_reached (); break; } } static gboolean match_pseudoclass_position (const GtkCssSelector *selector, const GtkCssMatcher *matcher) { switch (selector->position.type) { case POSITION_FORWARD: if (!_gtk_css_matcher_has_position (matcher, TRUE, selector->position.a, selector->position.b)) return FALSE; break; case POSITION_BACKWARD: if (!_gtk_css_matcher_has_position (matcher, FALSE, selector->position.a, selector->position.b)) return FALSE; break; case POSITION_ONLY: if (!_gtk_css_matcher_has_position (matcher, TRUE, 0, 1) || !_gtk_css_matcher_has_position (matcher, FALSE, 0, 1)) return FALSE; break; case POSITION_SORTED: return FALSE; default: g_assert_not_reached (); return FALSE; } return TRUE; } static guint hash_pseudoclass_position (const GtkCssSelector *a) { return (((a->position.type << POSITION_NUMBER_BITS) | a->position.a) << POSITION_NUMBER_BITS) | a->position.b; } static int comp_pseudoclass_position (const GtkCssSelector *a, const GtkCssSelector *b) { int diff; diff = a->position.type - b->position.type; if (diff) return diff; diff = a->position.a - b->position.a; if (diff) return diff; return a->position.b - b->position.b; } static GtkCssChange change_pseudoclass_position (const GtkCssSelector *selector) { switch (selector->position.type) { case POSITION_FORWARD: if (selector->position.a == 0 && selector->position.b == 1) return GTK_CSS_CHANGE_FIRST_CHILD; else return GTK_CSS_CHANGE_NTH_CHILD; case POSITION_BACKWARD: if (selector->position.a == 0 && selector->position.b == 1) return GTK_CSS_CHANGE_LAST_CHILD; else return GTK_CSS_CHANGE_NTH_LAST_CHILD; case POSITION_ONLY: return GTK_CSS_CHANGE_FIRST_CHILD | GTK_CSS_CHANGE_LAST_CHILD; default: g_assert_not_reached (); case POSITION_SORTED: return 0; } } #define GTK_CSS_CHANGE_PSEUDOCLASS_POSITION change_pseudoclass_position(selector) DEFINE_SIMPLE_SELECTOR(pseudoclass_position, PSEUDOCLASS_POSITION, print_pseudoclass_position, match_pseudoclass_position, hash_pseudoclass_position, comp_pseudoclass_position, FALSE, TRUE, FALSE) #undef GTK_CSS_CHANGE_PSEUDOCLASS_POSITION /* API */ static guint gtk_css_selector_size (const GtkCssSelector *selector) { guint size = 0; while (selector) { selector = gtk_css_selector_previous (selector); size++; } return size; } static GtkCssSelector * gtk_css_selector_new (const GtkCssSelectorClass *class, GtkCssSelector *selector) { guint size; size = gtk_css_selector_size (selector); selector = g_realloc (selector, sizeof (GtkCssSelector) * (size + 1) + sizeof (gpointer)); if (size == 0) selector[1].class = NULL; else memmove (selector + 1, selector, sizeof (GtkCssSelector) * size + sizeof (gpointer)); memset (selector, 0, sizeof (GtkCssSelector)); selector->class = class; return selector; } static GtkCssSelector * parse_selector_class (GtkCssParser *parser, GtkCssSelector *selector, gboolean negate) { char *name; name = _gtk_css_parser_try_name (parser, FALSE); if (name == NULL) { _gtk_css_parser_error (parser, "Expected a valid name for class"); if (selector) _gtk_css_selector_free (selector); return NULL; } selector = gtk_css_selector_new (negate ? &GTK_CSS_SELECTOR_NOT_CLASS : &GTK_CSS_SELECTOR_CLASS, selector); selector->style_class.style_class = g_quark_from_string (name); g_free (name); return selector; } static GtkCssSelector * parse_selector_id (GtkCssParser *parser, GtkCssSelector *selector, gboolean negate) { char *name; name = _gtk_css_parser_try_name (parser, FALSE); if (name == NULL) { _gtk_css_parser_error (parser, "Expected a valid name for id"); if (selector) _gtk_css_selector_free (selector); return NULL; } selector = gtk_css_selector_new (negate ? &GTK_CSS_SELECTOR_NOT_ID : &GTK_CSS_SELECTOR_ID, selector); selector->id.name = g_intern_string (name); g_free (name); return selector; } static GtkCssSelector * parse_selector_pseudo_class_nth_child (GtkCssParser *parser, GtkCssSelector *selector, PositionType type, gboolean negate) { int a, b; if (!_gtk_css_parser_try (parser, "(", TRUE)) { _gtk_css_parser_error (parser, "Missing opening bracket for pseudo-class"); if (selector) _gtk_css_selector_free (selector); return NULL; } if (_gtk_css_parser_try (parser, "even", TRUE)) { a = 2; b = 0; } else if (_gtk_css_parser_try (parser, "odd", TRUE)) { a = 2; b = 1; } else if (type == POSITION_FORWARD && _gtk_css_parser_try (parser, "first", TRUE)) { a = 0; b = 1; } else if (type == POSITION_FORWARD && _gtk_css_parser_try (parser, "last", TRUE)) { a = 0; b = 1; type = POSITION_BACKWARD; } else { int multiplier; if (_gtk_css_parser_try (parser, "+", TRUE)) multiplier = 1; else if (_gtk_css_parser_try (parser, "-", TRUE)) multiplier = -1; else multiplier = 1; if (_gtk_css_parser_try_int (parser, &a)) { if (a < 0) { _gtk_css_parser_error (parser, "Expected an integer"); if (selector) _gtk_css_selector_free (selector); return NULL; } a *= multiplier; } else if (_gtk_css_parser_has_prefix (parser, "n")) { a = multiplier; } else { _gtk_css_parser_error (parser, "Expected an integer"); if (selector) _gtk_css_selector_free (selector); return NULL; } if (_gtk_css_parser_try (parser, "n", TRUE)) { if (_gtk_css_parser_try (parser, "+", TRUE)) multiplier = 1; else if (_gtk_css_parser_try (parser, "-", TRUE)) multiplier = -1; else multiplier = 1; if (_gtk_css_parser_try_int (parser, &b)) { if (b < 0) { _gtk_css_parser_error (parser, "Expected an integer"); if (selector) _gtk_css_selector_free (selector); return NULL; } } else b = 0; b *= multiplier; } else { b = a; a = 0; } } if (!_gtk_css_parser_try (parser, ")", FALSE)) { _gtk_css_parser_error (parser, "Missing closing bracket for pseudo-class"); if (selector) _gtk_css_selector_free (selector); return NULL; } selector = gtk_css_selector_new (negate ? &GTK_CSS_SELECTOR_NOT_PSEUDOCLASS_POSITION : &GTK_CSS_SELECTOR_PSEUDOCLASS_POSITION, selector); selector->position.type = type; selector->position.a = a; selector->position.b = b; return selector; } static GtkRegionFlags try_parse_selector_region_pseudo_class (GtkCssParser *parser) { static const struct { const char *name; GtkRegionFlags flags; } region_flags[] = { { "even", GTK_REGION_EVEN }, { "odd", GTK_REGION_ODD }, { "first-child", GTK_REGION_FIRST }, { "last-child", GTK_REGION_LAST }, { "only-child", GTK_REGION_ONLY }, { "sorted", GTK_REGION_SORTED } }; guint i; for (i = 0; i < G_N_ELEMENTS (region_flags); i++) { if (_gtk_css_parser_try (parser, region_flags[i].name, FALSE)) return region_flags[i].flags; } return 0; } static GtkCssSelector * parse_selector_pseudo_class (GtkCssParser *parser, GtkCssSelector *selector, gboolean negate) { static const struct { const char *name; GtkStateFlags state_flag; PositionType position_type; int position_a; int position_b; } pseudo_classes[] = { { "first-child", 0, POSITION_FORWARD, 0, 1 }, { "last-child", 0, POSITION_BACKWARD, 0, 1 }, { "only-child", 0, POSITION_ONLY, 0, 0 }, { "sorted", 0, POSITION_SORTED, 0, 0 }, { "active", GTK_STATE_FLAG_ACTIVE, }, { "prelight", GTK_STATE_FLAG_PRELIGHT, }, { "hover", GTK_STATE_FLAG_PRELIGHT, }, { "selected", GTK_STATE_FLAG_SELECTED, }, { "insensitive", GTK_STATE_FLAG_INSENSITIVE, }, { "inconsistent", GTK_STATE_FLAG_INCONSISTENT, }, { "focused", GTK_STATE_FLAG_FOCUSED, }, { "focus", GTK_STATE_FLAG_FOCUSED, }, { "backdrop", GTK_STATE_FLAG_BACKDROP, }, { "dir(ltr)", GTK_STATE_FLAG_DIR_LTR, }, { "dir(rtl)", GTK_STATE_FLAG_DIR_RTL, }, { "link", GTK_STATE_FLAG_LINK, }, { "visited", GTK_STATE_FLAG_VISITED, }, { "checked", GTK_STATE_FLAG_CHECKED, } }; guint i; if (_gtk_css_parser_try (parser, "nth-child", FALSE)) return parse_selector_pseudo_class_nth_child (parser, selector, POSITION_FORWARD, negate); else if (_gtk_css_parser_try (parser, "nth-last-child", FALSE)) return parse_selector_pseudo_class_nth_child (parser, selector, POSITION_BACKWARD, negate); for (i = 0; i < G_N_ELEMENTS (pseudo_classes); i++) { if (_gtk_css_parser_try (parser, pseudo_classes[i].name, FALSE)) { if (pseudo_classes[i].state_flag) { selector = gtk_css_selector_new (negate ? &GTK_CSS_SELECTOR_NOT_PSEUDOCLASS_STATE : &GTK_CSS_SELECTOR_PSEUDOCLASS_STATE, selector); selector->state.state = pseudo_classes[i].state_flag; } else { selector = gtk_css_selector_new (negate ? &GTK_CSS_SELECTOR_NOT_PSEUDOCLASS_POSITION : &GTK_CSS_SELECTOR_PSEUDOCLASS_POSITION, selector); selector->position.type = pseudo_classes[i].position_type; selector->position.a = pseudo_classes[i].position_a; selector->position.b = pseudo_classes[i].position_b; } return selector; } } _gtk_css_parser_error (parser, "Missing name of pseudo-class"); if (selector) _gtk_css_selector_free (selector); return NULL; } static GtkCssSelector * parse_selector_negation (GtkCssParser *parser, GtkCssSelector *selector) { char *name; name = _gtk_css_parser_try_ident (parser, FALSE); if (name) { selector = gtk_css_selector_new (&GTK_CSS_SELECTOR_NOT_NAME, selector); selector->name.reference = get_type_reference (name); g_free (name); } else if (_gtk_css_parser_try (parser, "*", FALSE)) selector = gtk_css_selector_new (&GTK_CSS_SELECTOR_NOT_ANY, selector); else if (_gtk_css_parser_try (parser, "#", FALSE)) selector = parse_selector_id (parser, selector, TRUE); else if (_gtk_css_parser_try (parser, ".", FALSE)) selector = parse_selector_class (parser, selector, TRUE); else if (_gtk_css_parser_try (parser, ":", FALSE)) selector = parse_selector_pseudo_class (parser, selector, TRUE); else { _gtk_css_parser_error (parser, "Not a valid selector for :not()"); if (selector) _gtk_css_selector_free (selector); return NULL; } _gtk_css_parser_skip_whitespace (parser); if (!_gtk_css_parser_try (parser, ")", FALSE)) { _gtk_css_parser_error (parser, "Missing closing bracket for :not()"); if (selector) _gtk_css_selector_free (selector); return NULL; } return selector; } static GtkCssSelector * parse_simple_selector (GtkCssParser *parser, GtkCssSelector *selector) { gboolean parsed_something = FALSE; guint region_offset = 0; char *name; name = _gtk_css_parser_try_ident (parser, FALSE); if (name) { if (_gtk_style_context_check_region_name (name)) { selector = gtk_css_selector_new (&GTK_CSS_SELECTOR_REGION, selector); selector->region.name = g_intern_string (name); region_offset = gtk_css_selector_size (selector); } else { selector = gtk_css_selector_new (&GTK_CSS_SELECTOR_NAME, selector); selector->name.reference = get_type_reference (name); } g_free (name); parsed_something = TRUE; } else if (_gtk_css_parser_try (parser, "*", FALSE)) { selector = gtk_css_selector_new (&GTK_CSS_SELECTOR_ANY, selector); parsed_something = TRUE; } do { if (_gtk_css_parser_try (parser, "#", FALSE)) selector = parse_selector_id (parser, selector, FALSE); else if (_gtk_css_parser_try (parser, ".", FALSE)) selector = parse_selector_class (parser, selector, FALSE); else if (_gtk_css_parser_try (parser, ":not(", TRUE)) selector = parse_selector_negation (parser, selector); else if (_gtk_css_parser_try (parser, ":", FALSE)) { GtkRegionFlags region_flags; if (region_offset && (region_flags = try_parse_selector_region_pseudo_class (parser))) { selector[gtk_css_selector_size (selector) - region_offset].region.flags |= region_flags; } else { selector = parse_selector_pseudo_class (parser, selector, FALSE); } } else if (!parsed_something) { _gtk_css_parser_error (parser, "Expected a valid selector"); if (selector) _gtk_css_selector_free (selector); return NULL; } else break; parsed_something = TRUE; } while (selector && !_gtk_css_parser_is_eof (parser)); _gtk_css_parser_skip_whitespace (parser); /* This is the big region hack where we change the descendant matcher * to a version that respects regions. */ if (selector) { if ((selector[0].class == &GTK_CSS_SELECTOR_ANY || selector[0].class == &GTK_CSS_SELECTOR_REGION) && selector[1].class == &GTK_CSS_SELECTOR_DESCENDANT) selector[1].class = &GTK_CSS_SELECTOR_DESCENDANT_FOR_REGION; } return selector; } GtkCssSelector * _gtk_css_selector_parse (GtkCssParser *parser) { GtkCssSelector *selector = NULL; while ((selector = parse_simple_selector (parser, selector)) && !_gtk_css_parser_is_eof (parser) && !_gtk_css_parser_begins_with (parser, ',') && !_gtk_css_parser_begins_with (parser, '{')) { if (_gtk_css_parser_try (parser, "+", TRUE)) selector = gtk_css_selector_new (&GTK_CSS_SELECTOR_ADJACENT, selector); else if (_gtk_css_parser_try (parser, "~", TRUE)) selector = gtk_css_selector_new (&GTK_CSS_SELECTOR_SIBLING, selector); else if (_gtk_css_parser_try (parser, ">", TRUE)) selector = gtk_css_selector_new (&GTK_CSS_SELECTOR_CHILD, selector); else selector = gtk_css_selector_new (&GTK_CSS_SELECTOR_DESCENDANT, selector); } return selector; } void _gtk_css_selector_free (GtkCssSelector *selector) { g_return_if_fail (selector != NULL); g_free (selector); } void _gtk_css_selector_print (const GtkCssSelector *selector, GString * str) { const GtkCssSelector *previous; g_return_if_fail (selector != NULL); previous = gtk_css_selector_previous (selector); if (previous) _gtk_css_selector_print (previous, str); selector->class->print (selector, str); } char * _gtk_css_selector_to_string (const GtkCssSelector *selector) { GString *string; g_return_val_if_fail (selector != NULL, NULL); string = g_string_new (NULL); _gtk_css_selector_print (selector, string); return g_string_free (string, FALSE); } static gboolean gtk_css_selector_foreach_match (const GtkCssSelector *selector, const GtkCssMatcher *matcher, gpointer unused) { selector = gtk_css_selector_previous (selector); if (selector == NULL) return TRUE; if (!gtk_css_selector_match (selector, matcher)) return FALSE; return gtk_css_selector_foreach (selector, matcher, gtk_css_selector_foreach_match, NULL); } /** * _gtk_css_selector_matches: * @selector: the selector * @path: the path to check * @state: The state to match * * Checks if the @selector matches the given @path. If @length is * smaller than the number of elements in @path, it is assumed that * only the first @length element of @path are valid and the rest * does not exist. This is useful for doing parent matches for the * 'inherit' keyword. * * Returns: %TRUE if the selector matches @path **/ gboolean _gtk_css_selector_matches (const GtkCssSelector *selector, const GtkCssMatcher *matcher) { g_return_val_if_fail (selector != NULL, FALSE); g_return_val_if_fail (matcher != NULL, FALSE); update_type_references (); if (!gtk_css_selector_match (selector, matcher)) return FALSE; return gtk_css_selector_foreach (selector, matcher, gtk_css_selector_foreach_match, NULL); } /* Computes specificity according to CSS 2.1. * The arguments must be initialized to 0 */ static void _gtk_css_selector_get_specificity (const GtkCssSelector *selector, guint *ids, guint *classes, guint *elements) { for (; selector; selector = gtk_css_selector_previous (selector)) { selector->class->add_specificity (selector, ids, classes, elements); } } int _gtk_css_selector_compare (const GtkCssSelector *a, const GtkCssSelector *b) { guint a_ids = 0, a_classes = 0, a_elements = 0; guint b_ids = 0, b_classes = 0, b_elements = 0; int compare; _gtk_css_selector_get_specificity (a, &a_ids, &a_classes, &a_elements); _gtk_css_selector_get_specificity (b, &b_ids, &b_classes, &b_elements); compare = a_ids - b_ids; if (compare) return compare; compare = a_classes - b_classes; if (compare) return compare; return a_elements - b_elements; } GtkCssChange _gtk_css_selector_get_change (const GtkCssSelector *selector) { if (selector == NULL) return 0; return selector->class->get_change (selector, _gtk_css_selector_get_change (gtk_css_selector_previous (selector))); } /******************** SelectorTree handling *****************/ static GHashTable * gtk_css_selectors_count_initial_init (void) { return g_hash_table_new ((GHashFunc)gtk_css_selector_hash_one, (GEqualFunc)gtk_css_selector_equal); } static void gtk_css_selectors_count_initial (const GtkCssSelector *selector, GHashTable *hash_one) { if (!selector->class->is_simple) { guint count = GPOINTER_TO_INT (g_hash_table_lookup (hash_one, selector)); g_hash_table_replace (hash_one, (gpointer)selector, GUINT_TO_POINTER (count + 1)); return; } for (; selector && selector->class->is_simple; selector = gtk_css_selector_previous (selector)) { guint count = GPOINTER_TO_INT (g_hash_table_lookup (hash_one, selector)); g_hash_table_replace (hash_one, (gpointer)selector, GUINT_TO_POINTER (count + 1)); } } static gboolean gtk_css_selectors_has_initial_selector (const GtkCssSelector *selector, const GtkCssSelector *initial) { if (!selector->class->is_simple) return gtk_css_selector_equal (selector, initial); for (; selector && selector->class->is_simple; selector = gtk_css_selector_previous (selector)) { if (gtk_css_selector_equal (selector, initial)) return TRUE; } return FALSE; } static GtkCssSelector * gtk_css_selectors_skip_initial_selector (GtkCssSelector *selector, const GtkCssSelector *initial) { GtkCssSelector *found; GtkCssSelector tmp; /* If the initial simple selector is not first, move it there so we can skip it without losing any other selectors */ if (!gtk_css_selector_equal (selector, initial)) { for (found = selector; found && found->class->is_simple; found = (GtkCssSelector *)gtk_css_selector_previous (found)) { if (gtk_css_selector_equal (found, initial)) break; } g_assert (found != NULL && found->class->is_simple); tmp = *found; *found = *selector; *selector = tmp; } return (GtkCssSelector *)gtk_css_selector_previous (selector); } static int direct_ptr_compare (const void *_a, const void *_b) { gpointer *a = (gpointer *)_a; gpointer *b = (gpointer *)_b; if (*a < *b) return -1; else if (*a == *b) return 0; return 1; } static gboolean gtk_css_selector_tree_match_foreach (const GtkCssSelector *selector, const GtkCssMatcher *matcher, gpointer res) { const GtkCssSelectorTree *tree = (const GtkCssSelectorTree *) selector; const GtkCssSelectorTree *prev; if (!gtk_css_selector_match (selector, matcher)) return FALSE; gtk_css_selector_tree_found_match (tree, res); for (prev = gtk_css_selector_tree_get_previous (tree); prev != NULL; prev = gtk_css_selector_tree_get_sibling (prev)) gtk_css_selector_foreach (&prev->selector, matcher, gtk_css_selector_tree_match_foreach, res); return FALSE; } GPtrArray * _gtk_css_selector_tree_match_all (const GtkCssSelectorTree *tree, const GtkCssMatcher *matcher) { GHashTable *res; GPtrArray *array; GHashTableIter iter; gpointer key; update_type_references (); res = g_hash_table_new (g_direct_hash, g_direct_equal); for (; tree != NULL; tree = gtk_css_selector_tree_get_sibling (tree)) gtk_css_selector_foreach (&tree->selector, matcher, gtk_css_selector_tree_match_foreach, res); array = g_ptr_array_sized_new (g_hash_table_size (res)); g_hash_table_iter_init (&iter, res); while (g_hash_table_iter_next (&iter, &key, NULL)) g_ptr_array_add (array, key); g_hash_table_destroy (res); qsort (array->pdata, array->len, sizeof (gpointer), direct_ptr_compare); return array; } /* When checking for changes via the tree we need to know if a rule further down the tree matched, because if so we need to add "our bit" to the Change. For instance in a a match like *.class:active we'll get a tree that first checks :active, if that matches we continue down to the tree, and if we get a match we add CHANGE_CLASS. However, the end of the tree where we have a match is an ANY which doesn't actually modify the change, so we don't know if we have a match or not. We fix this by setting GTK_CSS_CHANGE_GOT_MATCH which lets us guarantee that change != 0 on any match. */ #define GTK_CSS_CHANGE_GOT_MATCH GTK_CSS_CHANGE_RESERVED_BIT static GtkCssChange gtk_css_selector_tree_collect_change (const GtkCssSelectorTree *tree) { GtkCssChange change = 0; const GtkCssSelectorTree *prev; for (prev = gtk_css_selector_tree_get_previous (tree); prev != NULL; prev = gtk_css_selector_tree_get_sibling (prev)) change |= gtk_css_selector_tree_collect_change (prev); change = tree->selector.class->get_change (&tree->selector, change); return change; } static GtkCssChange gtk_css_selector_tree_get_change (const GtkCssSelectorTree *tree, const GtkCssMatcher *matcher) { GtkCssChange change = 0; const GtkCssSelectorTree *prev; if (!gtk_css_selector_match (&tree->selector, matcher)) return 0; if (!tree->selector.class->is_simple) return gtk_css_selector_tree_collect_change (tree) | GTK_CSS_CHANGE_GOT_MATCH; for (prev = gtk_css_selector_tree_get_previous (tree); prev != NULL; prev = gtk_css_selector_tree_get_sibling (prev)) change |= gtk_css_selector_tree_get_change (prev, matcher); if (change || gtk_css_selector_tree_get_matches (tree)) change = tree->selector.class->get_change (&tree->selector, change & ~GTK_CSS_CHANGE_GOT_MATCH) | GTK_CSS_CHANGE_GOT_MATCH; return change; } GtkCssChange _gtk_css_selector_tree_get_change_all (const GtkCssSelectorTree *tree, const GtkCssMatcher *matcher) { GtkCssChange change; change = 0; /* no need to foreach here because we abort for non-simple selectors */ for (; tree != NULL; tree = gtk_css_selector_tree_get_sibling (tree)) change |= gtk_css_selector_tree_get_change (tree, matcher); /* Never return reserved bit set */ return change & ~GTK_CSS_CHANGE_RESERVED_BIT; } #ifdef PRINT_TREE static void _gtk_css_selector_tree_print (const GtkCssSelectorTree *tree, GString *str, char *prefix) { gboolean first = TRUE; int len, i; for (; tree != NULL; tree = gtk_css_selector_tree_get_sibling (tree), first = FALSE) { if (!first) g_string_append (str, prefix); if (first) { if (gtk_css_selector_tree_get_sibling (tree)) g_string_append (str, "─┬─"); else g_string_append (str, "───"); } else { if (gtk_css_selector_tree_get_sibling (tree)) g_string_append (str, " ├─"); else g_string_append (str, " └─"); } len = str->len; tree->selector.class->print (&tree->selector, str); len = str->len - len; if (gtk_css_selector_tree_get_previous (tree)) { GString *prefix2 = g_string_new (prefix); if (gtk_css_selector_tree_get_sibling (tree)) g_string_append (prefix2, " │ "); else g_string_append (prefix2, " "); for (i = 0; i < len; i++) g_string_append_c (prefix2, ' '); _gtk_css_selector_tree_print (gtk_css_selector_tree_get_previous (tree), str, prefix2->str); g_string_free (prefix2, TRUE); } else g_string_append (str, "\n"); } } #endif void _gtk_css_selector_tree_match_print (const GtkCssSelectorTree *tree, GString *str) { const GtkCssSelectorTree *parent; g_return_if_fail (tree != NULL); tree->selector.class->print (&tree->selector, str); parent = gtk_css_selector_tree_get_parent (tree); if (parent != NULL) _gtk_css_selector_tree_match_print (parent, str); } void _gtk_css_selector_tree_free (GtkCssSelectorTree *tree) { if (tree == NULL) return; g_free (tree); } typedef struct { gpointer match; GtkCssSelector *current_selector; GtkCssSelectorTree **selector_match; } GtkCssSelectorRuleSetInfo; static GtkCssSelectorTree * get_tree (GByteArray *array, gint32 offset) { return (GtkCssSelectorTree *) (array->data + offset); } static GtkCssSelectorTree * alloc_tree (GByteArray *array, gint32 *offset) { GtkCssSelectorTree tree = { { NULL} }; *offset = array->len; g_byte_array_append (array, (guint8 *)&tree, sizeof (GtkCssSelectorTree)); return get_tree (array, *offset); } static gint32 subdivide_infos (GByteArray *array, GList *infos, gint32 parent_offset) { GHashTable *ht; GList *l; GList *matched; GList *remaining; gint32 tree_offset; GtkCssSelectorTree *tree; GtkCssSelectorRuleSetInfo *info; GtkCssSelector max_selector; GHashTableIter iter; guint max_count; gpointer key, value; GPtrArray *exact_matches; gint32 res; if (infos == NULL) return GTK_CSS_SELECTOR_TREE_EMPTY_OFFSET; ht = gtk_css_selectors_count_initial_init (); for (l = infos; l != NULL; l = l->next) { info = l->data; gtk_css_selectors_count_initial (info->current_selector, ht); } /* Pick the selector with highest count, and use as decision on this level as that makes it possible to skip the largest amount of checks later */ max_count = 0; g_hash_table_iter_init (&iter, ht); while (g_hash_table_iter_next (&iter, &key, &value)) { GtkCssSelector *selector = key; if (GPOINTER_TO_UINT (value) > max_count || (GPOINTER_TO_UINT (value) == max_count && gtk_css_selector_compare_one (selector, &max_selector) < 0)) { max_count = GPOINTER_TO_UINT (value); max_selector = *selector; } } matched = NULL; remaining = NULL; tree = alloc_tree (array, &tree_offset); tree->parent_offset = parent_offset; tree->selector = max_selector; exact_matches = NULL; for (l = infos; l != NULL; l = l->next) { info = l->data; if (gtk_css_selectors_has_initial_selector (info->current_selector, &max_selector)) { info->current_selector = gtk_css_selectors_skip_initial_selector (info->current_selector, &max_selector); if (info->current_selector == NULL) { /* Matches current node */ if (exact_matches == NULL) exact_matches = g_ptr_array_new (); g_ptr_array_add (exact_matches, info->match); if (info->selector_match != NULL) *info->selector_match = GUINT_TO_POINTER (tree_offset); } else matched = g_list_prepend (matched, info); } else { remaining = g_list_prepend (remaining, info); } } if (exact_matches) { g_ptr_array_add (exact_matches, NULL); /* Null terminate */ res = array->len; g_byte_array_append (array, (guint8 *)exact_matches->pdata, exact_matches->len * sizeof (gpointer)); g_ptr_array_free (exact_matches, TRUE); } else res = GTK_CSS_SELECTOR_TREE_EMPTY_OFFSET; get_tree (array, tree_offset)->matches_offset = res; res = subdivide_infos (array, matched, tree_offset); get_tree (array, tree_offset)->previous_offset = res; res = subdivide_infos (array, remaining, parent_offset); get_tree (array, tree_offset)->sibling_offset = res; g_list_free (matched); g_list_free (remaining); g_hash_table_unref (ht); return tree_offset; } struct _GtkCssSelectorTreeBuilder { GList *infos; }; GtkCssSelectorTreeBuilder * _gtk_css_selector_tree_builder_new (void) { return g_new0 (GtkCssSelectorTreeBuilder, 1); } void _gtk_css_selector_tree_builder_free (GtkCssSelectorTreeBuilder *builder) { g_list_free_full (builder->infos, g_free); g_free (builder); } void _gtk_css_selector_tree_builder_add (GtkCssSelectorTreeBuilder *builder, GtkCssSelector *selectors, GtkCssSelectorTree **selector_match, gpointer match) { GtkCssSelectorRuleSetInfo *info = g_new0 (GtkCssSelectorRuleSetInfo, 1); info->match = match; info->current_selector = selectors; info->selector_match = selector_match; builder->infos = g_list_prepend (builder->infos, info); } /* Convert all offsets to node-relative */ static void fixup_offsets (GtkCssSelectorTree *tree, guint8 *data) { while (tree != NULL) { if (tree->parent_offset != GTK_CSS_SELECTOR_TREE_EMPTY_OFFSET) tree->parent_offset -= ((guint8 *)tree - data); if (tree->previous_offset != GTK_CSS_SELECTOR_TREE_EMPTY_OFFSET) tree->previous_offset -= ((guint8 *)tree - data); if (tree->sibling_offset != GTK_CSS_SELECTOR_TREE_EMPTY_OFFSET) tree->sibling_offset -= ((guint8 *)tree - data); if (tree->matches_offset != GTK_CSS_SELECTOR_TREE_EMPTY_OFFSET) tree->matches_offset -= ((guint8 *)tree - data); fixup_offsets ((GtkCssSelectorTree *)gtk_css_selector_tree_get_previous (tree), data); tree = (GtkCssSelectorTree *)gtk_css_selector_tree_get_sibling (tree); } } GtkCssSelectorTree * _gtk_css_selector_tree_builder_build (GtkCssSelectorTreeBuilder *builder) { GtkCssSelectorTree *tree; GByteArray *array; guint8 *data; guint len; GList *l; GtkCssSelectorRuleSetInfo *info; array = g_byte_array_new (); subdivide_infos (array, builder->infos, GTK_CSS_SELECTOR_TREE_EMPTY_OFFSET); len = array->len; data = g_byte_array_free (array, FALSE); /* shrink to final size */ data = g_realloc (data, len); tree = (GtkCssSelectorTree *)data; fixup_offsets (tree, data); /* Convert offsets to final pointers */ for (l = builder->infos; l != NULL; l = l->next) { info = l->data; if (info->selector_match) *info->selector_match = (GtkCssSelectorTree *)(data + GPOINTER_TO_UINT (*info->selector_match)); } #ifdef PRINT_TREE { GString *s = g_string_new (""); _gtk_css_selector_tree_print (tree, s, ""); g_print ("%s", s->str); g_string_free (s, TRUE); } #endif return tree; }
Adamovskiy/gtk
gtk/gtkcssselector.c
C
lgpl-2.1
61,597
#include <stdlib.h> #include <stdio.h> #include <string.h> #include "librepo/version.h" #include "fixtures.h" #include "testsys.h" #include "test_version.h" START_TEST(test_version_check_macro) { ck_assert(LR_VERSION_CHECK(LR_VERSION_MAJOR, LR_VERSION_MINOR, LR_VERSION_PATCH)); ck_assert(LR_VERSION_CHECK(0, 0, 0)); ck_assert(!(LR_VERSION_CHECK(LR_VERSION_MAJOR, LR_VERSION_MINOR, LR_VERSION_PATCH+1))); ck_assert(!(LR_VERSION_CHECK(LR_VERSION_MAJOR, LR_VERSION_MINOR+1, LR_VERSION_PATCH))); ck_assert(!(LR_VERSION_CHECK(LR_VERSION_MAJOR+1, LR_VERSION_MINOR, LR_VERSION_PATCH))); } END_TEST Suite * version_suite(void) { Suite *s = suite_create("version"); TCase *tc = tcase_create("Main"); tcase_add_test(tc, test_version_check_macro); suite_add_tcase(s, tc); return s; }
Tojaj/librepo
tests/test_version.c
C
lgpl-2.1
1,082
/* 题目:定义Fibonacci 数列如下: / 0 n=0 f(n)= 1 n=1 \ f(n-1)+f(n-2) n=2 输入n,用最快的方法求该数列的第n 项。 分析:在很多C 语言教科书中讲到递归函数的时候,都会用Fibonacci 作为例子。 因此很多程序员对这道题的递归解法非常熟悉,但....呵呵,你知道的。。 ANSWER: This is the traditional problem of application of mathematics... let A= {1 1} {1 0} f(n) = A^(n-1)[0,0] this gives a O(log n) solution. int f(int n) { int A[4] = {1,1,1,0}; int result[4]; power(A, n, result); return result[0]; } void multiply(int[] A, int[] B, int _r) { _r[0] = A[0]*B[0] + A[1]*B[2]; _r[1] = A[0]*B[1] + A[1]*B[3]; _r[2] = A[2]*B[0] + A[3]*B[2]; _r[3] = A[2]*B[1] + A[3]*B[3]; } void power(int[] A, int n, int _r) { if (n==1) { memcpy(A, _r, 4*sizeof(int)); return; } int tmp[4]; power(A, n>>1, _r); multiply(_r, _r, tmp); if (n & 1 == 1) { multiply(tmp, A, _r); } else { memcpy(_r, tmp, 4*sizeof(int)); } } */ #include <stdio.h> #include <stdlib.h> int fibonacci(int n) { if (n == 0) { return 0; } else if (n == 1) { return 1; } else { int fn[3] = {0}; fn[0] = 0; fn[1] = 1; while (n >= 2) { fn[2] = fn[0] + fn[1]; fn[0] = fn[1]; fn[1] = fn[2]; n--; } return fn[2]; } } /* ------ ---- f[n+1] = [ 1, 1] ^n f[1] f[n] [ 1, 0] f[0] ------ ---- */ unsigned int fibonacci2(unsigned int n) { if (n == 0) { return 0; } else if(n == 1) { return 1; } else { int a[4] = {1, 1, 1, 0}; int ret[4] = {1, 1, 1, 0}; while (n-- > 1) { ret[0] = ret[0] * a[0] + ret[1] * a[2]; ret[1] = ret[0] * a[1] + ret[1] * a[3]; ret[2] = ret[2] * a[0] + ret[3] * a[2]; ret[3] = ret[2] * a[1] + ret[3] * a[3]; } return ret[2]; } } int main(void) { int n; int ret; printf("Please input number:"); scanf("%d", &n); ret = fibonacci(n); printf("1.The result is %d\n", ret); ret = fibonacci2(n); printf("2.The result is %d\n", ret); return 0; }
lolodo/algorithm
C/windows_c/src/Case019.c
C
lgpl-2.1
2,261
/* Copyright (C) 2018 Daniel Schultz This file is part of FLINT. FLINT is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. See <https://www.gnu.org/licenses/>. */ #include "nmod_mpoly.h" #include "fq_nmod_mpoly.h" void nmod_mpolyd_ctx_init(nmod_mpolyd_ctx_t dctx, slong nvars) { slong i; dctx->nvars = nvars; dctx->perm = (slong *) flint_malloc(nvars*sizeof(slong)); for (i = 0; i < nvars; i++) { dctx->perm[i] = i; } } void nmod_mpolyd_ctx_clear(nmod_mpolyd_ctx_t dctx) { flint_free(dctx->perm); } void nmod_mpolyd_init(nmod_mpolyd_t poly, slong nvars) { slong i; poly->nvars = nvars; poly->degb_alloc = nvars; poly->deg_bounds = (slong *) flint_malloc(poly->degb_alloc*sizeof(slong)); for (i = 0; i < nvars; i++) { poly->deg_bounds[i] = WORD(1); } poly->coeff_alloc = WORD(16); poly->coeffs = (mp_limb_t *) flint_malloc(poly->coeff_alloc*sizeof(mp_limb_t)); for (i = 0; i < poly->coeff_alloc; i++) { poly->coeffs[i] = UWORD(0); } } void nmod_mpolyd_fit_length(nmod_mpolyd_t poly, slong len) { if (poly->coeff_alloc < len) { /*flint_printf("realloc %wd -> %wd\n",poly->coeff_alloc, len);*/ poly->coeffs = (mp_limb_t *) flint_realloc(poly->coeffs, len*sizeof(mp_limb_t)); poly->coeff_alloc = len; } } void nmod_mpolyd_set_nvars(nmod_mpolyd_t poly, slong nvars) { poly->nvars = nvars; if (poly->degb_alloc < nvars) { poly->deg_bounds = (slong *) flint_realloc(poly->deg_bounds, nvars*sizeof(slong)); poly->degb_alloc = nvars; } } void nmod_mpolyd_zero(nmod_mpolyd_t poly) { slong i; for (i = 0; i < poly->nvars; i++) { poly->deg_bounds[i] = WORD(1); } poly->coeffs[0] = UWORD(0); } void nmod_mpolyd_clear(nmod_mpolyd_t poly) { flint_free(poly->deg_bounds); flint_free(poly->coeffs); poly->deg_bounds = NULL; poly->coeffs = NULL; } int nmod_mpolyd_set_degbounds(nmod_mpolyd_t A, slong * bounds) { slong i; int success = 0; slong degb_prod; degb_prod = 1; for (i = 0; i < A->nvars; i++) { ulong hi; A->deg_bounds[i] = bounds[i]; umul_ppmm(hi, degb_prod, degb_prod, A->deg_bounds[i]); if (hi != WORD(0) || degb_prod < 0) { goto done; } } success = 1; nmod_mpolyd_fit_length(A, degb_prod); done: return success; } int nmod_mpolyd_set_degbounds_perm(nmod_mpolyd_t A, const nmod_mpolyd_ctx_t dctx, slong * bounds) { slong i; int success = 0; const slong * perm = dctx->perm; slong degb_prod; degb_prod = 1; for (i = 0; i < A->nvars; i++) { ulong hi; A->deg_bounds[i] = bounds[perm[i]]; umul_ppmm(hi, degb_prod, degb_prod, A->deg_bounds[i]); if (hi != WORD(0) || degb_prod < 0) { goto done; } } success = 1; nmod_mpolyd_fit_length(A, degb_prod); done: return success; } /* convert B to A assuming degree bounds have been set in A */ void nmod_mpoly_convert_to_nmod_mpolyd_degbound(nmod_mpolyd_t A, const nmod_mpolyd_ctx_t dctx, const nmod_mpoly_t B, const nmod_mpoly_ctx_t ctx) { slong degb_prod; slong i, j, N; ulong * exps; const slong * perm = dctx->perm; slong nvars = ctx->minfo->nvars; TMP_INIT; FLINT_ASSERT(A->nvars == nvars); FLINT_ASSERT(B->bits <= FLINT_BITS); degb_prod = WORD(1); for (i = 0; i < nvars; i++) { degb_prod *= A->deg_bounds[i]; } for (i = 0; i < degb_prod; i++) { A->coeffs[i] = UWORD(0); } TMP_START; exps = (ulong *) TMP_ALLOC(nvars*sizeof(ulong)); N = mpoly_words_per_exp(B->bits, ctx->minfo); for (i = 0; i < B->length; i++) { slong off; mpoly_get_monomial_ui(exps, B->exps + N*i, B->bits, ctx->minfo); off = 0; for (j = 0; j < nvars; j++) { off = exps[perm[j]] + A->deg_bounds[j]*off; } A->coeffs[off] = B->coeffs[i]; } TMP_END; } /* convert B to A - sets degree bounds in A */ void nmod_mpoly_convert_to_nmod_mpolyd( nmod_mpolyd_t A, const nmod_mpolyd_ctx_t dctx, const nmod_mpoly_t B, const nmod_mpoly_ctx_t ctx) { slong degb_prod; slong i, j, N; slong * exps; const slong * perm = dctx->perm; slong nvars = ctx->minfo->nvars; TMP_INIT; nmod_mpolyd_set_nvars(A, ctx->minfo->nvars); FLINT_ASSERT(B->bits <= FLINT_BITS); if (B->length == 0) { nmod_mpolyd_zero(A); return; } TMP_START; exps = (slong *) TMP_ALLOC(ctx->minfo->nvars*sizeof(slong)); nmod_mpoly_degrees_si(exps, B, ctx); degb_prod = WORD(1); for (i = 0; i < nvars; i++) { A->deg_bounds[i] = exps[perm[i]] + 1; degb_prod *= A->deg_bounds[i]; } nmod_mpolyd_fit_length(A, degb_prod); for (i = 0; i < degb_prod; i++) { A->coeffs[i] = UWORD(0); } N = mpoly_words_per_exp(B->bits, ctx->minfo); for (i = 0; i < B->length; i++) { slong off = 0; mpoly_get_monomial_ui((ulong *)exps, B->exps + N*i, B->bits, ctx->minfo); for (j = 0; j < nvars; j++) { off = exps[perm[j]] + A->deg_bounds[j]*off; } A->coeffs[off] = B->coeffs[i]; } TMP_END; } /* Convert B to A */ void nmod_mpoly_convert_from_nmod_mpolyd( nmod_mpoly_t A, const nmod_mpoly_ctx_t ctx, const nmod_mpolyd_t B, const nmod_mpolyd_ctx_t dctx) { slong off, j, k, N; slong bits, nvars = ctx->minfo->nvars; slong Alen; slong * perm = dctx->perm; slong perm_nontrivial = 0; ulong topmask; ulong * exps, * pcurexp, * pexps; TMP_INIT; FLINT_ASSERT(nvars == B->nvars); TMP_START; exps = (ulong *) TMP_ALLOC(nvars*sizeof(ulong)); /* find bits needed for the result */ off = 1; for (j = 0; j < nvars; j++) { off *= B->deg_bounds[j]; exps[perm[j]] = B->deg_bounds[j] - 1; perm_nontrivial |= j ^ perm[j]; } FLINT_ASSERT(off <= B->coeff_alloc); bits = mpoly_exp_bits_required_ui(exps, ctx->minfo); bits = mpoly_fix_bits(bits, ctx->minfo); N = mpoly_words_per_exp(bits, ctx->minfo); /* we are going to push back terms manually */ nmod_mpoly_fit_length_reset_bits(A, 0, bits, ctx); Alen = 0; /* find exponent vector for all variables */ pexps = (ulong *) TMP_ALLOC(N*nvars*sizeof(ulong)); for (k = 0; k < nvars; k++) { for (j = 0; j < nvars; j++) exps[perm[j]] = (j == k); mpoly_set_monomial_ui(pexps + k*N, exps, bits, ctx->minfo); } /* get most significant exponent in exps and its vector in ptempexp */ off--; pcurexp = (ulong *) TMP_ALLOC(N*sizeof(ulong)); mpoly_monomial_zero(pcurexp, N); k = off; for (j = nvars - 1; j >= 0; j--) { exps[j] = k % B->deg_bounds[j]; k = k / B->deg_bounds[j]; mpoly_monomial_madd_inplace_mp(pcurexp, exps[j], pexps + N*j, N); } /* scan down through the exponents */ topmask = 0; for (; off >= 0; off--) { if (B->coeffs[off] != UWORD(0)) { _nmod_mpoly_fit_length(&A->coeffs, &A->coeffs_alloc, &A->exps, &A->exps_alloc, N, Alen + 1); A->coeffs[Alen] = B->coeffs[off]; mpoly_monomial_set(A->exps + N*Alen, pcurexp, N); topmask |= (A->exps + N*Alen)[N - 1]; Alen++; } j = nvars - 1; do { --exps[j]; if ((slong)(exps[j]) < WORD(0)) { FLINT_ASSERT(off == 0 || j > 0); FLINT_ASSERT(exps[j] == -UWORD(1)); exps[j] = B->deg_bounds[j] - 1; mpoly_monomial_madd_inplace_mp(pcurexp, exps[j], pexps + N*j, N); } else { mpoly_monomial_sub_mp(pcurexp, pcurexp, pexps + N*j, N); break; } } while (--j >= 0); } _nmod_mpoly_set_length(A, Alen, ctx); /* sort the exponents if needed */ if (ctx->minfo->ord != ORD_LEX || perm_nontrivial != WORD(0)) { slong msb; mpoly_get_cmpmask(pcurexp, N, bits, ctx->minfo); if (topmask != WORD(0)) { count_leading_zeros(msb, topmask); msb = (FLINT_BITS - 1)^msb; } else { msb = -WORD(1); } if (N == 1) { if (msb >= WORD(0)) { _nmod_mpoly_radix_sort1(A, 0, A->length, msb, pcurexp[0], topmask); } } else { _nmod_mpoly_radix_sort(A, 0, A->length, (N - 1)*FLINT_BITS + msb, N, pcurexp); } } TMP_END; } void nmod_mpolyd_print(nmod_mpolyd_t poly) { int first = 0; slong i, j; slong degb_prod; degb_prod = WORD(1); for (j = 0; j < poly->nvars; j++) { degb_prod *= poly->deg_bounds[j]; } first = 1; for (i = 0; i < degb_prod; i++) { ulong k = i; if (poly->coeffs[i] == 0) continue; if (!first) printf(" + "); flint_printf("%wu", poly->coeffs[i]); for (j = poly->nvars - 1; j >= 0; j--) { ulong m = poly->deg_bounds[j]; ulong e = k % m; k = k / m; flint_printf("*x%wd^%wd", j, e); } FLINT_ASSERT(k == 0); first = 0; } if (first) flint_printf("0"); } slong nmod_mpolyd_length(const nmod_mpolyd_t A) { slong i, j, degb_prod; degb_prod = WORD(1); for (j = 0; j < A->nvars; j++) degb_prod *= A->deg_bounds[j]; for (i = degb_prod; i > 0; i--) { if (A->coeffs[i - 1] != UWORD(0)) break; } return i; }
wbhart/flint2
nmod_mpoly/mpolyd.c
C
lgpl-2.1
10,274
/* radare - LGPL - Copyright 2010-2019 - pancake, maijin */ #include <r_types.h> #include <r_list.h> #include <r_flag.h> #include <r_core.h> #define USE_R2 1 #include <spp/spp.h> static bool is_valid_project_name(const char *name) { int i; if (r_str_endswith (name, ".zip")) { return false; } for (i = 0; name[i]; i++) { switch (name[i]) { case '\\': // for w32 case '.': case '_': case ':': case '-': continue; } if (name[i] >= 'a' && name[i] <= 'z') { continue; } if (name[i] >= 'A' && name[i] <= 'Z') { continue; } if (IS_DIGIT (name[i])) { continue; } return false; } return true; } static char *get_project_script_path(RCore *core, const char *file) { const char *magic = "# r2 rdb project file"; char *data, *prjfile; if (r_file_is_abspath (file)) { prjfile = strdup (file); } else { if (!is_valid_project_name (file)) { return NULL; } prjfile = r_file_abspath (r_config_get (core->config, "dir.projects")); prjfile = r_str_append (prjfile, R_SYS_DIR); prjfile = r_str_append (prjfile, file); if (!r_file_exists (prjfile) || r_file_is_directory (prjfile)) { prjfile = r_str_append (prjfile, R_SYS_DIR "rc"); } } data = r_file_slurp (prjfile, NULL); if (data) { if (strncmp (data, magic, strlen (magic))) { R_FREE (prjfile); } } free (data); return prjfile; } static int make_projects_directory(RCore *core) { char *prjdir = r_file_abspath (r_config_get (core->config, "dir.projects")); int ret = r_sys_mkdirp (prjdir); if (!ret) { eprintf ("Cannot mkdir dir.projects\n"); } free (prjdir); return ret; } R_API bool r_core_is_project(RCore *core, const char *name) { bool ret = false; if (name && *name && *name != '.') { char *path = get_project_script_path (core, name); if (!path) { return false; } if (r_str_endswith (path, R_SYS_DIR "rc") && r_file_exists (path)) { ret = true; } else { path = r_str_append (path, ".d"); if (r_file_is_directory (path)) { ret = true; } } free (path); } return ret; } R_API int r_core_project_cat(RCore *core, const char *name) { char *path = get_project_script_path (core, name); if (path) { char *data = r_file_slurp (path, NULL); if (data) { r_cons_println (data); free (data); } } free (path); return 0; } R_API int r_core_project_list(RCore *core, int mode) { PJ *pj = NULL; RListIter *iter; RList *list; char *foo, *path = r_file_abspath (r_config_get (core->config, "dir.projects")); if (!path) { return 0; } list = r_sys_dir (path); switch (mode) { case 'j': pj = pj_new (); if (!pj) { break; } pj_a (pj); r_list_foreach (list, iter, foo) { // todo. escape string if (r_core_is_project (core, foo)) { pj_s (pj, foo); } } pj_end (pj); r_cons_printf ("%s\n", pj_string (pj)); pj_free (pj); break; default: r_list_foreach (list, iter, foo) { if (r_core_is_project (core, foo)) { r_cons_println (foo); } } break; } r_list_free (list); free (path); return 0; } static inline void remove_project_file(char * path) { if (r_file_exists (path)) { r_file_rm (path); eprintf ("rm %s\n", path); } } static inline void remove_notes_file(char *prjDir) { char *notes_txt = r_str_newf ("%s%s%s", prjDir, R_SYS_DIR, "notes.txt"); if (r_file_exists (notes_txt)) { r_file_rm (notes_txt); eprintf ("rm %s\n", notes_txt); } free(notes_txt); } static inline void remove_rop_directory(char *prjDir) { char *rop_d = r_str_newf ("%s%s%s", prjDir, R_SYS_DIR, "rop.d"); if (r_file_is_directory (rop_d)) { char *f; RListIter *iter; RList *files = r_sys_dir (rop_d); r_list_foreach (files, iter, f) { char *filepath = r_str_append (strdup (rop_d), R_SYS_DIR); filepath = r_str_append (filepath, f); if (!r_file_is_directory (filepath)) { eprintf ("rm %s\n", filepath); r_file_rm (filepath); } free (filepath); } r_file_rm (rop_d); eprintf ("rm %s\n", rop_d); r_list_free (files); } free (rop_d); } R_API int r_core_project_delete(RCore *core, const char *prjfile) { if (r_sandbox_enable (0)) { eprintf ("Cannot delete project in sandbox mode\n"); return 0; } char *path = get_project_script_path (core, prjfile); if (!path) { eprintf ("Invalid project name '%s'\n", prjfile); return false; } if (r_core_is_project (core, prjfile)) { char *prjDir = r_file_dirname (path); if (!prjDir) { eprintf ("Cannot resolve directory\n"); free (path); return false; } remove_project_file (path); remove_notes_file (prjDir); remove_rop_directory (prjDir); // remove directory only if it's empty r_file_rm (prjDir); free (prjDir); } free (path); return 0; } static bool load_project_rop(RCore *core, const char *prjfile) { char *path, *db = NULL, *path_ns; bool found = 0; SdbListIter *it; SdbNs *ns; if (!prjfile || !*prjfile) { return false; } Sdb *rop_db = sdb_ns (core->sdb, "rop", false); Sdb *nop_db = sdb_ns (rop_db, "nop", false); Sdb *mov_db = sdb_ns (rop_db, "mov", false); Sdb *const_db = sdb_ns (rop_db, "const", false); Sdb *arithm_db = sdb_ns (rop_db, "arithm", false); Sdb *arithmct_db = sdb_ns (rop_db, "arithm_ct", false); char *rcPath = get_project_script_path (core, prjfile); char *prjDir = r_file_dirname (rcPath); if (r_str_endswith (prjfile, R_SYS_DIR "rc")) { // XXX eprintf ("ENDS WITH\n"); path = strdup (prjfile); path[strlen (path) - 3] = 0; } else if (r_file_fexists ("%s" R_SYS_DIR "rc", prjDir, prjfile)) { path = r_str_newf ("%s" R_SYS_DIR, prjDir, prjfile); } else { if (*prjfile == R_SYS_DIR[0]) { db = r_str_newf ("%s.d", prjfile); if (!db) { free (prjDir); free (rcPath); return false; } path = strdup (db); } else { db = r_str_newf ("%s" R_SYS_DIR "%s.d", prjDir, prjfile); if (!db) { free (prjDir); free (rcPath); return false; } path = r_file_abspath (db); } } if (!path) { free (db); free (prjDir); free (rcPath); return false; } if (rop_db) { ls_foreach (core->sdb->ns, it, ns){ if (ns->sdb == rop_db) { ls_delete (core->sdb->ns, it); found = true; break; } } } if (!found) { sdb_free (rop_db); } rop_db = sdb_new (path, "rop", 0); if (!rop_db) { free (db); free (path); free (prjDir); free (rcPath); return false; } sdb_ns_set (core->sdb, "rop", rop_db); path_ns = r_str_newf ("%s" R_SYS_DIR "rop", prjDir); if (!r_file_exists (path_ns)) { path_ns = r_str_append (path_ns, ".sdb"); } nop_db = sdb_new (path_ns, "nop", 0); sdb_ns_set (rop_db, "nop", nop_db); mov_db = sdb_new (path_ns, "mov", 0); sdb_ns_set (rop_db, "mov", mov_db); const_db = sdb_new (path_ns, "const", 0); sdb_ns_set (rop_db, "const", const_db); arithm_db = sdb_new (path_ns, "arithm", 0); sdb_ns_set (rop_db, "arithm", arithm_db); arithmct_db = sdb_new (path_ns, "arithm_ct", 0); sdb_ns_set (rop_db, "arithm_ct", arithmct_db); free (path); free (path_ns); free (db); free (prjDir); free (rcPath); return true; } R_API void r_core_project_execute_cmds(RCore *core, const char *prjfile) { char *str = r_core_project_notes_file (core, prjfile); char *data = r_file_slurp (str, NULL); if (!data) { free (str); return; } Output out; out.fout = NULL; out.cout = r_strbuf_new (NULL); r_strbuf_init (out.cout); struct Proc proc; spp_proc_set (&proc, "spp", 1); spp_eval (data, &out); free (data); data = strdup (r_strbuf_get (out.cout)); char *bol = strtok (data, "\n"); while (bol) { if (bol[0] == ':') { r_core_cmd0 (core, bol + 1); } bol = strtok (NULL, "\n"); } free (data); free (str); } /*** vvv thready ***/ typedef struct { RCore *core; char *prjName; char *rcPath; } ProjectState; static RThreadFunctionRet project_load_background(RThread *th) { ProjectState *ps = th->user; r_core_project_load (ps->core, ps->prjName, ps->rcPath); free (ps->prjName); free (ps->rcPath); free (ps); return R_TH_STOP; } R_API RThread *r_core_project_load_bg(RCore *core, const char *prjName, const char *rcPath) { ProjectState *ps = R_NEW (ProjectState); ps->core = core; ps->prjName = strdup (prjName); ps->rcPath = strdup (rcPath); RThread *th = r_th_new (project_load_background, ps, false); if (th) { r_th_start (th, true); char thname[16] = {0}; size_t thlen = R_MIN (strlen(prjName), sizeof(thname) - 1); strncpy (thname, prjName, thlen); thname[15] = 0; r_th_setname (th, thname); } return th; } /*** ^^^ thready ***/ static ut64 getProjectLaddr(RCore *core, const char *prjfile) { ut64 laddr = 0; char *buf = r_file_slurp (prjfile, NULL); char *pos; if (buf) { if ((pos = strstr(buf, "\"e bin.laddr = "))) { laddr = r_num_math (NULL, pos + 15); } free (buf); } return laddr; } R_API bool r_core_project_open(RCore *core, const char *prjfile, bool thready) { bool askuser = true; int ret, close_current_session = 1; char *oldbin; const char *newbin; ut64 mapaddr = 0; if (!prjfile || !*prjfile) { return false; } if (thready) { eprintf ("Loading projects in a thread has been deprecated. Use tasks\n"); return false; } char *prj = get_project_script_path (core, prjfile); if (!prj) { eprintf ("Invalid project name '%s'\n", prjfile); return false; } char *filepath = r_core_project_info (core, prj); // eprintf ("OPENING (%s) from %s\n", prj, r_config_get (core->config, "file.path")); /* if it is not an URI */ if (!filepath) { eprintf ("Cannot retrieve information for project '%s'\n", prj); free (prj); return false; } if (!filepath[0]) { goto cookiefactory; } if (!strstr (filepath, "://")) { /* check if path exists */ if (!r_file_exists (filepath)) { eprintf ("Cannot find file '%s'\n", filepath); free (prj); free (filepath); return false; } } cookiefactory: ; const char *file_path = r_config_get (core->config, "file.path"); if (!file_path || !*file_path) { file_path = r_config_get (core->config, "file.lastpath"); } oldbin = strdup (file_path); if (!strcmp (prjfile, r_config_get (core->config, "prj.name"))) { // eprintf ("Reloading project\n"); askuser = false; #if 0 free (prj); free (filepath); return false; #endif } if (askuser) { if (r_cons_is_interactive ()) { close_current_session = r_cons_yesno ('y', "Close current session? (Y/n)"); } } if (close_current_session) { // delete r_core_file_close_fd (core, -1); r_io_close_all (core->io); r_anal_purge (core->anal); r_flag_unset_all (core->flags); r_bin_file_delete_all (core->bin); // open new file // TODO: handle read/read-write mode if (filepath[0]) { /* Old-style project without embedded on commands to open all files. */ if (!r_core_file_open (core, filepath, 0, UT64_MAX)) { eprintf ("Cannot open file '%s'\n", filepath); ret = false; goto beach; } } } mapaddr = getProjectLaddr (core, prj); if (mapaddr) { r_config_set_i (core->config, "bin.laddr", mapaddr); } if (filepath[0] && close_current_session && r_config_get_i (core->config, "file.info")) { mapaddr = r_config_get_i (core->config, "file.offset"); (void)r_core_bin_load (core, filepath, mapaddr? mapaddr: UT64_MAX); } /* load sdb stuff in here */ ret = r_core_project_load (core, prjfile, prj); if (filepath[0]) { newbin = r_config_get (core->config, "file.path"); if (!newbin || !*newbin) { newbin = r_config_get (core->config, "file.lastpath"); } if (strcmp (oldbin, newbin)) { eprintf ("WARNING: file.path changed: %s => %s\n", oldbin, newbin); } } beach: free (oldbin); free (filepath); free (prj); return ret; } R_API char *r_core_project_info(RCore *core, const char *prjfile) { FILE *fd; char buf[256], *file = NULL; char *prj = get_project_script_path (core, prjfile); if (!prj) { eprintf ("Invalid project name '%s'\n", prjfile); return NULL; } fd = r_sandbox_fopen (prj, "r"); if (fd) { for (;;) { if (!fgets (buf, sizeof (buf), fd)) { break; } if (feof (fd)) { break; } if (!strncmp (buf, "\"e file.path = ", 15)) { buf[strlen (buf) - 2] = 0; file = r_str_new (buf + 15); break; } if (!strncmp (buf, "\"e file.lastpath = ", 19)) { buf[strlen (buf) - 2] = 0; file = r_str_new (buf + 19); break; } // TODO: deprecate before 1.0 if (!strncmp (buf, "e file.path = ", 14)) { buf[strlen (buf) - 1] = 0; file = r_str_new (buf + 14); break; } } fclose (fd); } else { eprintf ("Cannot open project info (%s)\n", prj); } #if 0 if (file) { r_cons_printf ("Project: %s\n", prj); r_cons_printf ("FilePath: %s\n", file); } #endif free (prj); return file; } static int fdc; //this is a ugly, remove it, when we have $fd static bool store_files_and_maps (RCore *core, RIODesc *desc, ut32 id) { RList *maps = NULL; RListIter *iter; RIOMap *map; if (desc) { // reload bin info r_cons_printf ("\"obf %s\"\n", desc->uri); r_cons_printf ("\"ofs \\\"%s\\\" %s\"\n", desc->uri, r_str_rwx_i (desc->perm)); if ((maps = r_io_map_get_for_fd (core->io, id))) { r_list_foreach (maps, iter, map) { r_cons_printf ("om %d 0x%"PFMT64x" 0x%"PFMT64x" 0x%"PFMT64x" %s%s%s\n", fdc, map->itv.addr, map->itv.size, map->delta, r_str_rwx_i (map->perm), map->name ? " " : "", map->name ? map->name : ""); } r_list_free (maps); } fdc++; } return true; } static bool simple_project_save_script(RCore *core, const char *file, int opts) { char *filename, *hl, *ohl = NULL; int fd, fdold; if (!file || * file == '\0') { return false; } filename = r_str_word_get_first (file); fd = r_sandbox_open (file, O_BINARY | O_RDWR | O_CREAT | O_TRUNC, 0644); if (fd == -1) { free (filename); return false; } hl = r_cons_singleton ()->highlight; if (hl) { ohl = strdup (hl); r_cons_highlight (NULL); } fdold = r_cons_singleton ()->fdout; r_cons_singleton ()->fdout = fd; r_cons_singleton ()->context->is_interactive = false; // NOES must use api r_str_write (fd, "# r2 rdb project file\n"); if (opts & R_CORE_PRJ_EVAL) { r_str_write (fd, "# eval\n"); r_config_list (core->config, NULL, true); r_cons_flush (); } if (opts & R_CORE_PRJ_FCNS) { r_str_write (fd, "# functions\n"); r_str_write (fd, "fs functions\n"); r_core_cmd (core, "afl*", 0); r_cons_flush (); } if (opts & R_CORE_PRJ_FLAGS) { r_str_write (fd, "# flags\n"); r_core_cmd (core, "f.**", 0); r_cons_flush (); } if (opts & R_CORE_PRJ_META) { r_str_write (fd, "# meta\n"); r_meta_print_list_all (core->anal, R_META_TYPE_ANY, 1); r_cons_flush (); r_core_cmd (core, "fV*", 0); r_cons_flush (); } if (opts & R_CORE_PRJ_XREFS) { r_str_write (fd, "# xrefs\n"); r_core_cmd (core, "ax*", 0); r_cons_flush (); } r_cons_singleton ()->fdout = fdold; r_cons_singleton ()->context->is_interactive = true; if (ohl) { r_cons_highlight (ohl); free (ohl); } close (fd); free (filename); return true; } static bool project_save_script(RCore *core, const char *file, int opts) { char *filename, *hl, *ohl = NULL; int fd, fdold; if (!file || *file == '\0') { return false; } filename = r_str_word_get_first (file); fd = r_sandbox_open (file, O_BINARY | O_RDWR | O_CREAT | O_TRUNC, 0644); if (fd == -1) { free (filename); return false; } hl = r_cons_singleton ()->highlight; if (hl) { ohl = strdup (hl); r_cons_highlight (NULL); } fdold = r_cons_singleton ()->fdout; r_cons_singleton ()->fdout = fd; r_cons_singleton ()->context->is_interactive = false; r_str_write (fd, "# r2 rdb project file\n"); if (!core->bin->is_debugger && !r_config_get_i (core->config, "asm.emu")) { char *fpath = r_file_abspath (core->bin->file); if (fpath) { char *reopen = r_str_newf ("\"o %s\"\n",fpath); if (reopen) { r_str_write (fd, reopen); free (reopen); free (fpath); } } } // Set file.path and file.lastpath to empty string to signal // new behaviour to project load routine (see io maps below). r_config_set (core->config, "file.path", ""); r_config_set (core->config, "file.lastpath", ""); if (opts & R_CORE_PRJ_EVAL) { r_str_write (fd, "# eval\n"); r_config_list (core->config, NULL, true); r_cons_flush (); } if (opts & R_CORE_PRJ_FCNS) { r_str_write (fd, "# functions\n"); r_str_write (fd, "fs functions\n"); r_core_cmd (core, "afl*", 0); r_cons_flush (); } if (opts & R_CORE_PRJ_FLAGS) { r_str_write (fd, "# flags\n"); r_flag_space_push (core->flags, NULL); r_flag_list (core->flags, true, NULL); r_flag_space_pop (core->flags); r_cons_flush (); } if (opts & R_CORE_PRJ_IO_MAPS && core->io && core->io->files) { fdc = 3; r_id_storage_foreach (core->io->files, (RIDStorageForeachCb)store_files_and_maps, core); r_cons_flush (); } { r_core_cmd (core, "fz*", 0); r_cons_flush (); } if (opts & R_CORE_PRJ_META) { r_str_write (fd, "# meta\n"); r_meta_print_list_all (core->anal, R_META_TYPE_ANY, 1); r_cons_flush (); r_core_cmd (core, "fV*", 0); r_cons_flush (); } if (opts & R_CORE_PRJ_XREFS) { r_core_cmd (core, "ax*", 0); r_cons_flush (); } if (opts & R_CORE_PRJ_FLAGS) { r_core_cmd (core, "f.**", 0); r_cons_flush (); } if (opts & R_CORE_PRJ_DBG_BREAK) { r_core_cmd (core, "db*", 0); r_cons_flush (); } if (opts & R_CORE_PRJ_ANAL_HINTS) { r_core_cmd (core, "ah*", 0); r_cons_flush (); } if (opts & R_CORE_PRJ_ANAL_TYPES) { r_str_write (fd, "# types\n"); r_core_cmd (core, "t*", 0); r_cons_flush (); } if (opts & R_CORE_PRJ_ANAL_MACROS) { r_str_write (fd, "# macros\n"); r_core_cmd (core, "(*", 0); r_str_write (fd, "# aliases\n"); r_core_cmd (core, "$*", 0); r_cons_flush (); } if (opts & R_CORE_PRJ_ANAL_SEEK) { r_cons_printf ("# seek\n" "s 0x%08"PFMT64x "\n", core->offset); r_cons_flush (); } r_cons_singleton ()->fdout = fdold; r_cons_singleton ()->context->is_interactive = true; if (ohl) { r_cons_highlight (ohl); free (ohl); } close (fd); free (filename); return true; } // TODO: rename to r_core_project_save_script R_API bool r_core_project_save_script(RCore *core, const char *file, int opts) { return project_save_script (core, file, opts); } #define TRANSITION 1 R_API bool r_core_project_save(RCore *core, const char *prjName) { bool scr_null = false; bool ret = true; char *scriptPath, *prjDir; SdbListIter *it; SdbNs *ns; char *oldPrjName = NULL; if (!prjName || !*prjName) { return false; } scriptPath = get_project_script_path (core, prjName); if (!scriptPath) { eprintf ("Invalid project name '%s'\n", prjName); return false; } if (r_str_endswith (scriptPath, R_SYS_DIR "rc")) { /* new project format */ prjDir = r_file_dirname (scriptPath); } else { prjDir = r_str_newf ("%s.d", scriptPath); } if (r_file_exists (scriptPath)) { if (r_file_is_directory (scriptPath)) { eprintf ("WTF. rc is a directory?\n"); } if (r_str_endswith (prjDir, ".d")) { eprintf ("Upgrading project...\n"); #if TRANSITION r_file_rm (scriptPath); r_sys_mkdirp (prjDir); eprintf ("Please remove: rm -rf %s %s.d\n", prjName, prjName); char *rc = r_str_newf ("%s" R_SYS_DIR "rc", prjDir); if (!rc) { free (prjDir); free (scriptPath); return false; } free (scriptPath); scriptPath = rc; free (prjDir); prjDir = r_file_dirname (scriptPath); #endif } } if (!prjDir) { prjDir = strdup (prjName); } if (!r_file_exists (prjDir)) { r_sys_mkdirp (prjDir); } if (r_config_get_i (core->config, "scr.null")) { r_config_set_i (core->config, "scr.null", false); scr_null = true; } make_projects_directory (core); Sdb *rop_db = sdb_ns (core->sdb, "rop", false); if (rop_db) { /* set filepath for all the rop sub-dbs */ ls_foreach (rop_db->ns, it, ns) { char *rop_path = r_str_newf ("%s" R_SYS_DIR "rop.d" R_SYS_DIR "%s", prjDir, ns->name); sdb_file (ns->sdb, rop_path); sdb_sync (ns->sdb); free (rop_path); } } const char *oldPrjNameC = r_config_get (core->config, "prj.name"); if (oldPrjNameC) { oldPrjName = strdup (oldPrjNameC); } r_config_set (core->config, "prj.name", prjName); if (r_config_get_i (core->config, "prj.simple")) { if (!simple_project_save_script (core, scriptPath, R_CORE_PRJ_ALL)) { eprintf ("Cannot open '%s' for writing\n", prjName); ret = false; } } else { if (!project_save_script (core, scriptPath, R_CORE_PRJ_ALL)) { eprintf ("Cannot open '%s' for writing\n", prjName); ret = false; } } if (r_config_get_i (core->config, "prj.files")) { eprintf ("TODO: prj.files: support copying more than one file into the project directory\n"); char *binFile = r_core_project_info (core, prjName); const char *binFileName = r_file_basename (binFile); char *prjBinDir = r_str_newf ("%s" R_SYS_DIR "bin", prjDir); char *prjBinFile = r_str_newf ("%s" R_SYS_DIR "%s", prjBinDir, binFileName); r_sys_mkdirp (prjBinDir); if (!r_file_copy (binFile, prjBinFile)) { eprintf ("Warning: Cannot copy '%s' into '%s'\n", binFile, prjBinFile); } free (prjBinFile); free (prjBinDir); free (binFile); } if (r_config_get_i (core->config, "prj.git")) { char *cwd = r_sys_getdir (); char *gitDir = r_str_newf ("%s" R_SYS_DIR ".git", prjDir); if (r_sys_chdir (prjDir)) { if (!r_file_is_directory (gitDir)) { r_sys_cmd ("git init"); } r_sys_cmd ("git add * ; git commit -a"); } else { eprintf ("Cannot chdir %s\n", prjDir); } r_sys_chdir (cwd); free (gitDir); free (cwd); } if (r_config_get_i (core->config, "prj.zip")) { char *cwd = r_sys_getdir (); const char *prjName = r_file_basename (prjDir); if (r_sys_chdir (prjDir)) { if (!strchr (prjName, '\'')) { r_sys_chdir (".."); r_sys_cmdf ("rm -f '%s.zip'; zip -r '%s'.zip '%s'", prjName, prjName, prjName); } else { eprintf ("Command injection attempt?\n"); } } else { eprintf ("Cannot chdir %s\n", prjDir); } r_sys_chdir (cwd); free (cwd); } // LEAK : not always in heap free (prjName); free (prjDir); if (scr_null) { r_config_set_i (core->config, "scr.null", true); } if (!ret && oldPrjName) { // reset prj.name on fail r_config_set (core->config, "prj.name", oldPrjName); } free (scriptPath); free (oldPrjName); return ret; } R_API char *r_core_project_notes_file(RCore *core, const char *prjName) { char *notes_txt; const char *prjdir = r_config_get (core->config, "dir.projects"); char *prjpath = r_file_abspath (prjdir); notes_txt = r_str_newf ("%s"R_SYS_DIR "%s"R_SYS_DIR "notes.txt", prjpath, prjName); free (prjpath); return notes_txt; } R_API bool r_core_project_load(RCore *core, const char *prjName, const char *rcpath) { const bool cfg_fortunes = r_config_get_i (core->config, "cfg.fortunes"); const bool scr_interactive = r_cons_is_interactive (); const bool scr_prompt = r_config_get_i (core->config, "scr.prompt"); (void) load_project_rop (core, prjName); bool ret = r_core_cmd_file (core, rcpath); r_config_set_i (core->config, "cfg.fortunes", cfg_fortunes); r_config_set_i (core->config, "scr.interactive", scr_interactive); r_config_set_i (core->config, "scr.prompt", scr_prompt); r_config_bump (core->config, "asm.arch"); return ret; }
ret2libc/radare2
libr/core/project.c
C
lgpl-3.0
23,220
/* * Copyright © 2009 Adrian Johnson * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * * Author: Adrian Johnson <ajohnson@redneon.com> */ #include "cairo-test.h" #include <float.h> #define SIZE 256 /* This test is designed to test the accuracy of the rendering of mesh * patterns. * * Color accuracy is tested by a square patch covering the whole * surface with black and white corners. * * Extents accuracy is checked by a small red square patch at the * center of the surface which should measure 2x2 pixels. */ static cairo_test_status_t draw (cairo_t *cr, int width, int height) { cairo_pattern_t *pattern; double offset; cairo_test_paint_checkered (cr); pattern = cairo_pattern_create_mesh (); cairo_mesh_pattern_begin_patch (pattern); cairo_mesh_pattern_move_to (pattern, 0, 0); cairo_mesh_pattern_line_to (pattern, 1, 0); cairo_mesh_pattern_line_to (pattern, 1, 1); cairo_mesh_pattern_line_to (pattern, 0, 1); cairo_mesh_pattern_set_corner_color_rgb (pattern, 0, 0, 0, 0); cairo_mesh_pattern_set_corner_color_rgb (pattern, 1, 1, 1, 1); cairo_mesh_pattern_set_corner_color_rgb (pattern, 2, 0, 0, 0); cairo_mesh_pattern_set_corner_color_rgb (pattern, 3, 1, 1, 1); cairo_mesh_pattern_end_patch (pattern); cairo_mesh_pattern_begin_patch (pattern); /* A small 1x1 red patch, that should be rendered as a 2x2 red * square in the center of the image */ offset = 0.5 / SIZE; cairo_mesh_pattern_move_to (pattern, 0.5 + offset, 0.5 + offset); cairo_mesh_pattern_line_to (pattern, 0.5 + offset, 0.5 - offset); cairo_mesh_pattern_line_to (pattern, 0.5 - offset, 0.5 - offset); cairo_mesh_pattern_line_to (pattern, 0.5 - offset, 0.5 + offset); cairo_mesh_pattern_set_corner_color_rgb (pattern, 0, 1, 0, 0); cairo_mesh_pattern_set_corner_color_rgb (pattern, 1, 1, 0, 0); cairo_mesh_pattern_set_corner_color_rgb (pattern, 2, 1, 0, 0); cairo_mesh_pattern_set_corner_color_rgb (pattern, 3, 1, 0, 0); cairo_mesh_pattern_end_patch (pattern); cairo_scale (cr, SIZE, SIZE); cairo_set_source (cr, pattern); cairo_paint (cr); cairo_pattern_destroy (pattern); return CAIRO_TEST_SUCCESS; } CAIRO_TEST (mesh_pattern_accuracy, "Paint mesh pattern", "mesh, pattern", /* keywords */ NULL, /* requirements */ SIZE, SIZE, NULL, draw)
zwcloud/CairoSharp
source/Native/cairo/test/mesh-pattern-accuracy.c
C
lgpl-3.0
3,430
/** * Copyright 2005-2007 ECMWF * * Licensed under the GNU Lesser General Public License which * incorporates the terms and conditions of version 3 of the GNU * General Public License. * See LICENSE and gpl-3.0.txt for details. */ /*************************************************************************** * Enrico Fucile * ***************************************************************************/ #include "grib_api_internal.h" /* This is used by make_class.pl START_CLASS_DEF CLASS = action IMPLEMENTS = dump IMPLEMENTS = destroy;execute MEMBERS = char *name MEMBERS = int append MEMBERS = int padtomultiple END_CLASS_DEF */ /* START_CLASS_IMP */ /* Don't edit anything between START_CLASS_IMP and END_CLASS_IMP Instead edit values between START_CLASS_DEF and END_CLASS_DEF or edit "action.class" and rerun ./make_class.pl */ static void init_class (grib_action_class*); static void dump (grib_action* d, FILE*,int); static void destroy (grib_context*,grib_action*); static int execute(grib_action* a,grib_handle* h); typedef struct grib_action_write { grib_action act; /* Members defined in write */ char *name; int append; int padtomultiple; } grib_action_write; static grib_action_class _grib_action_class_write = { 0, /* super */ "action_class_write", /* name */ sizeof(grib_action_write), /* size */ 0, /* inited */ &init_class, /* init_class */ 0, /* init */ &destroy, /* destroy */ &dump, /* dump */ 0, /* xref */ 0, /* create_accessor*/ 0, /* notify_change */ 0, /* reparse */ &execute, /* execute */ 0, /* compile */ }; grib_action_class* grib_action_class_write = &_grib_action_class_write; static void init_class(grib_action_class* c) { } /* END_CLASS_IMP */ extern int errno; grib_action* grib_action_create_write( grib_context* context, const char* name,int append,int padtomultiple) { char buf[1024]; grib_action_write* a =NULL; grib_action_class* c = grib_action_class_write; grib_action* act = (grib_action*)grib_context_malloc_clear_persistent(context,c->size); act->op = grib_context_strdup_persistent(context,"section"); act->cclass = c; a = (grib_action_write*)act; act->context = context; a->name = grib_context_strdup_persistent(context,name); sprintf(buf,"write%p",(void*)a->name); act->name = grib_context_strdup_persistent(context,buf); a->append=append; a->padtomultiple=padtomultiple; return act; } static int execute(grib_action* act, grib_handle *h) { int ioerr=0; grib_action_write* a = (grib_action_write*) act; int err =GRIB_SUCCESS; size_t size; const void* buffer=NULL; char* filename; char string[1024]={0,}; grib_file* of=NULL; if ((err=grib_get_message(h,&buffer,&size))!= GRIB_SUCCESS) { grib_context_log(act->context,GRIB_LOG_ERROR,"unable to get message\n"); return err; } if (strlen(a->name)!=0) { err = grib_recompose_name(h,NULL,a->name,string,0); filename=string; } else { filename = act->context->outfilename ? act->context->outfilename : "filter.out"; } if (a->append) of=grib_file_open(filename,"a",&err); else of=grib_file_open(filename,"w",&err); if (!of || !of->handle) { grib_context_log(act->context,GRIB_LOG_ERROR,"unable to open file %s\n",filename); return GRIB_IO_PROBLEM; } if (h->gts_header) fwrite(h->gts_header,1,h->gts_header_len,of->handle); if(fwrite(buffer,1,size,of->handle) != size) { ioerr=errno; grib_context_log(act->context,(GRIB_LOG_ERROR)|(GRIB_LOG_PERROR), "Error writing to %s",filename); return GRIB_IO_PROBLEM; } if (a->padtomultiple) { char* zeros; size_t padding=a->padtomultiple - size%a->padtomultiple; /* printf("XXX padding=%d size=%d padtomultiple=%d\n",padding,size,a->padtomultiple); */ zeros=calloc(padding,1); if(fwrite(zeros,1,padding,of->handle) != padding) { ioerr=errno; grib_context_log(act->context,(GRIB_LOG_ERROR)|(GRIB_LOG_PERROR), "Error writing to %s",filename); return GRIB_IO_PROBLEM; } free(zeros); } if (h->gts_header) { char gts_trailer[4]={'\x0D','\x0D','\x0A','\x03'}; fwrite(gts_trailer,1,4,of->handle); } grib_file_close(filename,&err); if (err != GRIB_SUCCESS) { grib_context_log(act->context,GRIB_LOG_ERROR,"unable to get message\n"); return err; } return err; } static void dump(grib_action* act, FILE* f, int lvl) { } static void destroy(grib_context* context,grib_action* act) { grib_action_write* a = (grib_action_write*) act; grib_context_free_persistent(context, a->name); grib_context_free_persistent(context, act->name); grib_context_free_persistent(context, act->op); }
erdc-cm/grib_api
src/action_class_write.c
C
lgpl-3.0
5,456
/* tio_str-- Test file for mpc_inp_str and mpc_out_str. Copyright (C) 2009, 2011, 2013, 2014 INRIA This file is part of GNU MPC. GNU MPC 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 3 of the License, or (at your option) any later version. GNU MPC 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 program. If not, see http://www.gnu.org/licenses/ . */ #include "mpc-tests.h" #ifdef HAVE_UNISTD_H #ifndef _POSIX_C_SOURCE #define _POSIX_C_SOURCE 1 /* apparently needed on Darwin */ #endif #include <unistd.h> /* for dup, dup2, STDIN_FILENO and STDOUT_FILENO */ #else #define STDIN_FILENO 0 #define STDOUT_FILENO 1 #endif extern unsigned long line_number; /* character appearing next in the file, may be EOF */ extern int nextchar; extern const char *mpc_rnd_mode[]; static void check_file (const char* file_name) { FILE *fp; int tmp; int base; int inex_re; int inex_im; mpc_t expected, got; mpc_rnd_t rnd = MPC_RNDNN; int inex = 0, expected_inex; size_t expected_size, size; known_signs_t ks = {1, 1}; fp = open_data_file (file_name); mpc_init2 (expected, 53); mpc_init2 (got, 53); /* read data file */ line_number = 1; nextchar = getc (fp); skip_whitespace_comments (fp); while (nextchar != EOF) { /* 1. read a line of data: expected result, base, rounding mode */ read_ternary (fp, &inex_re); read_ternary (fp, &inex_im); read_mpc (fp, expected, &ks); if (inex_re == TERNARY_ERROR || inex_im == TERNARY_ERROR) expected_inex = -1; else expected_inex = MPC_INEX (inex_re, inex_im); read_int (fp, &tmp, "size"); expected_size = (size_t)tmp; read_int (fp, &base, "base"); read_mpc_rounding_mode (fp, &rnd); /* 2. read string at the same precision as the expected result */ while (nextchar != '"') nextchar = getc (fp); mpfr_set_prec (mpc_realref (got), MPC_PREC_RE (expected)); mpfr_set_prec (mpc_imagref (got), MPC_PREC_IM (expected)); inex = mpc_inp_str (got, fp, &size, base, rnd); /* 3. compare this result with the expected one */ if (inex != expected_inex || !same_mpc_value (got, expected, ks) || size != expected_size) { printf ("mpc_inp_str failed (line %lu) with rounding mode %s\n", line_number, mpc_rnd_mode[rnd]); if (inex != expected_inex) printf(" got inexact value: %d\nexpected inexact value: %d\n", inex, expected_inex); if (size != expected_size) printf (" got size: %lu\nexpected size: %lu\n ", (unsigned long int) size, (unsigned long int) expected_size); printf (" "); MPC_OUT (got); MPC_OUT (expected); exit (1); } while ((nextchar = getc (fp)) != '"'); nextchar = getc (fp); skip_whitespace_comments (fp); } mpc_clear (expected); mpc_clear (got); close_data_file (fp); } static void check_io_str (mpc_ptr read_number, mpc_ptr expected) { char tmp_file[] = "mpc_test"; FILE *fp; size_t sz; if (!(fp = fopen (tmp_file, "w"))) { printf ("Error: Could not open file %s in write mode\n", tmp_file); exit (1); } mpc_out_str (fp, 10, 0, expected, MPC_RNDNN); fclose (fp); if (!(fp = fopen (tmp_file, "r"))) { printf ("Error: Could not open file %s in read mode\n", tmp_file); exit (1); }; if (mpc_inp_str (read_number, fp, &sz, 10, MPC_RNDNN) == -1) { printf ("Error: mpc_inp_str cannot correctly re-read number " "in file %s\n", tmp_file); exit (1); } fclose (fp); /* mpc_cmp set erange flag when an operand is a NaN */ mpfr_clear_flags (); if (mpc_cmp (read_number, expected) != 0 || mpfr_erangeflag_p()) { printf ("Error: inp_str o out_str <> Id\n"); MPC_OUT (read_number); MPC_OUT (expected); exit (1); } } #ifndef MPC_NO_STREAM_REDIRECTION /* test out_str with stream=NULL */ static void check_stdout (mpc_ptr read_number, mpc_ptr expected) { char tmp_file[] = "mpc_test"; int fd; size_t sz; fflush (stdout); fd = dup (STDOUT_FILENO); if (freopen (tmp_file, "w", stdout) == NULL) { printf ("mpc_inp_str cannot redirect stdout\n"); exit (1); } mpc_out_str (NULL, 2, 0, expected, MPC_RNDNN); fflush (stdout); dup2 (fd, STDOUT_FILENO); close (fd); clearerr (stdout); fflush (stdin); fd = dup (STDIN_FILENO); if (freopen (tmp_file, "r", stdin) == NULL) { printf ("mpc_inp_str cannot redirect stdout\n"); exit (1); } if (mpc_inp_str (read_number, NULL, &sz, 2, MPC_RNDNN) == -1) { printf ("mpc_inp_str cannot correctly re-read number " "in file %s\n", tmp_file); exit (1); } mpfr_clear_flags (); /* mpc_cmp set erange flag when an operand is a NaN */ if (mpc_cmp (read_number, expected) != 0 || mpfr_erangeflag_p()) { printf ("mpc_inp_str did not read the number which was written by " "mpc_out_str\n"); MPC_OUT (read_number); MPC_OUT (expected); exit (1); } fflush (stdin); dup2 (fd, STDIN_FILENO); close (fd); clearerr (stdin); } #endif /* MPC_NO_STREAM_REDIRECTION */ int main (void) { mpc_t z, x; mpfr_prec_t prec; test_start (); mpc_init2 (z, 1000); mpc_init2 (x, 1000); check_file ("inp_str.dat"); for (prec = 2; prec <= 1000; prec+=7) { mpc_set_prec (z, prec); mpc_set_prec (x, prec); mpc_set_si_si (x, 1, 1, MPC_RNDNN); check_io_str (z, x); mpc_set_si_si (x, -1, 1, MPC_RNDNN); check_io_str (z, x); mpfr_set_inf (mpc_realref(x), -1); mpfr_set_inf (mpc_imagref(x), +1); check_io_str (z, x); test_default_random (x, -1024, 1024, 128, 25); check_io_str (z, x); } #ifndef MPC_NO_STREAM_REDIRECTION mpc_set_si_si (x, 1, -4, MPC_RNDNN); mpc_div_ui (x, x, 3, MPC_RNDDU); check_stdout(z, x); #endif mpc_clear (z); mpc_clear (x); test_end (); return 0; }
evaautomation/mpc
tests/tio_str.c
C
lgpl-3.0
6,507
/** ****************************************************************************** * @file DMA/DMA_FLASHToRAM/Src/stm32f1xx_it.c * @author MCD Application Team * @version V1.3.0 * @date 18-December-2015 * @brief Main Interrupt Service Routines. * This file provides template for all exceptions handler and * peripherals interrupt service routine. ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT(c) 2015 STMicroelectronics</center></h2> * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "main.h" #include "stm32f1xx_it.h" /** @addtogroup STM32F1xx_HAL_Examples * @{ */ /** @addtogroup DMA_FLASHToRAM * @{ */ /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ extern DMA_HandleTypeDef DmaHandle; /* Private function prototypes -----------------------------------------------*/ /* Private functions ---------------------------------------------------------*/ /******************************************************************************/ /* Cortex-M3 Processor Exceptions Handlers */ /******************************************************************************/ /** * @brief This function handles NMI exception. * @param None * @retval None */ void NMI_Handler(void) { } /** * @brief This function handles Hard Fault exception. * @param None * @retval None */ void HardFault_Handler(void) { /* Go to infinite loop when Hard Fault exception occurs */ while (1) { } } /** * @brief This function handles Memory Manage exception. * @param None * @retval None */ void MemManage_Handler(void) { /* Go to infinite loop when Memory Manage exception occurs */ while (1) { } } /** * @brief This function handles Bus Fault exception. * @param None * @retval None */ void BusFault_Handler(void) { /* Go to infinite loop when Bus Fault exception occurs */ while (1) { } } /** * @brief This function handles Usage Fault exception. * @param None * @retval None */ void UsageFault_Handler(void) { /* Go to infinite loop when Usage Fault exception occurs */ while (1) { } } /** * @brief This function handles SVCall exception. * @param None * @retval None */ void SVC_Handler(void) { } /** * @brief This function handles Debug Monitor exception. * @param None * @retval None */ void DebugMon_Handler(void) { } /** * @brief This function handles PendSVC exception. * @param None * @retval None */ void PendSV_Handler(void) { } /** * @brief This function handles SysTick Handler. * @param None * @retval None */ void SysTick_Handler(void) { HAL_IncTick(); } /******************************************************************************/ /* STM32F1xx Peripherals Interrupt Handlers */ /* Add here the Interrupt Handler for the used peripheral(s) (PPP), for the */ /* available peripheral interrupt handler's name please refer to the startup */ /* file (startup_stm32f1xx.s). */ /******************************************************************************/ /** * @brief This function handles DMA channel interrupt request. * @param None * @retval None */ void DMA_INSTANCE_IRQHANDLER(void) { /* Check the interrupt and clear flag */ HAL_DMA_IRQHandler(&DmaHandle); } /** * @} */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
hyller/CodeLibrary
stm32cubef1/STM32Cube_FW_F1_V1.3.0/Projects/STM3210E_EVAL/Examples/DMA/DMA_FLASHToRAM/Src/stm32f1xx_it.c
C
unlicense
5,715
/*- * See the file LICENSE for redistribution information. * * Copyright (c) 2001, 2010 Oracle and/or its affiliates. All rights reserved. * * $Id$ */ #include "db_config.h" #include "db_int.h" /* * __os_id -- * Return the current process ID. * * PUBLIC: void __os_id __P((DB_ENV *, pid_t *, db_threadid_t*)); */ void __os_id(dbenv, pidp, tidp) DB_ENV *dbenv; pid_t *pidp; db_threadid_t *tidp; { /* * We can't depend on dbenv not being NULL, this routine is called * from places where there's no DB_ENV handle. * * We cache the pid in the ENV handle, getting the process ID is a * fairly slow call on lots of systems. */ if (pidp != NULL) { if (dbenv == NULL) { #if defined(HAVE_VXWORKS) *pidp = taskIdSelf(); #else *pidp = getpid(); #endif } else *pidp = dbenv->env->pid_cache; } if (tidp != NULL) { #if defined(DB_WIN32) *tidp = GetCurrentThreadId(); #elif defined(HAVE_MUTEX_UI_THREADS) *tidp = thr_self(); #elif defined(HAVE_PTHREAD_SELF) *tidp = pthread_self(); #else /* * Default to just getpid. */ *tidp = 0; #endif } }
racker/omnibus
source/db-5.0.26.NC/os/os_pid.c
C
apache-2.0
1,092
/* * Copyright (c) 2018 STMicroelectronics * * SPDX-License-Identifier: Apache-2.0 */ #include <zephyr.h> #include <misc/printk.h> #include <board.h> #include <gpio.h> #include <i2c.h> #include <spi.h> #include <sensor.h> /* #define ARGONKEY_TEST_LOG 1 */ #define WHOAMI_REG 0x0F #define WHOAMI_ALT_REG 0x4F static inline float out_ev(struct sensor_value *val) { return (val->val1 + (float)val->val2 / 1000000); } static int lsm6dsl_trig_cnt; #ifdef CONFIG_LSM6DSL_TRIGGER static void lsm6dsl_trigger_handler(struct device *dev, struct sensor_trigger *trig) { #ifdef ARGONKEY_TEST_LOG char out_str[64]; #endif struct sensor_value accel_x, accel_y, accel_z; struct sensor_value gyro_x, gyro_y, gyro_z; #if defined(CONFIG_LSM6DSL_EXT0_LIS2MDL) struct sensor_value magn_x, magn_y, magn_z; #endif #if defined(CONFIG_LSM6DSL_EXT0_LPS22HB) struct sensor_value press, temp; #endif lsm6dsl_trig_cnt++; sensor_sample_fetch_chan(dev, SENSOR_CHAN_ACCEL_XYZ); sensor_channel_get(dev, SENSOR_CHAN_ACCEL_X, &accel_x); sensor_channel_get(dev, SENSOR_CHAN_ACCEL_Y, &accel_y); sensor_channel_get(dev, SENSOR_CHAN_ACCEL_Z, &accel_z); #ifdef ARGONKEY_TEST_LOG sprintf(out_str, "accel (%f %f %f) m/s2", out_ev(&accel_x), out_ev(&accel_y), out_ev(&accel_z)); printk("TRIG %s\n", out_str); #endif /* lsm6dsl gyro */ sensor_sample_fetch_chan(dev, SENSOR_CHAN_GYRO_XYZ); sensor_channel_get(dev, SENSOR_CHAN_GYRO_X, &gyro_x); sensor_channel_get(dev, SENSOR_CHAN_GYRO_Y, &gyro_y); sensor_channel_get(dev, SENSOR_CHAN_GYRO_Z, &gyro_z); #ifdef ARGONKEY_TEST_LOG sprintf(out_str, "gyro (%f %f %f) dps", out_ev(&gyro_x), out_ev(&gyro_y), out_ev(&gyro_z)); printk("TRIG %s\n", out_str); #endif #if defined(CONFIG_LSM6DSL_EXT0_LIS2MDL) /* lsm6dsl magn */ sensor_sample_fetch_chan(dev, SENSOR_CHAN_MAGN_XYZ); sensor_channel_get(dev, SENSOR_CHAN_MAGN_X, &magn_x); sensor_channel_get(dev, SENSOR_CHAN_MAGN_Y, &magn_y); sensor_channel_get(dev, SENSOR_CHAN_MAGN_Z, &magn_z); #ifdef ARGONKEY_TEST_LOG sprintf(out_str, "magn (%f %f %f) gauss", out_ev(&magn_x), out_ev(&magn_y), out_ev(&magn_z)); printk("TRIG %s\n", out_str); #endif #endif #if defined(CONFIG_LSM6DSL_EXT0_LPS22HB) /* lsm6dsl press/temp */ sensor_sample_fetch_chan(dev, SENSOR_CHAN_PRESS); sensor_channel_get(dev, SENSOR_CHAN_PRESS, &press); sensor_sample_fetch_chan(dev, SENSOR_CHAN_AMBIENT_TEMP); sensor_channel_get(dev, SENSOR_CHAN_AMBIENT_TEMP, &temp); #ifdef ARGONKEY_TEST_LOG sprintf(out_str, "press (%f) kPa - temp (%f) deg", out_ev(&press), out_ev(&temp)); printk("%s\n", out_str); #endif #endif } #endif void main(void) { int cnt = 0; char out_str[64]; static struct device *led0, *led1; int i, on = 1; led0 = device_get_binding(LED0_GPIO_CONTROLLER); gpio_pin_configure(led0, LED0_GPIO_PIN, GPIO_DIR_OUT); gpio_pin_write(led0, LED0_GPIO_PIN, 1); led1 = device_get_binding(LED1_GPIO_CONTROLLER); gpio_pin_configure(led1, LED1_GPIO_PIN, GPIO_DIR_OUT); for (i = 0; i < 5; i++) { gpio_pin_write(led1, LED1_GPIO_PIN, on); k_sleep(200); on = (on == 1) ? 0 : 1; } printk("ArgonKey test!!\n"); #ifdef CONFIG_LPS22HB struct device *baro_dev = device_get_binding(CONFIG_LPS22HB_DEV_NAME); if (!baro_dev) { printk("Could not get pointer to %s sensor\n", CONFIG_LPS22HB_DEV_NAME); return; } #endif #ifdef CONFIG_HTS221 struct device *hum_dev = device_get_binding(CONFIG_HTS221_NAME); if (!hum_dev) { printk("Could not get pointer to %s sensor\n", CONFIG_HTS221_NAME); return; } #endif #ifdef CONFIG_LSM6DSL struct device *accel_dev = device_get_binding(CONFIG_LSM6DSL_DEV_NAME); if (!accel_dev) { printk("Could not get pointer to %s sensor\n", CONFIG_LSM6DSL_DEV_NAME); return; } #if defined(CONFIG_LSM6DSL_ACCEL_ODR) && (CONFIG_LSM6DSL_ACCEL_ODR == 0) struct sensor_value a_odr_attr; /* set sampling frequency to 104Hz for accel */ a_odr_attr.val1 = 104; a_odr_attr.val2 = 0; if (sensor_attr_set(accel_dev, SENSOR_CHAN_ACCEL_XYZ, SENSOR_ATTR_SAMPLING_FREQUENCY, &a_odr_attr) < 0) { printk("Cannot set sampling frequency for accelerometer.\n"); return; } #endif #if defined(CONFIG_LSM6DSL_ACCEL_FS) && (CONFIG_LSM6DSL_ACCEL_FS == 0) struct sensor_value a_fs_attr; /* set full scale to 16g for accel */ sensor_g_to_ms2(16, &a_fs_attr); if (sensor_attr_set(accel_dev, SENSOR_CHAN_ACCEL_XYZ, SENSOR_ATTR_FULL_SCALE, &a_fs_attr) < 0) { printk("Cannot set fs for accelerometer.\n"); return; } #endif #if defined(CONFIG_LSM6DSL_GYRO_ODR) && (CONFIG_LSM6DSL_GYRO_ODR == 0) struct sensor_value g_odr_attr; /* set sampling frequency to 104Hz for accel */ g_odr_attr.val1 = 104; g_odr_attr.val2 = 0; if (sensor_attr_set(accel_dev, SENSOR_CHAN_GYRO_XYZ, SENSOR_ATTR_SAMPLING_FREQUENCY, &g_odr_attr) < 0) { printk("Cannot set sampling frequency for gyro.\n"); return; } #endif #if defined(CONFIG_LSM6DSL_GYRO_FS) && (CONFIG_LSM6DSL_GYRO_FS == 0) struct sensor_value g_fs_attr; /* set full scale to 245dps for accel */ sensor_g_to_ms2(245, &g_fs_attr); if (sensor_attr_set(accel_dev, SENSOR_CHAN_GYRO_XYZ, SENSOR_ATTR_FULL_SCALE, &g_fs_attr) < 0) { printk("Cannot set fs for gyroscope.\n"); return; } #endif #endif #ifdef CONFIG_VL53L0X struct device *tof_dev = device_get_binding(CONFIG_VL53L0X_NAME); if (!tof_dev) { printk("Could not get pointer to %s sensor\n", CONFIG_VL53L0X_NAME); return; } #endif #ifdef CONFIG_LSM6DSL_TRIGGER struct sensor_trigger trig; trig.type = SENSOR_TRIG_DATA_READY; trig.chan = SENSOR_CHAN_ACCEL_XYZ; sensor_trigger_set(accel_dev, &trig, lsm6dsl_trigger_handler); #endif while (1) { #ifdef CONFIG_LPS22HB struct sensor_value temp, press; #endif #ifdef CONFIG_HTS221 struct sensor_value humidity; #endif #ifdef CONFIG_LSM6DSL struct sensor_value accel_x, accel_y, accel_z; struct sensor_value gyro_x, gyro_y, gyro_z; #if defined(CONFIG_LSM6DSL_EXT0_LIS2MDL) struct sensor_value magn_x, magn_y, magn_z; #endif #if defined(CONFIG_LSM6DSL_EXT0_LPS22HB) struct sensor_value press, temp; #endif #endif #ifdef CONFIG_VL53L0X struct sensor_value prox; #endif #ifdef CONFIG_VL53L0X sensor_sample_fetch(tof_dev); sensor_channel_get(tof_dev, SENSOR_CHAN_PROX, &prox); printk("proxy: %d ;\n", prox.val1); sensor_channel_get(tof_dev, SENSOR_CHAN_DISTANCE, &prox); printk("distance: %d -- %3d mm;\n", prox.val1, prox.val2); #endif #ifdef CONFIG_LPS22HB sensor_sample_fetch(baro_dev); sensor_channel_get(baro_dev, SENSOR_CHAN_AMBIENT_TEMP, &temp); sensor_channel_get(baro_dev, SENSOR_CHAN_PRESS, &press); printk("temp: %d.%02d C; press: %d.%06d\n", temp.val1, temp.val2, press.val1, press.val2); #endif #ifdef CONFIG_HTS221 sensor_sample_fetch(hum_dev); sensor_channel_get(hum_dev, SENSOR_CHAN_HUMIDITY, &humidity); printk("humidity: %d.%06d\n", humidity.val1, humidity.val2); #endif #ifdef CONFIG_LSM6DSL /* lsm6dsl accel */ sensor_sample_fetch_chan(accel_dev, SENSOR_CHAN_ACCEL_XYZ); sensor_channel_get(accel_dev, SENSOR_CHAN_ACCEL_X, &accel_x); sensor_channel_get(accel_dev, SENSOR_CHAN_ACCEL_Y, &accel_y); sensor_channel_get(accel_dev, SENSOR_CHAN_ACCEL_Z, &accel_z); sprintf(out_str, "accel (%f %f %f) m/s2", out_ev(&accel_x), out_ev(&accel_y), out_ev(&accel_z)); printk("%s\n", out_str); /* lsm6dsl gyro */ sensor_sample_fetch_chan(accel_dev, SENSOR_CHAN_GYRO_XYZ); sensor_channel_get(accel_dev, SENSOR_CHAN_GYRO_X, &gyro_x); sensor_channel_get(accel_dev, SENSOR_CHAN_GYRO_Y, &gyro_y); sensor_channel_get(accel_dev, SENSOR_CHAN_GYRO_Z, &gyro_z); sprintf(out_str, "gyro (%f %f %f) dps", out_ev(&gyro_x), out_ev(&gyro_y), out_ev(&gyro_z)); printk("%s\n", out_str); #if defined(CONFIG_LSM6DSL_EXT0_LIS2MDL) /* lsm6dsl magn */ sensor_sample_fetch_chan(accel_dev, SENSOR_CHAN_MAGN_XYZ); sensor_channel_get(accel_dev, SENSOR_CHAN_MAGN_X, &magn_x); sensor_channel_get(accel_dev, SENSOR_CHAN_MAGN_Y, &magn_y); sensor_channel_get(accel_dev, SENSOR_CHAN_MAGN_Z, &magn_z); sprintf(out_str, "magn (%f %f %f) gauss", out_ev(&magn_x), out_ev(&magn_y), out_ev(&magn_z)); printk("%s\n", out_str); #endif #if defined(CONFIG_LSM6DSL_EXT0_LPS22HB) /* lsm6dsl press/temp */ sensor_sample_fetch_chan(accel_dev, SENSOR_CHAN_PRESS); sensor_channel_get(accel_dev, SENSOR_CHAN_PRESS, &press); sensor_sample_fetch_chan(accel_dev, SENSOR_CHAN_AMBIENT_TEMP); sensor_channel_get(accel_dev, SENSOR_CHAN_AMBIENT_TEMP, &temp); sprintf(out_str, "press (%f) kPa - temp (%f) deg", out_ev(&press), out_ev(&temp)); printk("%s\n", out_str); #endif #endif /* CONFIG_LSM6DSL */ printk("- (%d) (trig_cnt: %d)\n\n", ++cnt, lsm6dsl_trig_cnt); k_sleep(2000); } }
mbolivar/zephyr
samples/boards/96b_argonkey/src/main.c
C
apache-2.0
8,806
#include "config/config.h" #include <sys/types.h> #include <sys/wait.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <sys/errno.h> #include <string.h> #include "dispatch_test.h" #define _test_print(_file, _line, _desc, \ _expr, _fmt1, _val1, _fmt2, _val2) do { \ const char* _exprstr = _expr ? "PASS" : "FAIL"; \ char _linestr[BUFSIZ]; \ if (!_expr) { \ snprintf(_linestr, sizeof(_linestr), \ " (%s:%ld)", _file, _line); \ } else { \ _linestr[0] = 0; \ } \ if (_fmt2 == 0) { \ printf("\tValue: " _fmt1 "\n" \ "[%s] %s%s\n", \ _val1, \ _exprstr, \ _desc, \ _linestr); \ } else { \ printf("\tActual: " _fmt1 "\n" \ "\tExpected: " _fmt2 "\n" \ "[%s] %s%s\n", \ _val1, \ _val2, \ _exprstr, \ _desc, \ _linestr); \ } \ if (!_expr) { \ printf("\t%s:%ld\n", _file, _line); \ } \ fflush(stdout); \ } while (0); void test_start(const char* desc) { printf("\n==================================================\n"); printf("[TEST] %s\n", desc); printf("[PID] %d\n", getpid()); printf("==================================================\n\n"); usleep(100000); // give 'gdb --waitfor=' a chance to find this proc } #define test_ptr_null(a,b) _test_ptr_null(__FILE__, __LINE__, a, b) void _test_ptr_null(const char* file, long line, const char* desc, const void* ptr) { _test_print(file, line, desc, (ptr == NULL), "%p", ptr, "%p", (void*)0); } #define test_ptr_notnull(a,b) _test_ptr_notnull(__FILE__, __LINE__, a, b) void _test_ptr_notnull(const char* file, long line, const char* desc, const void* ptr) { _test_print(file, line, desc, (ptr != NULL), "%p", ptr, "%p", ptr ?: (void*)~0); } #define test_ptr(a,b,c) _test_ptr(__FILE__, __LINE__, a, b, c) void _test_ptr(const char* file, long line, const char* desc, const void* actual, const void* expected) { _test_print(file, line, desc, (actual == expected), "%p", actual, "%p", expected); } #define test_long(a,b,c) _test_long(__FILE__, __LINE__, a, b, c) void _test_long(const char* file, long line, const char* desc, long actual, long expected) { _test_print(file, line, desc, (actual == expected), "%ld", actual, "%ld", expected); } #define test_long_less_than(a, b, c) _test_long_less_than(__FILE__, __LINE__, a, b, c) void _test_long_less_than(const char* file, long line, const char* desc, long actual, long expected_max) { _test_print(file, line, desc, (actual < expected_max), "%ld", actual, "<%ld", expected_max); } #define test_double_less_than(d, v, m) _test_double_less_than(__FILE__, __LINE__, d, v, m) void _test_double_less_than(const char* file, long line, const char* desc, double val, double max_expected) { _test_print(file, line, desc, (val < max_expected), "%f", val, "<%f", max_expected); } #define test_double_less_than_or_equal(d, v, m) _test_double_less_than(__FILE__, __LINE__, d, v, m) void _test_double_less_than_or_equal(const char* file, long line, const char* desc, double val, double max_expected) { _test_print(file, line, desc, (val <= max_expected), "%f", val, "<%f", max_expected); } #define test_errno(a,b,c) _test_errno(__FILE__, __LINE__, a, b, c) void _test_errno(const char* file, long line, const char* desc, long actual, long expected) { char* actual_str; char* expected_str; asprintf(&actual_str, "%ld\t%s", actual, actual ? strerror(actual) : ""); asprintf(&expected_str, "%ld\t%s", expected, expected ? strerror(expected) : ""); _test_print(file, line, desc, (actual == expected), "%s", actual_str, "%s", expected_str); free(actual_str); free(expected_str); } //#include <spawn.h> extern char **environ; void test_stop(void) { test_stop_after_delay((void *)(intptr_t)0); } void test_stop_after_delay(void *delay) { #if HAVE_LEAKS int res; pid_t pid; char pidstr[10]; #endif if (delay != NULL) { sleep((int)(intptr_t)delay); } #if HAVE_LEAKS if (getenv("NOLEAKS")) _exit(EXIT_SUCCESS); /* leaks doesn't work against debug variant malloc */ if (getenv("DYLD_IMAGE_SUFFIX")) _exit(EXIT_SUCCESS); snprintf(pidstr, sizeof(pidstr), "%d", getpid()); char* args[] = { "./leaks-wrapper", pidstr, NULL }; res = posix_spawnp(&pid, args[0], NULL, NULL, args, environ); if (res == 0 && pid > 0) { int status; waitpid(pid, &status, 0); test_long("Leaks", status, 0); } else { perror(args[0]); } #endif _exit(EXIT_SUCCESS); }
JackieXie168/libdispatch
doc/opengcd/trunk/libdispatch-197/testing/dispatch_test.c
C
apache-2.0
4,442
/* * OCILIB - C Driver for Oracle (C Wrapper for Oracle OCI) * * Website: http://www.ocilib.net * * Copyright (c) 2007-2016 Vincent ROGIER <vince.rogier@ocilib.net> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "ocilib_internal.h" /* ********************************************************************************************* * * STRINGS MESSAGES * ********************************************************************************************* */ static otext * OCILib_TypeNames[OCI_IPC_COUNT] = { OTEXT("Oracle memory"), OTEXT("boolean pointer"), OTEXT("generic pointer"), OTEXT("short pointer"), OTEXT("int pointer"), OTEXT("big_int pointer"), OTEXT("double pointer"), OTEXT("float pointer"), OTEXT("string pointer"), OTEXT("function callback"), OTEXT("Error handle"), OTEXT("TypeInfo handle"), OTEXT("Connection handle"), OTEXT("Pool handle"), OTEXT("Transaction handle"), OTEXT("Statement handle"), OTEXT("Resultset handle"), OTEXT("Column handle"), OTEXT("Date handle"), OTEXT("Timestamp handle"), OTEXT("Interval handle"), OTEXT("Lob handle"), OTEXT("File handle"), OTEXT("Long handle"), OTEXT("Object handle"), OTEXT("Collection handle"), OTEXT("Collection iterator handle"), OTEXT("Collection element handle"), OTEXT("Hash Table handle"), OTEXT("Thread handle"), OTEXT("Mutex handle"), OTEXT("Bind handle"), OTEXT("Ref handle"), OTEXT("Direct Path handle"), OTEXT("Subscription handle"), OTEXT("Event handle"), OTEXT("Array handle"), OTEXT("Message handle"), OTEXT("Enqueue handle"), OTEXT("Dequeue handle"), OTEXT("Agent handle"), OTEXT("Internal list handle"), OTEXT("Internal list item handle"), OTEXT("Internal array of bind handles"), OTEXT("Internal define handle"), OTEXT("Internal array of define handles"), OTEXT("Internal hash entry handle"), OTEXT("Internal array of hash entry handles"), OTEXT("Internal hash value handle"), OTEXT("Internal thread key handle"), OTEXT("Internal Oracle date handle"), OTEXT("Internal C time structure"), OTEXT("Internal array of resultset handles"), OTEXT("Internal array of PL/SQL sizes integers"), OTEXT("Internal array of PL/SQL return codes integers"), OTEXT("Internal server output handle"), OTEXT("Internal array of indicator integers"), OTEXT("Internal array of buffer length integers"), OTEXT("Internal array of data buffers"), OTEXT("Internal Long handle data buffer"), OTEXT("Internal trace info structure"), OTEXT("Internal array of direct path columns"), OTEXT("Internal array of batch error objects") }; #if defined(OCI_CHARSET_WIDE) && !defined(_MSC_VER) static otext * OCILib_ErrorMsg[OCI_ERR_COUNT] = { OTEXT("No error"), OTEXT("OCILIB has not been initialized"), OTEXT("Cannot load OCI shared library (%ls)"), OTEXT("Cannot load OCI symbols from shared library"), OTEXT("OCILIB has not been initialized in multi threaded mode"), OTEXT("Memory allocation failure (type %ls, size : %d)"), OTEXT("Feature not available (%ls) "), OTEXT("A null %ls has been provided"), OTEXT("Oracle data type (sql code %d) not supported for this operation "), OTEXT("Unknown identifier %c while parsing SQL"), OTEXT("Unknown argument %d while retrieving data"), OTEXT("Index %d out of bounds"), OTEXT("Found %d non freed %ls"), OTEXT("Maximum number of binds (%d) already reached"), OTEXT("Object attribute '%ls' not found"), OTEXT("The integer parameter value must be at least %d"), OTEXT("Elements are not compatible"), OTEXT("The statement must be %ls to perform this operation"), OTEXT("The statement is not scrollable"), OTEXT("Name or position '%ls' already binded to the statement"), OTEXT("Invalid new size for bind arrays (initial %d, current %d, new %d)"), OTEXT("Column '%ls' not find in table '%ls'"), OTEXT("Unable to perform this operation on a %ls direct path process"), OTEXT("Cannot create OCI environment"), OTEXT("Name or position '%ls' previously binded with different data type"), OTEXT("Object '%ls' type does not match the requested object type"), OTEXT("Item '%ls' (type %d) not found"), OTEXT("Argument '%ls' : Invalid value %d") }; #else static otext * OCILib_ErrorMsg[OCI_ERR_COUNT] = { OTEXT("No error"), OTEXT("OCILIB has not been initialized"), OTEXT("Cannot load OCI shared library (%s)"), OTEXT("Cannot load OCI symbols from shared library"), OTEXT("OCILIB has not been initialized in multi threaded mode"), OTEXT("Memory allocation failure (type %s, size : %d)"), OTEXT("Feature not available (%s) "), OTEXT("A null %s has been provided"), OTEXT("Oracle data type (sql code %d) not supported for this operation "), OTEXT("Unknown identifier %c while parsing SQL : "), OTEXT("Unknown argument %d while retrieving data"), OTEXT("Index %d out of bounds"), OTEXT("Found %d non freed %s"), OTEXT("Maximum number of binds (%d) already reached"), OTEXT("Object attribute '%s' not found"), OTEXT("The integer parameter value must be at least %d"), OTEXT("Elements are not compatible"), OTEXT("The statement must be %s to perform this operation"), OTEXT("The statement is not scrollable"), OTEXT("Name or position '%s' already binded to the statement"), OTEXT("Invalid new size for bind arrays (initial %d, current %d, new %d)"), OTEXT("Column '%s' not find in table '%s'"), OTEXT("Unable to perform this operation on a %s direct path process"), OTEXT("Cannot create OCI environment"), OTEXT("Name or position '%s' previously binded with different datatype"), OTEXT("Object '%s' type does not match the requested object type"), OTEXT("Item '%s' (type %d) not found"), OTEXT("Argument '%s' : Invalid value %d") }; #endif static otext * OCILib_OraFeatures[OCI_FEATURE_COUNT] = { OTEXT("Oracle 9.0 support for Unicode data"), OTEXT("Oracle 9.0 Timestamps and Intervals"), OTEXT("Oracle 9.2 Direct path date caching"), OTEXT("Oracle 9.2 Statement caching"), OTEXT("Oracle 10g R1 LOBs size extensions"), OTEXT("Oracle 10g R2 Database change notification"), OTEXT("Oracle 10g R2 remote database startup/shutdown"), OTEXT("Oracle 10g R2 High Availability"), OTEXT("Oracle XA Connections"), OTEXT("Oracle 12c R1 PL/SQL extended support") }; typedef struct OCI_StmtStateTable { int state; otext *name; } OCI_StmtStateTable; static OCI_StmtStateTable OCILib_StmtStates[OCI_STMT_STATES_COUNT] = { { OCI_STMT_CLOSED, OTEXT("closed") }, { OCI_STMT_PARSED, OTEXT("parsed") }, { OCI_STMT_PREPARED, OTEXT("prepared") }, { OCI_STMT_DESCRIBED, OTEXT("described") }, { OCI_STMT_EXECUTED, OTEXT("executed") } }; static otext * OCILib_DirPathStates[OCI_DPS_COUNT] = { OTEXT("non prepared"), OTEXT("prepared"), OTEXT("converted"), OTEXT("terminated") }; static otext * OCILib_HandleNames[OCI_HDLE_COUNT] = { OTEXT("OCI handle"), OTEXT("OCI descriptors"), OTEXT("OCI Object handles") }; /* ********************************************************************************************* * * PRIVATE FUNCTIONS * ********************************************************************************************* */ /* --------------------------------------------------------------------------------------------- * * OCI_ExceptionGetError * --------------------------------------------------------------------------------------------- */ OCI_Error * OCI_ExceptionGetError ( void ) { OCI_Error *err = OCI_ErrorGet(TRUE); if (err) { OCI_ErrorReset(err); } return err; } /* --------------------------------------------------------------------------------------------- * * OCI_ExceptionRaise * --------------------------------------------------------------------------------------------- */ void OCI_ExceptionRaise ( OCI_Error *err ) { if (err) { err->active = TRUE; if (OCILib.error_handler) { OCILib.error_handler(err); } err->active = FALSE; } } /* --------------------------------------------------------------------------------------------- * * OCI_ExceptionOCI * --------------------------------------------------------------------------------------------- */ void OCI_ExceptionOCI ( OCIError *p_err, OCI_Connection *con, OCI_Statement *stmt, boolean warning ) { OCI_Error *err = OCI_ExceptionGetError(); if (err) { int dbsize = (int) (osizeof(err->str) - (size_t) 1); dbtext *dbstr = OCI_StringGetOracleString(err->str, &dbsize); err->type = (warning ? OCI_ERR_WARNING : OCI_ERR_ORACLE); err->con = con; err->stmt = stmt; /* get oracle description */ OCIErrorGet((dvoid *) p_err, (ub4) 1, (OraText *) NULL, &err->sqlcode, (OraText *) dbstr, (ub4) dbsize, (ub4) OCI_HTYPE_ERROR); OCI_StringCopyOracleStringToNativeString(dbstr, err->str, dbcharcount(dbsize)); OCI_StringReleaseOracleString(dbstr); } OCI_ExceptionRaise(err); } /* --------------------------------------------------------------------------------------------- * * OCI_ExceptionNotInitialized * --------------------------------------------------------------------------------------------- */ void OCI_ExceptionNotInitialized ( void ) { OCI_Error *err = OCI_ExceptionGetError(); if (err) { err->type = OCI_ERR_OCILIB; err->libcode = OCI_ERR_NOT_INITIALIZED; ostrncat(err->str, OCILib_ErrorMsg[OCI_ERR_NOT_INITIALIZED], osizeof(err->str) - (size_t) 1); } OCI_ExceptionRaise(err); } /* --------------------------------------------------------------------------------------------- * * OCI_ExceptionLoadingShareLib * --------------------------------------------------------------------------------------------- */ void OCI_ExceptionLoadingSharedLib ( void ) { #ifdef OCI_IMPORT_RUNTIME OCI_Error *err = OCI_ExceptionGetError(); if (err) { err->type = OCI_ERR_OCILIB; err->libcode = OCI_ERR_LOADING_SHARED_LIB; osprintf(err->str, osizeof(err->str) - (size_t) 1, OCILib_ErrorMsg[OCI_ERR_LOADING_SHARED_LIB], OCI_DL_META_NAME); } OCI_ExceptionRaise(err); #endif } /* --------------------------------------------------------------------------------------------- * * OCI_ExceptionLoadingSymbols * --------------------------------------------------------------------------------------------- */ void OCI_ExceptionLoadingSymbols ( void ) { OCI_Error *err = OCI_ExceptionGetError(); if (err) { err->type = OCI_ERR_OCILIB; err->libcode = OCI_ERR_LOADING_SYMBOLS; ostrncat(err->str, OCILib_ErrorMsg[OCI_ERR_LOADING_SYMBOLS], osizeof(err->str) - (size_t) 1); } OCI_ExceptionRaise(err); } /* --------------------------------------------------------------------------------------------- * * OCI_ExceptionNotMultithreaded * --------------------------------------------------------------------------------------------- */ void OCI_ExceptionNotMultithreaded ( void ) { OCI_Error *err = OCI_ExceptionGetError(); if (err) { err->type = OCI_ERR_OCILIB; err->libcode = OCI_ERR_MULTITHREADED; ostrncat(err->str, OCILib_ErrorMsg[OCI_ERR_MULTITHREADED], osizeof(err->str) - (size_t) 1); } OCI_ExceptionRaise(err); } /* --------------------------------------------------------------------------------------------- * * OCI_ExceptionNullPointer * --------------------------------------------------------------------------------------------- */ void OCI_ExceptionNullPointer ( int type ) { OCI_Error *err = OCI_ExceptionGetError(); if (err) { err->type = OCI_ERR_OCILIB; err->libcode = OCI_ERR_NULL_POINTER; osprintf(err->str, osizeof(err->str) - (size_t) 1, OCILib_ErrorMsg[OCI_ERR_NULL_POINTER], OCILib_TypeNames[type+1]); } OCI_ExceptionRaise(err); } /* --------------------------------------------------------------------------------------------- * * OCI_ExceptionMemory * --------------------------------------------------------------------------------------------- */ void OCI_ExceptionMemory ( int type, size_t nb_bytes, OCI_Connection *con, OCI_Statement *stmt ) { OCI_Error *err = OCI_ExceptionGetError(); if (err) { err->type = OCI_ERR_OCILIB; err->libcode = OCI_ERR_MEMORY; err->con = con; err->stmt = stmt; osprintf(err->str, osizeof(err->str) - (size_t) 1, OCILib_ErrorMsg[OCI_ERR_MEMORY], OCILib_TypeNames[type+1], nb_bytes); } OCI_ExceptionRaise(err); } /* --------------------------------------------------------------------------------------------- * * OCI_ExceptionNotAvailable * --------------------------------------------------------------------------------------------- */ void OCI_ExceptionNotAvailable ( OCI_Connection *con, int feature ) { OCI_Error *err = OCI_ExceptionGetError(); if (err) { err->type = OCI_ERR_OCILIB; err->libcode = OCI_ERR_NOT_AVAILABLE; err->con = con; osprintf(err->str, osizeof(err->str) - (size_t) 1, OCILib_ErrorMsg[OCI_ERR_NOT_AVAILABLE], OCILib_OraFeatures[feature-1]); } OCI_ExceptionRaise(err); } /* --------------------------------------------------------------------------------------------- * * OCI_ExceptionDatatypeNotSupported * --------------------------------------------------------------------------------------------- */ void OCI_ExceptionDatatypeNotSupported ( OCI_Connection *con, OCI_Statement *stmt, int code ) { OCI_Error *err = OCI_ExceptionGetError(); if (err) { err->type = OCI_ERR_OCILIB; err->libcode = OCI_ERR_DATATYPE_NOT_SUPPORTED; err->con = con; err->stmt = stmt; osprintf(err->str, osizeof(err->str) - (size_t) 1, OCILib_ErrorMsg[OCI_ERR_DATATYPE_NOT_SUPPORTED], code); } OCI_ExceptionRaise(err); } /* --------------------------------------------------------------------------------------------- * * OCI_ExceptionParsingError * --------------------------------------------------------------------------------------------- */ void OCI_ExceptionParsingToken ( OCI_Connection *con, OCI_Statement *stmt, otext token ) { OCI_Error *err = OCI_ExceptionGetError(); if (err) { err->type = OCI_ERR_OCILIB; err->libcode = OCI_ERR_PARSE_TOKEN; err->con = con; err->stmt = stmt; osprintf(err->str, osizeof(err->str) - (size_t) 1, OCILib_ErrorMsg[OCI_ERR_PARSE_TOKEN], token); } OCI_ExceptionRaise(err); } /* --------------------------------------------------------------------------------------------- * * OCI_ExceptionMappingArgument * --------------------------------------------------------------------------------------------- */ void OCI_ExceptionMappingArgument ( OCI_Connection *con, OCI_Statement *stmt, int arg ) { OCI_Error *err = OCI_ExceptionGetError(); if (err) { err->type = OCI_ERR_OCILIB; err->libcode = OCI_ERR_MAP_ARGUMENT; err->con = con; err->stmt = stmt; osprintf(err->str, osizeof(err->str) - (size_t) 1, OCILib_ErrorMsg[OCI_ERR_MAP_ARGUMENT], arg); } OCI_ExceptionRaise(err); } /* --------------------------------------------------------------------------------------------- * * OCI_ExceptionOutOfBounds * --------------------------------------------------------------------------------------------- */ void OCI_ExceptionOutOfBounds ( OCI_Connection *con, int value ) { OCI_Error *err = OCI_ExceptionGetError(); if (err) { err->type = OCI_ERR_OCILIB; err->libcode = OCI_ERR_OUT_OF_BOUNDS; err->con = con; osprintf(err->str, osizeof(err->str) - (size_t) 1, OCILib_ErrorMsg[OCI_ERR_OUT_OF_BOUNDS], value); } OCI_ExceptionRaise(err); } /* --------------------------------------------------------------------------------------------- * * OCI_ExceptionUnfreedData * --------------------------------------------------------------------------------------------- */ void OCI_ExceptionUnfreedData ( int type_elem, int nb_elem ) { OCI_Error *err = OCI_ExceptionGetError(); if (err) { err->type = OCI_ERR_OCILIB; err->libcode = OCI_ERR_UNFREED_DATA; osprintf(err->str, osizeof(err->str) - (size_t) 1, OCILib_ErrorMsg[OCI_ERR_UNFREED_DATA], nb_elem, OCILib_HandleNames[type_elem-1]); } OCI_ExceptionRaise(err); } /* --------------------------------------------------------------------------------------------- * * OCI_ExceptionRuntimeLoading * --------------------------------------------------------------------------------------------- */ void OCI_ExceptionMaxBind ( OCI_Statement *stmt ) { OCI_Error *err = OCI_ExceptionGetError(); if (err) { err->type = OCI_ERR_OCILIB; err->libcode = OCI_ERR_MAX_BIND; err->stmt = stmt; if (stmt) { err->con = stmt->con; } osprintf(err->str, osizeof(err->str) - (size_t) 1, OCILib_ErrorMsg[OCI_ERR_MAX_BIND], OCI_BIND_MAX); } OCI_ExceptionRaise(err); } /* --------------------------------------------------------------------------------------------- * * OCI_ExceptionAttributeNotFound * --------------------------------------------------------------------------------------------- */ void OCI_ExceptionAttributeNotFound ( OCI_Connection *con, const otext *attr ) { OCI_Error *err = OCI_ExceptionGetError(); if (err) { err->type = OCI_ERR_OCILIB; err->libcode = OCI_ERR_ATTR_NOT_FOUND; err->con = con; osprintf(err->str, osizeof(err->str) - (size_t) 1, OCILib_ErrorMsg[OCI_ERR_ATTR_NOT_FOUND], attr); } OCI_ExceptionRaise(err); } /* --------------------------------------------------------------------------------------------- * * OCI_ExceptionMinimumValue * --------------------------------------------------------------------------------------------- */ void OCI_ExceptionMinimumValue ( OCI_Connection *con, OCI_Statement *stmt, int min ) { OCI_Error *err = OCI_ExceptionGetError(); if (err) { err->type = OCI_ERR_OCILIB; err->libcode = OCI_ERR_MIN_VALUE; err->con = con; err->stmt = stmt; osprintf(err->str, osizeof(err->str) - (size_t) 1, OCILib_ErrorMsg[OCI_ERR_MIN_VALUE], min); } OCI_ExceptionRaise(err); } /* --------------------------------------------------------------------------------------------- * * OCI_ExceptionTypeNotCompatible * --------------------------------------------------------------------------------------------- */ void OCI_ExceptionTypeNotCompatible ( OCI_Connection *con ) { OCI_Error *err = OCI_ExceptionGetError(); if (err) { err->type = OCI_ERR_OCILIB; err->libcode = OCI_ERR_NOT_COMPATIBLE; err->con = con; ostrncat(err->str, OCILib_ErrorMsg[OCI_ERR_NOT_COMPATIBLE], osizeof(err->str) - (size_t) 1); } OCI_ExceptionRaise(err); } /* --------------------------------------------------------------------------------------------- * * OCI_ExceptionStatementState * --------------------------------------------------------------------------------------------- */ void OCI_ExceptionStatementState ( OCI_Statement *stmt, int state ) { OCI_Error *err = OCI_ExceptionGetError(); if (err) { int i, index = 0; err->type = OCI_ERR_OCILIB; err->libcode = OCI_ERR_STMT_STATE; err->stmt = stmt; if (stmt) { err->con = stmt->con; } for(i = 0; i < OCI_STMT_STATES_COUNT; i++) { if (state == OCILib_StmtStates[i].state) { index = i; break; } } osprintf(err->str, osizeof(err->str) - (size_t) 1, OCILib_ErrorMsg[OCI_ERR_STMT_STATE], OCILib_StmtStates[index].name); } OCI_ExceptionRaise(err); } /* --------------------------------------------------------------------------------------------- * * OCI_ExceptionStatementNotScrollable * --------------------------------------------------------------------------------------------- */ void OCI_ExceptionStatementNotScrollable ( OCI_Statement *stmt ) { OCI_Error *err = OCI_ExceptionGetError(); if (err) { err->type = OCI_ERR_OCILIB; err->libcode = OCI_ERR_STMT_NOT_SCROLLABLE; err->stmt = stmt; if (stmt) { err->con = stmt->con; } ostrncat(err->str, OCILib_ErrorMsg[OCI_ERR_STMT_NOT_SCROLLABLE], osizeof(err->str) - (size_t) 1); } OCI_ExceptionRaise(err); } /* --------------------------------------------------------------------------------------------- * * OCI_ExceptionBindAlreadyUsed * --------------------------------------------------------------------------------------------- */ void OCI_ExceptionBindAlreadyUsed ( OCI_Statement *stmt, const otext * bind ) { OCI_Error *err = OCI_ExceptionGetError(); if (err) { err->type = OCI_ERR_OCILIB; err->libcode = OCI_ERR_BIND_ALREADY_USED; err->stmt = stmt; if (stmt) { err->con = stmt->con; } osprintf(err->str, osizeof(err->str) - (size_t) 1, OCILib_ErrorMsg[OCI_ERR_BIND_ALREADY_USED], bind); } OCI_ExceptionRaise(err); } /* --------------------------------------------------------------------------------------------- * * OCI_ExceptionBindArraySize * --------------------------------------------------------------------------------------------- */ void OCI_ExceptionBindArraySize ( OCI_Statement *stmt, unsigned int maxsize, unsigned int cursize, unsigned int newsize ) { OCI_Error *err = OCI_ExceptionGetError(); if (err) { err->type = OCI_ERR_OCILIB; err->libcode = OCI_ERR_BIND_ARRAY_SIZE; err->stmt = stmt; if (stmt) { err->con = stmt->con; } osprintf(err->str, osizeof(err->str) - (size_t) 1, OCILib_ErrorMsg[OCI_ERR_BIND_ARRAY_SIZE], maxsize, cursize, newsize); } OCI_ExceptionRaise(err); } /* --------------------------------------------------------------------------------------------- * * OCI_ExceptionDirPathColNotFound * --------------------------------------------------------------------------------------------- */ void OCI_ExceptionDirPathColNotFound ( OCI_DirPath *dp, const otext * column, const otext *table ) { OCI_Error *err = OCI_ExceptionGetError(); if (err) { err->type = OCI_ERR_OCILIB; err->libcode = OCI_ERR_DIRPATH_STATE; err->stmt = NULL; if (dp) { err->con = dp->con; } osprintf(err->str, osizeof(err->str) - (size_t) 1, OCILib_ErrorMsg[OCI_ERR_COLUMN_NOT_FOUND], column, table); } OCI_ExceptionRaise(err); } /* --------------------------------------------------------------------------------------------- * * OCI_ExceptionDirPathState * --------------------------------------------------------------------------------------------- */ void OCI_ExceptionDirPathState ( OCI_DirPath *dp, int state ) { OCI_Error *err = OCI_ExceptionGetError(); if (err) { err->type = OCI_ERR_OCILIB; err->libcode = OCI_ERR_DIRPATH_STATE; err->stmt = NULL; if (dp) { err->con = dp->con; } osprintf(err->str, osizeof(err->str) - (size_t) 1, OCILib_ErrorMsg[OCI_ERR_DIRPATH_STATE], OCILib_DirPathStates[state-1]); } OCI_ExceptionRaise(err); } /* --------------------------------------------------------------------------------------------- * * OCI_ExceptionOCIEnvironment * --------------------------------------------------------------------------------------------- */ void OCI_ExceptionOCIEnvironment ( void ) { OCI_Error *err = OCI_ExceptionGetError(); if (err) { err->type = OCI_ERR_OCILIB; err->libcode = OCI_ERR_CREATE_OCI_ENVIRONMENT; ostrncat(err->str, OCILib_ErrorMsg[OCI_ERR_CREATE_OCI_ENVIRONMENT], osizeof(err->str) - (size_t) 1); } OCI_ExceptionRaise(err); } /* --------------------------------------------------------------------------------------------- * * OCI_ExceptionRebindBadDatatype * --------------------------------------------------------------------------------------------- */ void OCI_ExceptionRebindBadDatatype ( OCI_Statement *stmt, const otext * bind ) { OCI_Error *err = OCI_ExceptionGetError(); if (err) { err->type = OCI_ERR_OCILIB; err->libcode = OCI_ERR_REBIND_BAD_DATATYPE; err->stmt = stmt; if (stmt) { err->con = stmt->con; } osprintf(err->str, osizeof(err->str) - (size_t) 1, OCILib_ErrorMsg[OCI_ERR_REBIND_BAD_DATATYPE], bind); } OCI_ExceptionRaise(err); } /* --------------------------------------------------------------------------------------------- * * OCI_ExceptionTypeInfoWrongType * --------------------------------------------------------------------------------------------- */ void OCI_ExceptionTypeInfoWrongType ( OCI_Connection *con, const otext * name ) { OCI_Error *err = OCI_ExceptionGetError(); if (err) { err->type = OCI_ERR_OCILIB; err->libcode = OCI_ERR_TYPEINFO_DATATYPE; err->stmt = NULL; err->con = con; osprintf(err->str, osizeof(err->str) - (size_t) 1, OCILib_ErrorMsg[OCI_ERR_TYPEINFO_DATATYPE], name); } OCI_ExceptionRaise(err); } /* --------------------------------------------------------------------------------------------- * * OCI_ExceptionItemNotFound * --------------------------------------------------------------------------------------------- */ void OCI_ExceptionItemNotFound ( OCI_Connection *con, OCI_Statement *stmt, const otext *name, unsigned int type ) { OCI_Error *err = OCI_ExceptionGetError(); if (err) { err->type = OCI_ERR_OCILIB; err->libcode = OCI_ERR_ITEM_NOT_FOUND; err->stmt = stmt; err->con = con; osprintf(err->str, osizeof(err->str) - (size_t)1, OCILib_ErrorMsg[OCI_ERR_ITEM_NOT_FOUND], name, type); } OCI_ExceptionRaise(err); } /* --------------------------------------------------------------------------------------------- * * OCI_ExceptionArgInvalidValue * --------------------------------------------------------------------------------------------- */ void OCI_ExceptionArgInvalidValue ( OCI_Connection *con, OCI_Statement *stmt, const otext *name, unsigned int value ) { OCI_Error *err = OCI_ExceptionGetError(); if (err) { err->type = OCI_ERR_OCILIB; err->libcode = OCI_ERR_ITEM_NOT_FOUND; err->stmt = stmt; err->con = con; osprintf(err->str, osizeof(err->str) - (size_t)1, OCILib_ErrorMsg[OCI_ERR_ARG_INVALID_VALUE], name, value); } OCI_ExceptionRaise(err); }
ysmgigi/dbss
src/ocilib-4.2.1/src/exception.c
C
apache-2.0
30,607
/* * $Id$ * Copyright (C) 2008 AIST, National Institute of Advanced Industrial Science and Technology */ /* * took from Ruby. Thank you, Ruby! */ int endian() { static int init = 0; static int endian = 0; char *p; if (init) return endian; init = 1; p = &init; return endian = p[0]?1:0; }
ohkawatks/orbe
repository/AIST/sw_services/orbe_src_v1_00_a/src/endianCheck.c
C
apache-2.0
321
/* * Copyright (c) 2017 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #define DT_DRV_COMPAT plantower_pms7003 /* sensor pms7003.c - Driver for plantower PMS7003 sensor * PMS7003 product: http://www.plantower.com/en/content/?110.html * PMS7003 spec: http://aqicn.org/air/view/sensor/spec/pms7003.pdf */ #include <errno.h> #include <arch/cpu.h> #include <init.h> #include <kernel.h> #include <drivers/sensor.h> #include <stdlib.h> #include <string.h> #include <drivers/uart.h> #include <logging/log.h> LOG_MODULE_REGISTER(PMS7003, CONFIG_SENSOR_LOG_LEVEL); /* wait serial output with 1000ms timeout */ #define CFG_PMS7003_SERIAL_TIMEOUT 1000 struct pms7003_data { const struct device *uart_dev; uint16_t pm_1_0; uint16_t pm_2_5; uint16_t pm_10; }; /** * @brief wait for an array data from uart device with a timeout * * @param dev the uart device * @param data the data array to be matched * @param len the data array len * @param timeout the timeout in milliseconds * @return 0 if success; -ETIME if timeout */ static int uart_wait_for(const struct device *dev, uint8_t *data, int len, int timeout) { int matched_size = 0; int64_t timeout_time = k_uptime_get() + K_MSEC(timeout); while (1) { uint8_t c; if (k_uptime_get() > timeout_time) { return -ETIME; } if (uart_poll_in(dev, &c) == 0) { if (c == data[matched_size]) { matched_size++; if (matched_size == len) { break; } } else if (c == data[0]) { matched_size = 1; } else { matched_size = 0; } } } return 0; } /** * @brief read bytes from uart * * @param data the data buffer * @param len the data len * @param timeout the timeout in milliseconds * @return 0 if success; -ETIME if timeout */ static int uart_read_bytes(const struct device *dev, uint8_t *data, int len, int timeout) { int read_size = 0; int64_t timeout_time = k_uptime_get() + K_MSEC(timeout); while (1) { uint8_t c; if (k_uptime_get() > timeout_time) { return -ETIME; } if (uart_poll_in(dev, &c) == 0) { data[read_size++] = c; if (read_size == len) { break; } } } return 0; } static int pms7003_sample_fetch(const struct device *dev, enum sensor_channel chan) { struct pms7003_data *drv_data = dev->data; /* sample output */ /* 42 4D 00 1C 00 01 00 01 00 01 00 01 00 01 00 01 01 92 * 00 4E 00 03 00 00 00 00 00 00 71 00 02 06 */ uint8_t pms7003_start_bytes[] = {0x42, 0x4d}; uint8_t pms7003_receive_buffer[30]; if (uart_wait_for(drv_data->uart_dev, pms7003_start_bytes, sizeof(pms7003_start_bytes), CFG_PMS7003_SERIAL_TIMEOUT) < 0) { LOG_WRN("waiting for start bytes is timeout"); return -ETIME; } if (uart_read_bytes(drv_data->uart_dev, pms7003_receive_buffer, 30, CFG_PMS7003_SERIAL_TIMEOUT) < 0) { return -ETIME; } drv_data->pm_1_0 = (pms7003_receive_buffer[8] << 8) + pms7003_receive_buffer[9]; drv_data->pm_2_5 = (pms7003_receive_buffer[10] << 8) + pms7003_receive_buffer[11]; drv_data->pm_10 = (pms7003_receive_buffer[12] << 8) + pms7003_receive_buffer[13]; LOG_DBG("pm1.0 = %d", drv_data->pm_1_0); LOG_DBG("pm2.5 = %d", drv_data->pm_2_5); LOG_DBG("pm10 = %d", drv_data->pm_10); return 0; } static int pms7003_channel_get(const struct device *dev, enum sensor_channel chan, struct sensor_value *val) { struct pms7003_data *drv_data = dev->data; if (chan == SENSOR_CHAN_PM_1_0) { val->val1 = drv_data->pm_1_0; val->val2 = 0; } else if (chan == SENSOR_CHAN_PM_2_5) { val->val1 = drv_data->pm_2_5; val->val2 = 0; } else if (chan == SENSOR_CHAN_PM_10) { val->val1 = drv_data->pm_10; val->val2 = 0; } else { return -EINVAL; } return 0; } static const struct sensor_driver_api pms7003_api = { .sample_fetch = &pms7003_sample_fetch, .channel_get = &pms7003_channel_get, }; static int pms7003_init(const struct device *dev) { struct pms7003_data *drv_data = dev->data; drv_data->uart_dev = device_get_binding(DT_INST_BUS_LABEL(0)); if (!drv_data->uart_dev) { LOG_DBG("uart device is not found: %s", DT_INST_BUS_LABEL(0)); return -EINVAL; } return 0; } static struct pms7003_data pms7003_data; DEVICE_DT_INST_DEFINE(0, &pms7003_init, device_pm_control_nop, &pms7003_data, NULL, POST_KERNEL, CONFIG_SENSOR_INIT_PRIORITY, &pms7003_api);
Vudentz/zephyr
drivers/sensor/pms7003/pms7003.c
C
apache-2.0
4,354
/* socket.c Created: Feb 2001 by Philip Homburg <philip@f-mnx.phicoh.com> Open a TCP connection */ #define _POSIX_C_SOURCE 2 #include <errno.h> #include <fcntl.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <signal.h> #include <string.h> #include <unistd.h> #include <sys/ioctl.h> #include <sys/wait.h> #include <net/hton.h> #include <net/netlib.h> #include <net/gen/in.h> #include <net/gen/inet.h> #include <netdb.h> #include <net/gen/socket.h> #include <net/gen/tcp.h> #include <net/gen/tcp_io.h> #define BUF_SIZE 10240 char *progname; int tcpfd= -1; char buf[BUF_SIZE]; static int bulk= 0; static int push= 0; static int stdout_issocket= 0; static int timeout; static void do_conn(char *hostname, char *portname); static void alrm_conn(int sig); static void alrm_io(int sig); static void fullduplex(void); static void fatal(char *msg, ...); static void usage(void); int main(int argc, char *argv[]) { int c; char *hostname; char *portname; char *check; int B_flag, P_flag, s_flag; char *t_arg; (progname=strrchr(argv[0],'/')) ? progname++ : (progname=argv[0]); B_flag= 0; P_flag= 0; s_flag= 0; t_arg= NULL; while (c= getopt(argc, argv, "BPst:?"), c != -1) { switch(c) { case 'B': B_flag= 1; break; case 'P': P_flag= 1; break; case 's': s_flag= 1; break; case 't': t_arg= optarg; break; case '?': usage(); default: fatal("getopt failed: '%c'", c); } } if (t_arg) { timeout= strtol(t_arg, &check, 0); if (check[0] != '\0') fatal("unable to parse timeout '%s'\n", t_arg); if (timeout <= 0) fatal("bad timeout '%d'\n", timeout); } else timeout= 0; if (optind+2 != argc) usage(); hostname= argv[optind++]; portname= argv[optind++]; bulk= B_flag; push= P_flag; stdout_issocket= s_flag; do_conn(hostname, portname); /* XXX */ if (timeout) { signal(SIGALRM, alrm_io); alarm(timeout); } fullduplex(); exit(0); } static void do_conn(char *hostname, char *portname) { ipaddr_t addr; tcpport_t port; struct hostent *he; struct servent *se; char *tcp_device, *check; nwio_tcpconf_t tcpconf; nwio_tcpcl_t tcpcl; nwio_tcpopt_t tcpopt; if (!inet_aton(hostname, &addr)) { he= gethostbyname(hostname); if (he == NULL) fatal("unknown hostname '%s'", hostname); if (he->h_addrtype != AF_INET || he->h_length != sizeof(addr)) fatal("bad address for '%s'", hostname); memcpy(&addr, he->h_addr, sizeof(addr)); } port= strtol(portname, &check, 0); if (check[0] != 0) { se= getservbyname(portname, "tcp"); if (se == NULL) fatal("unkown port '%s'", portname); port= ntohs(se->s_port); } tcp_device= getenv("TCP_DEVICE"); if (tcp_device == NULL) tcp_device= TCP_DEVICE; tcpfd= open(tcp_device, O_RDWR); if (tcpfd == -1) fatal("unable to open '%s': %s", tcp_device, strerror(errno)); tcpconf.nwtc_flags= NWTC_EXCL | NWTC_LP_SEL | NWTC_SET_RA | NWTC_SET_RP; tcpconf.nwtc_remaddr= addr; tcpconf.nwtc_remport= htons(port);; if (ioctl(tcpfd, NWIOSTCPCONF, &tcpconf) == -1) fatal("NWIOSTCPCONF failed: %s", strerror(errno)); if (timeout) { signal(SIGALRM, alrm_conn); alarm(timeout); } tcpcl.nwtcl_flags= 0; if (ioctl(tcpfd, NWIOTCPCONN, &tcpcl) == -1) { fatal("unable to connect to %s:%u: %s", inet_ntoa(addr), ntohs(tcpconf.nwtc_remport), strerror(errno)); } alarm(0); if (bulk) { tcpopt.nwto_flags= NWTO_BULK; if (ioctl(tcpfd, NWIOSTCPOPT, &tcpopt) == -1) fatal("NWIOSTCPOPT failed: %s", strerror(errno)); } } static void alrm_conn(int sig) { fatal("timeout during connect"); } static void alrm_io(int sig) { fatal("timeout during io"); } static void fullduplex(void) { pid_t cpid; int o, r, s, s_errno, loc; cpid= fork(); switch(cpid) { case -1: fatal("fork failed: %s", strerror(errno)); case 0: /* Read from TCP, write to stdout. */ for (;;) { r= read(tcpfd, buf, BUF_SIZE); if (r == 0) break; if (r == -1) { r= errno; if (stdout_issocket) ioctl(1, NWIOTCPSHUTDOWN, NULL); fatal("error reading from TCP conn.: %s", strerror(errno)); } s= r; for (o= 0; o<s; o += r) { r= write(1, buf+o, s-o); if (r <= 0) { fatal("error writing to stdout: %s", r == 0 ? "EOF" : strerror(errno)); } } } if (stdout_issocket) { r= ioctl(1, NWIOTCPSHUTDOWN, NULL); if (r == -1) { fatal("NWIOTCPSHUTDOWN failed on stdout: %s", strerror(errno)); } } exit(0); default: break; } /* Read from stdin, write to TCP. */ for (;;) { r= read(0, buf, BUF_SIZE); if (r == 0) break; if (r == -1) { s_errno= errno; kill(cpid, SIGTERM); fatal("error reading from stdin: %s", strerror(s_errno)); } s= r; for (o= 0; o<s; o += r) { r= write(tcpfd, buf+o, s-o); if (r <= 0) { s_errno= errno; kill(cpid, SIGTERM); fatal("error writing to TCP conn.: %s", r == 0 ? "EOF" : strerror(s_errno)); } } if (push) ioctl(tcpfd, NWIOTCPPUSH, NULL); } if (ioctl(tcpfd, NWIOTCPSHUTDOWN, NULL) == -1) { s_errno= errno; kill(cpid, SIGTERM); fatal("unable to shut down TCP conn.: %s", strerror(s_errno)); } r= waitpid(cpid, &loc, 0); if (r == -1) { s_errno= errno; kill(cpid, SIGTERM); fatal("waitpid failed: %s", strerror(s_errno)); } if (WIFEXITED(loc)) exit(WEXITSTATUS(loc)); kill(getpid(), WTERMSIG(loc)); exit(1); } static void fatal(char *fmt, ...) { va_list ap; va_start(ap, fmt); fprintf(stderr, "%s: ", progname); vfprintf(stderr, fmt, ap); fprintf(stderr, "\n"); va_end(ap); exit(1); } static void usage(void) { fprintf(stderr, "Usage: %s [-BPs] [-t timeout] hostname portname\n", progname); exit(1); } /* * $PchId: socket.c,v 1.3 2005/01/31 22:33:20 philip Exp $ */
veritas-shine/minix3-rpi
minix/commands/swifi/socket.c
C
apache-2.0
5,758
/* * Copyright (c) 2018 Makaio GmbH * * SPDX-License-Identifier: Apache-2.0 */ #include <shell/shell_rtt.h> #include <init.h> #include <SEGGER_RTT.h> #include <logging/log.h> BUILD_ASSERT_MSG(!(IS_ENABLED(CONFIG_LOG_BACKEND_RTT) && COND_CODE_0(CONFIG_LOG_BACKEND_RTT_BUFFER, (1), (0))), "Conflicting log RTT backend enabled on the same channel"); SHELL_RTT_DEFINE(shell_transport_rtt); SHELL_DEFINE(shell_rtt, CONFIG_SHELL_PROMPT_RTT, &shell_transport_rtt, CONFIG_SHELL_BACKEND_RTT_LOG_MESSAGE_QUEUE_SIZE, CONFIG_SHELL_BACKEND_RTT_LOG_MESSAGE_QUEUE_TIMEOUT, SHELL_FLAG_OLF_CRLF); LOG_MODULE_REGISTER(shell_rtt, CONFIG_SHELL_RTT_LOG_LEVEL); static bool rtt_blocking; static void timer_handler(struct k_timer *timer) { const struct shell_rtt *sh_rtt = k_timer_user_data_get(timer); if (SEGGER_RTT_HasData(0)) { sh_rtt->handler(SHELL_TRANSPORT_EVT_RX_RDY, sh_rtt->context); } } static int init(const struct shell_transport *transport, const void *config, shell_transport_handler_t evt_handler, void *context) { struct shell_rtt *sh_rtt = (struct shell_rtt *)transport->ctx; sh_rtt->handler = evt_handler; sh_rtt->context = context; k_timer_init(&sh_rtt->timer, timer_handler, NULL); k_timer_user_data_set(&sh_rtt->timer, (void *)sh_rtt); k_timer_start(&sh_rtt->timer, CONFIG_SHELL_RTT_RX_POLL_PERIOD, CONFIG_SHELL_RTT_RX_POLL_PERIOD); return 0; } static int uninit(const struct shell_transport *transport) { return 0; } static int enable(const struct shell_transport *transport, bool blocking) { struct shell_rtt *sh_rtt = (struct shell_rtt *)transport->ctx; if (blocking) { rtt_blocking = true; k_timer_stop(&sh_rtt->timer); } return 0; } static int write(const struct shell_transport *transport, const void *data, size_t length, size_t *cnt) { struct shell_rtt *sh_rtt = (struct shell_rtt *)transport->ctx; const u8_t *data8 = (const u8_t *)data; if (rtt_blocking) { *cnt = SEGGER_RTT_WriteNoLock(0, data8, length); while (SEGGER_RTT_HasDataUp(0)) { /* empty */ } } else { *cnt = SEGGER_RTT_Write(0, data8, length); } sh_rtt->handler(SHELL_TRANSPORT_EVT_TX_RDY, sh_rtt->context); return 0; } static int read(const struct shell_transport *transport, void *data, size_t length, size_t *cnt) { *cnt = SEGGER_RTT_Read(0, data, length); return 0; } const struct shell_transport_api shell_rtt_transport_api = { .init = init, .uninit = uninit, .enable = enable, .write = write, .read = read }; static int enable_shell_rtt(struct device *arg) { ARG_UNUSED(arg); bool log_backend = CONFIG_SHELL_RTT_INIT_LOG_LEVEL > 0; u32_t level = (CONFIG_SHELL_RTT_INIT_LOG_LEVEL > LOG_LEVEL_DBG) ? CONFIG_LOG_MAX_LEVEL : CONFIG_SHELL_RTT_INIT_LOG_LEVEL; shell_init(&shell_rtt, NULL, true, log_backend, level); return 0; } /* Function is used for testing purposes */ const struct shell *shell_backend_rtt_get_ptr(void) { return &shell_rtt; } SYS_INIT(enable_shell_rtt, POST_KERNEL, 0);
ldts/zephyr
subsys/shell/shell_rtt.c
C
apache-2.0
2,990
#include "private.h" #include <Elementary.h> #include "config.h" #include "termio.h" #include "media.h" #include "options.h" #include "options_wallpaper.h" #include "extns.h" #include "media.h" #include "main.h" #include <sys/stat.h> typedef struct _Background_Item { const char *path; Eina_Bool selected; Elm_Object_Item *item; } Background_Item; typedef struct _Insert_Gen_Grid_Item_Notify { Elm_Gengrid_Item_Class *class; Background_Item *item; } Insert_Gen_Grid_Item_Notify; static Eina_Stringshare *_system_path, *_user_path; static Evas_Object *_bg_grid = NULL, *_term = NULL, *_entry = NULL, *_flip = NULL, *_bubble = NULL; static Eina_List *_backgroundlist = NULL; static Ecore_Timer *_bubble_disappear; static Ecore_Thread *_thread; static void _cb_fileselector(void *data EINA_UNUSED, Evas_Object *obj, void* event) { if (event) { elm_object_text_set(_entry, elm_fileselector_path_get(obj)); elm_flip_go_to(_flip, EINA_TRUE, ELM_FLIP_PAGE_LEFT); } else { elm_flip_go_to(_flip, EINA_TRUE, ELM_FLIP_PAGE_LEFT); } } static Eina_Bool _cb_timer_bubble_disappear(void *data EINA_UNUSED) { evas_object_del(_bubble); _bubble_disappear = NULL; return ECORE_CALLBACK_CANCEL; } static void _bubble_show(char *text) { Evas_Object *opbox = elm_object_top_widget_get(_bg_grid); Evas_Object *o; int x = 0, y = 0, w , h; evas_object_geometry_get(_bg_grid, &x, &y, &w ,&h); if (_bubble_disappear) { ecore_timer_del(_bubble_disappear); _cb_timer_bubble_disappear(NULL); } _bubble = elm_bubble_add(opbox); elm_bubble_pos_set(_bubble, ELM_BUBBLE_POS_BOTTOM_RIGHT); evas_object_resize(_bubble, 200, 50); evas_object_move(_bubble, (x + w - 200), (y + h - 50)); evas_object_show(_bubble); o = elm_label_add(_bubble); elm_object_text_set(o, text); elm_object_content_set(_bubble, o); _bubble_disappear = ecore_timer_add(2.0, _cb_timer_bubble_disappear, NULL); } static char * _grid_text_get(void *data, Evas_Object *obj EINA_UNUSED, const char *part EINA_UNUSED) { Background_Item *item = data; const char *s; if (!item->path) return strdup(_("None")); s = ecore_file_file_get(item->path); if (s) return strdup(s); return NULL; } static Evas_Object * _grid_content_get(void *data, Evas_Object *obj, const char *part) { Background_Item *item = data; Evas_Object *o, *oe; Config *config = termio_config_get(_term); char path[PATH_MAX]; if (!strcmp(part, "elm.swallow.icon")) { if (item->path) { int i; Media_Type type; for (i = 0; extn_edj[i]; i++) { if (eina_str_has_extension(item->path, extn_edj[i])) return media_add(obj, item->path, config, MEDIA_BG, MEDIA_TYPE_EDJE); } type = media_src_type_get(item->path); return media_add(obj, item->path, config, MEDIA_THUMB, type); } else { if (!config->theme) return NULL; snprintf(path, PATH_MAX, "%s/themes/%s", elm_app_data_dir_get(), config->theme); o = elm_layout_add(obj); oe = elm_layout_edje_get(o); if (!edje_object_file_set(oe, path, "terminology/background")) { evas_object_del(o); return NULL; } evas_object_show(o); return o; } } return NULL; } static void _item_selected(void *data, Evas_Object *obj EINA_UNUSED, void *event EINA_UNUSED) { Background_Item *item = data; Config *config = termio_config_get(_term); if (!config) return; if (!item->path) { // no background eina_stringshare_del(config->background); config->background = NULL; config_save(config, NULL); main_media_update(config); } else if (eina_stringshare_replace(&(config->background), item->path)) { config_save(config, NULL); main_media_update(config); } } static void _insert_gengrid_item(Insert_Gen_Grid_Item_Notify *msg_data) { Insert_Gen_Grid_Item_Notify *insert_msg = msg_data; Config *config = termio_config_get(_term); if (insert_msg && insert_msg->item && insert_msg->class && config) { Background_Item *item = insert_msg->item; Elm_Gengrid_Item_Class *item_class = insert_msg->class; item->item = elm_gengrid_item_append(_bg_grid, item_class, item, _item_selected, item); if ((!item->path) && (!config->background)) { elm_gengrid_item_selected_set(item->item, EINA_TRUE); elm_gengrid_item_bring_in(item->item, ELM_GENGRID_ITEM_SCROLLTO_MIDDLE); } else if ((item->path) && (config->background)) { if (strcmp(item->path, config->background) == 0) { elm_gengrid_item_selected_set(item->item, EINA_TRUE); elm_gengrid_item_bring_in(item->item, ELM_GENGRID_ITEM_SCROLLTO_MIDDLE); } } } free(msg_data); } static Eina_List* _rec_read_directorys(Eina_List *list, const char *root_path, Elm_Gengrid_Item_Class *class) { Eina_List *childs = ecore_file_ls(root_path); char *file_name, path[PATH_MAX]; int i, j; Background_Item *item; const char **extns[5] = { extn_img, extn_scale, extn_edj, extn_mov, NULL }; const char **ex; Insert_Gen_Grid_Item_Notify *notify; if (!childs) return list; EINA_LIST_FREE(childs, file_name) { snprintf(path, PATH_MAX, "%s/%s", root_path, file_name); if ((!ecore_file_is_dir(path)) && (file_name[0] != '.')) { //file is found, search for correct file endings ! for (j = 0; extns[j]; j++) { ex = extns[j]; for (i = 0; ex[i]; i++) { if (eina_str_has_extension(file_name, ex[i])) { //File is found and valid item = calloc(1, sizeof(Background_Item)); if (item) { notify = calloc(1, sizeof(Insert_Gen_Grid_Item_Notify)); item->path = eina_stringshare_add(path); list = eina_list_append(list, item); //insert item to gengrid notify->class = class; notify->item = item; //ecore_thread_feedback(th, notify); _insert_gengrid_item(notify); } break; } } } } free(file_name); } return list; } static void _refresh_directory(const char* data) { Background_Item *item; Elm_Gengrid_Item_Class *item_class; // This will run elm_gengrid_clear elm_gengrid_clear(_bg_grid); if (_backgroundlist) { EINA_LIST_FREE(_backgroundlist, item) { if (item->path) eina_stringshare_del(item->path); free(item); } _backgroundlist = NULL; } item_class = elm_gengrid_item_class_new(); item_class->func.text_get = _grid_text_get; item_class->func.content_get = _grid_content_get; item = calloc(1, sizeof(Background_Item)); _backgroundlist = eina_list_append(_backgroundlist, item); //Insert None Item Insert_Gen_Grid_Item_Notify *notify = calloc(1, sizeof(Insert_Gen_Grid_Item_Notify)); notify->class = item_class; notify->item = item; _insert_gengrid_item(notify); _backgroundlist = _rec_read_directorys(_backgroundlist, data, item_class); elm_gengrid_item_class_free(item_class); _thread = NULL; } static void _gengrid_refresh_samples(const char *path) { if(!ecore_file_exists(path)) return; _refresh_directory(path); } static void _cb_entry_changed(void *data EINA_UNUSED, Evas_Object *parent, void *event EINA_UNUSED) { const char *path = elm_object_text_get(parent); _gengrid_refresh_samples(path); } static void _cb_hoversel_select(void *data, Evas_Object *hoversel EINA_UNUSED, void *event EINA_UNUSED) { Evas_Object *o; char *path = data; if (path) { elm_object_text_set(_entry, path); } else { o = elm_object_part_content_get(_flip, "back"); elm_fileselector_path_set(o, elm_object_text_get(_entry)); elm_flip_go_to(_flip, EINA_FALSE, ELM_FLIP_PAGE_RIGHT); } } static void _system_background_dir_init(void) { char path[PATH_MAX]; snprintf(path, PATH_MAX, "%s/backgrounds/", elm_app_data_dir_get()); if (_system_path) eina_stringshare_replace(&_system_path, path); else _system_path = eina_stringshare_add(path); } static const char* _user_background_dir_init(void){ char path[PATH_MAX], *user; user = getenv("HOME"); if(!user) return NULL; snprintf(path, PATH_MAX, "%s/.config/terminology/background/", user); if (!ecore_file_exists(path)) ecore_file_mkpath(path); if (!_user_path) _user_path = eina_stringshare_add(path); else eina_stringshare_replace(&_user_path, path); return _user_path; } static const char* _import_background(const char* background) { char path[PATH_MAX]; const char *filename = ecore_file_file_get(background); if (!filename) return NULL; if (!_user_background_dir_init()) return NULL; snprintf(path, PATH_MAX, "%s/%s", _user_path, filename); if (!ecore_file_cp(background, path)) return NULL; return eina_stringshare_add(path); } static void _cb_grid_doubleclick(void *data EINA_UNUSED, Evas_Object *obj EINA_UNUSED, void *event EINA_UNUSED) { Config *config = termio_config_get(_term); char *config_background_dir = ecore_file_dir_get(config->background); if (!_user_path) { if (!_user_background_dir_init()) return; } if (!config->background) return; if (strncmp(config_background_dir, _user_path, strlen(config_background_dir)) == 0) { _bubble_show(_("Source file is target file")); free(config_background_dir); return; } const char *newfile = _import_background(config->background); if (newfile) { eina_stringshare_replace(&(config->background), newfile); config_save(config, NULL); main_media_update(config); eina_stringshare_del(newfile); _bubble_show(_("Picture imported")); elm_object_text_set(_entry, config_background_dir); } else { _bubble_show(_("Failed")); } free(config_background_dir); } void options_wallpaper(Evas_Object *opbox, Evas_Object *term) { Evas_Object *frame, *o, *bx, *bx2; Config *config = termio_config_get(term); char path[PATH_MAX], *config_background_dir; _term = term; frame = o = elm_frame_add(opbox); evas_object_size_hint_weight_set(o, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND); evas_object_size_hint_align_set(o, EVAS_HINT_FILL, EVAS_HINT_FILL); elm_object_text_set(o, _("Background")); evas_object_show(o); elm_box_pack_end(opbox, o); _flip = o = elm_flip_add(opbox); evas_object_size_hint_weight_set(o, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND); evas_object_size_hint_align_set(o, EVAS_HINT_FILL, EVAS_HINT_FILL); elm_object_content_set(frame, o); evas_object_show(o); o = elm_fileselector_add(opbox); evas_object_size_hint_weight_set(o, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND); evas_object_size_hint_align_set(o, EVAS_HINT_FILL, EVAS_HINT_FILL); elm_object_part_content_set(_flip, "back", o); elm_fileselector_folder_only_set(o, EINA_TRUE); evas_object_smart_callback_add(o, "done", _cb_fileselector, NULL); evas_object_show(o); bx = o = elm_box_add(opbox); evas_object_size_hint_weight_set(o, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND); evas_object_size_hint_align_set(o, EVAS_HINT_FILL, EVAS_HINT_FILL); elm_object_part_content_set(_flip, "front", bx); evas_object_show(o); bx2 = o = elm_box_add(opbox); evas_object_size_hint_weight_set(o, EVAS_HINT_EXPAND, 0.0); evas_object_size_hint_align_set(o, EVAS_HINT_FILL, 0.0); elm_box_horizontal_set(o, EINA_TRUE); elm_box_pack_start(bx, o); evas_object_show(o); _entry = o = elm_entry_add(opbox); evas_object_size_hint_weight_set(o, EVAS_HINT_EXPAND, 0.0); evas_object_size_hint_align_set(o, EVAS_HINT_FILL, 0.0); elm_entry_single_line_set(o, EINA_TRUE); elm_entry_scrollable_set(o, EINA_TRUE); elm_scroller_policy_set(o, ELM_SCROLLER_POLICY_OFF, ELM_SCROLLER_POLICY_OFF); evas_object_smart_callback_add(_entry, "changed", _cb_entry_changed, NULL); elm_box_pack_start(bx2, o); evas_object_show(o); o = elm_hoversel_add(opbox); evas_object_size_hint_weight_set(o, 0.0, 0.0); evas_object_size_hint_align_set(o, EVAS_HINT_FILL, 0.0); elm_object_text_set(o, _("Select Path")); elm_box_pack_end(bx2, o); evas_object_show(o); snprintf(path, PATH_MAX, "%s/backgrounds/", elm_app_data_dir_get()); _system_background_dir_init(); elm_hoversel_item_add(o, _("System"), NULL, ELM_ICON_NONE, _cb_hoversel_select , _system_path); if (_user_background_dir_init()) elm_hoversel_item_add(o, _("User"), NULL, ELM_ICON_NONE, _cb_hoversel_select , _user_path); //In the other case it has failed, so dont show the user item elm_hoversel_item_add(o, _("Other"), NULL, ELM_ICON_NONE, _cb_hoversel_select , NULL); _bg_grid = o = elm_gengrid_add(opbox); evas_object_size_hint_weight_set(o, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND); evas_object_size_hint_align_set(o, EVAS_HINT_FILL, EVAS_HINT_FILL); evas_object_smart_callback_add(o, "clicked,double", _cb_grid_doubleclick, NULL); elm_gengrid_item_size_set(o, elm_config_scale_get() * 100, elm_config_scale_get() * 80); elm_box_pack_end(bx, o); evas_object_show(o); o = elm_label_add(opbox); evas_object_size_hint_weight_set(o, EVAS_HINT_EXPAND, 0.0); evas_object_size_hint_align_set(o, EVAS_HINT_FILL, 0.0); elm_object_text_set(o, _("Double click on a picture to import it")); elm_box_pack_end(bx, o); evas_object_show(o); if (config->background) { config_background_dir = ecore_file_dir_get(config->background); elm_object_text_set(_entry, config_background_dir); free(config_background_dir); } else { elm_object_text_set(_entry, _system_path); } } void options_wallpaper_clear(void) { Background_Item *item; EINA_LIST_FREE(_backgroundlist, item) { if (item->path) eina_stringshare_del(item->path); free(item); } _backgroundlist = NULL; if (_user_path) { eina_stringshare_del(_user_path); _user_path = NULL; } if (_system_path) { eina_stringshare_del(_system_path); _system_path = NULL; } }
ihorlaitan/terminology
src/bin/options_wallpaper.c
C
bsd-2-clause
15,837
/**************************************************************************** * arch/arm/src/nuc1xx/nuc_lowputc.c * * Copyright (C) 2013 Gregory Nutt. All rights reserved. * Author: Gregory Nutt <gnutt@nuttx.org> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name NuttX nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /**************************************************************************** * Included Files ****************************************************************************/ #include <nuttx/config.h> #include <stdint.h> #include <assert.h> #include <debug.h> #include <arch/board/board.h> #include "up_arch.h" #include "chip.h" #include "nuc_config.h" #include "chip/chip/nuc_clk.h" #include "chip/chip/nuc_uart.h" #include "chip/nuc_gcr.h" #include "nuc_lowputc.h" /**************************************************************************** * Pre-processor Definitions ****************************************************************************/ /* Get the serial console UART configuration */ #ifdef HAVE_SERIAL_CONSOLE # if defined(CONFIG_UART0_SERIAL_CONSOLE) # define NUC_CONSOLE_BASE NUC_UART0_BASE # define NUC_CONSOLE_DEPTH UART0_FIFO_DEPTH # define NUC_CONSOLE_BAUD CONFIG_UART0_BAUD # define NUC_CONSOLE_BITS CONFIG_UART0_BITS # define NUC_CONSOLE_PARITY CONFIG_UART0_PARITY # define NUC_CONSOLE_2STOP CONFIG_UART0_2STOP # elif defined(CONFIG_UART1_SERIAL_CONSOLE) # define NUC_CONSOLE_BASE NUC_UART1_BASE # define NUC_CONSOLE_DEPTH UART1_FIFO_DEPTH # define NUC_CONSOLE_BAUD CONFIG_UART1_BAUD # define NUC_CONSOLE_BITS CONFIG_UART1_BITS # define NUC_CONSOLE_PARITY CONFIG_UART1_PARITY # define NUC_CONSOLE_2STOP CONFIG_UART1_2STOP # elif defined(CONFIG_UART2_SERIAL_CONSOLE) # define NUC_CONSOLE_BASE NUC_UART2_BASE # define NUC_CONSOLE_DEPTH UART2_FIFO_DEPTH # define NUC_CONSOLE_BAUD CONFIG_UART2_BAUD # define NUC_CONSOLE_BITS CONFIG_UART2_BITS # define NUC_CONSOLE_PARITY CONFIG_UART2_PARITY # define NUC_CONSOLE_2STOP CONFIG_UART2_2STOP # endif #endif /* Select either the external high speed crystal, the PLL output, or * the internal high speed clock as the UART clock source. */ #if defined(CONFIG_NUC_UARTCLK_XTALHI) # define NUC_UART_CLK BOARD_XTALHI_FREQUENCY #elif defined(CONFIG_NUC_UARTCLK_PLL) # define NUC_UART_CLK BOARD_PLL_FOUT #elif defined(CONFIG_NUC_UARTCLK_INTHI) # define NUC_UART_CLK NUC_INTHI_FREQUENCY #endif /**************************************************************************** * Private Functions ****************************************************************************/ /**************************************************************************** * Name: nuc_console_ready * * Description: * Wait until the console is ready to add another character to the TX * FIFO. * *****************************************************************************/ #ifdef HAVE_SERIAL_CONSOLE static inline void nuc_console_ready(void) { #if 1 /* Wait for the TX FIFO to be empty (excessive!) */ while ((getreg32(NUC_CONSOLE_BASE + NUC_UART_FSR_OFFSET) & UART_FSR_TX_EMPTY) == 0); #else uint32_t depth; /* Wait until there is space in the TX FIFO */ do { register uint32_t regval = getreg32(NUC_CONSOLE_BASE + NUC_UART_FSR_OFFSET); depth = (regval & UART_FSR_TX_POINTER_MASK) >> UART_FSR_TX_POINTER_SHIFT; } while (depth >= (NUC_CONSOLE_DEPTH-1)); #endif } #endif /* HAVE_SERIAL_CONSOLE */ /**************************************************************************** * Public Functions ****************************************************************************/ /**************************************************************************** * Name: nuc_lowsetup * * Description: * Called at the very beginning of _start. Performs low level initialization. * *****************************************************************************/ void nuc_lowsetup(void) { #ifdef HAVE_UART uint32_t regval; /* Configure UART GPIO pins. * * Basic UART0 TX/RX requires that GPIOB MFP bits 0 and 1 be set. If flow * control is enabled, then GPIOB MFP bits 3 and 4 must also be set and ALT * MFP bits 11, 13, and 14 must be cleared. */ #if defined(CONFIG_NUC_UART0) || defined(CONFIG_NUC_UART1) regval = getreg32(NUC_GCR_GPB_MFP); #ifdef CONFIG_NUC_UART0 #ifdef CONFIG_UART0_FLOW_CONTROL regval |= (GCR_GPB_MFP0 | GCR_GPB_MFP1 | GCR_GPB_MFP2| GCR_GPB_MFP3); #else regval |= (GCR_GPB_MFP0 | GCR_GPB_MFP1); #endif #endif /* CONFIG_NUC_UART0 */ /* Basic UART1 TX/RX requires that GPIOB MFP bits 4 and 5 be set. If flow * control is enabled, then GPIOB MFP bits 6 and 7 must also be set and ALT * MFP bit 11 must be cleared. */ #ifdef CONFIG_NUC_UART1 #ifdef CONFIG_UART1_FLOW_CONTROL regval |= (GCR_GPB_MFP4 | GCR_GPB_MFP5 | GCR_GPB_MFP6| GCR_GPB_MFP7) #else regval |= (GCR_GPB_MFP4 | GCR_GPB_MFP5); #endif #endif /* CONFIG_NUC_UART1 */ putreg32(regval, NUC_GCR_GPB_MFP); #if defined(CONFIG_UART0_FLOW_CONTROL) || defined(CONFIG_UART1_FLOW_CONTROL) regval = getreg32(NUC_GCR_ALT_MFP); regval &= ~GCR_ALT_MFP_EBI_EN; #ifdef CONFIG_UART0_FLOW_CONTROL regval &= ~(GCR_ALT_MFP_EBI_NWRL_EN | GCR_ALT_MFP_EBI_NWRH_WN); #endif putreg32(NUC_GCR_ALT_MFP); #endif /* CONFIG_UART0_FLOW_CONTROL || CONFIG_UART1_FLOW_CONTROL */ #endif /* CONFIG_NUC_UART0 || CONFIG_NUC_UART1 */ /* UART1 TX/RX support requires that GPIOD bits 14 and 15 be set. UART2 * does not support flow control. */ #ifdef CONFIG_NUC_UART2 regval = getreg32(NUC_GCR_GPD_MFP); regval |= (GCR_GPD_MFP14 | GCR_GPD_MFP15); putreg32(regval, NUC_GCR_GPD_MFP); #endif /* CONFIG_NUC_UART2 */ /* Reset the UART peripheral(s) */ regval = getreg32(NUC_GCR_IPRSTC2); #ifdef CONFIG_NUC_UART0 regval |= GCR_IPRSTC2_UART0_RST; putreg32(regval, NUC_GCR_IPRSTC2); regval &= ~GCR_IPRSTC2_UART0_RST; putreg32(regval, NUC_GCR_IPRSTC2); #endif #ifdef CONFIG_NUC_UART1 regval |= GCR_IPRSTC2_UART1_RST; putreg32(regval, NUC_GCR_IPRSTC2); regval &= ~GCR_IPRSTC2_UART1_RST; putreg32(regval, NUC_GCR_IPRSTC2); #endif #ifdef CONFIG_NUC_UART2 regval |= GCR_IPRSTC2_UART2_RST; putreg32(regval, NUC_GCR_IPRSTC2); regval &= ~GCR_IPRSTC2_UART2_RST; putreg32(regval, NUC_GCR_IPRSTC2); #endif /* Configure the UART clock source. Set the UART clock source to either * the external high speed crystal (CLKSEL1 reset value), the PLL output, * or the internal high speed clock. */ regval = getreg32(NUC_CLK_CLKSEL1); regval &= ~CLK_CLKSEL1_UART_S_MASK; #if defined(CONFIG_NUC_UARTCLK_XTALHI) regval |= CLK_CLKSEL1_UART_S_XTALHI; #elif defined(CONFIG_NUC_UARTCLK_PLL) regval |= CLK_CLKSEL1_UART_S_PLL; #elif defined(CONFIG_NUC_UARTCLK_INTHI) regval |= CLK_CLKSEL1_UART_S_INTHI; #endif putreg32(regval, NUC_CLK_CLKSEL1); /* Enable UART clocking for the selected UARTs */ regval = getreg32(NUC_CLK_APBCLK); regval &= ~(CLK_APBCLK_UART0_EN | CLK_APBCLK_UART1_EN | CLK_APBCLK_UART2_EN); #ifdef CONFIG_NUC_UART0 regval |= CLK_APBCLK_UART0_EN; #endif #ifdef CONFIG_NUC_UART1 regval |= CLK_APBCLK_UART1_EN; #endif #ifdef CONFIG_NUC_UART2 regval |= CLK_APBCLK_UART2_EN; #endif putreg32(regval, NUC_CLK_APBCLK); /* Configure the console UART */ #ifdef HAVE_SERIAL_CONSOLE /* Reset the TX FIFO */ regval = getreg32(NUC_CONSOLE_BASE + NUC_UART_FCR_OFFSET); regval &= ~(UART_FCR_TFR | UART_FCR_RFR); putreg32(regval | UART_FCR_TFR, NUC_CONSOLE_BASE + NUC_UART_FCR_OFFSET); /* Reset the RX FIFO */ putreg32(regval | UART_FCR_RFR, NUC_CONSOLE_BASE + NUC_UART_FCR_OFFSET); /* Set Rx Trigger Level */ regval &= ~UART_FCR_RFITL_MASK; regval |= UART_FCR_RFITL_4; putreg32(regval, NUC_CONSOLE_BASE + NUC_UART_FCR_OFFSET); /* Set Parity & Data bits and Stop bits */ regval = 0; #if NUC_CONSOLE_BITS == 5 regval |= UART_LCR_WLS_5; #elif NUC_CONSOLE_BITS == 6 regval |= UART_LCR_WLS_6; #elif NUC_CONSOLE_BITS == 7 regval |= UART_LCR_WLS_7; #elif NUC_CONSOLE_BITS == 8 regval |= UART_LCR_WLS_8; #else error "Unknown console UART data width" #endif #if NUC_CONSOLE_PARITY == 1 regval |= UART_LCR_PBE; #elif NUC_CONSOLE_PARITY == 2 regval |= (UART_LCR_PBE | UART_LCR_EPE); #endif #if NUC_CONSOLE_2STOP != 0 regval |= UART_LCR_NSB; #endif putreg32(regval, NUC_CONSOLE_BASE + NUC_UART_LCR_OFFSET); /* Set Time-Out values */ regval = UART_TOR_TOIC(40) | UART_TOR_DLY(0); putreg32(regval, NUC_CONSOLE_BASE + NUC_UART_TOR_OFFSET); /* Set the baud */ nuc_setbaud(NUC_CONSOLE_BASE, NUC_CONSOLE_BAUD); #endif /* HAVE_SERIAL_CONSOLE */ #endif /* HAVE_UART */ } /**************************************************************************** * Name: nuc_lowputc * * Description: * Output one character to the UART using a simple polling method. * *****************************************************************************/ void nuc_lowputc(uint32_t ch) { #ifdef HAVE_SERIAL_CONSOLE /* Wait for the TX FIFO to become available */ nuc_console_ready(); /* Then write the character to to the TX FIFO */ putreg32(ch, NUC_CONSOLE_BASE + NUC_UART_THR_OFFSET); #endif /* HAVE_SERIAL_CONSOLE */ } /**************************************************************************** * Name: nuc_setbaud * * Description: * Set the BAUD divxisor for the selected UART * * Mode DIV_X_EN DIV_X_ONE Divider X BRD (Baud rate equation) * ------------------------------------------------------------- * 0 0 0 B A UART_CLK / [16 * (A+2)] * 1 1 0 B A UART_CLK / [(B+1) * (A+2)] , B must >= 8 * 2 1 1 Don't care A UART_CLK / (A+2), A must >=3 * * Here we assume that the default clock source for the UART modules is * the external high speed crystal. * *****************************************************************************/ #ifdef HAVE_UART void nuc_setbaud(uintptr_t base, uint32_t baud) { uint32_t regval; uint32_t clksperbit; uint32_t brd; uint32_t divx; regval = getreg32(base + NUC_UART_BAUD_OFFSET); /* Mode 0: Source Clock mod 16 < 3 => Using Divider X = 16 */ clksperbit = (NUC_UART_CLK + (baud >> 1)) / baud; if ((clksperbit & 15) < 3) { regval &= ~(UART_BAUD_DIV_X_ONE | UART_BAUD_DIV_X_EN); brd = (clksperbit >> 4) - 2; } /* Source Clock mod 16 >3 => Up 5% Error BaudRate */ else { /* Mode 2: Try to Set Divider X = 1 */ regval |= (UART_BAUD_DIV_X_ONE | UART_BAUD_DIV_X_EN); brd = clksperbit - 2; /* Check if the divxider exceeds the range */ if (brd > 0xffff) { /* Mode 1: Try to Set Divider X up 10 */ regval &= ~UART_BAUD_DIV_X_ONE; for (divx = 8; divx < 16; divx++) { brd = clksperbit % (divx + 1); if (brd < 3) { regval &= ~UART_BAUD_DIVIDER_X_MASK; regval |= UART_BAUD_DIVIDER_X(divx); brd -= 2; break; } } } } regval &= ~UART_BAUD_BRD_MASK; regval |= UART_BAUD_BRD(brd); putreg32(regval, base + NUC_UART_BAUD_OFFSET); } #endif /* HAVE_UART */
IUTInfoAix/terrarium_2015
nuttx/arch/arm/src/nuc1xx/nuc_lowputc.c
C
bsd-2-clause
12,821
/* * Copyright (c) 2001 Alexander Kabaev * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer * in this position and unchanged. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * $FreeBSD: soc2013/dpl/head/lib/libkse/thread/thr_rtld.c 174155 2007-11-30 17:20:29Z deischen $ */ #include <sys/cdefs.h> #include <stdlib.h> #include "rtld_lock.h" #include "thr_private.h" static int _thr_rtld_clr_flag(int); static void *_thr_rtld_lock_create(void); static void _thr_rtld_lock_destroy(void *); static void _thr_rtld_lock_release(void *); static void _thr_rtld_rlock_acquire(void *); static int _thr_rtld_set_flag(int); static void _thr_rtld_wlock_acquire(void *); #ifdef NOTYET static void * _thr_rtld_lock_create(void) { pthread_rwlock_t prwlock; if (_pthread_rwlock_init(&prwlock, NULL)) return (NULL); return (prwlock); } static void _thr_rtld_lock_destroy(void *lock) { pthread_rwlock_t prwlock; prwlock = (pthread_rwlock_t)lock; if (prwlock != NULL) _pthread_rwlock_destroy(&prwlock); } static void _thr_rtld_rlock_acquire(void *lock) { pthread_rwlock_t prwlock; prwlock = (pthread_rwlock_t)lock; _thr_rwlock_rdlock(&prwlock); } static void _thr_rtld_wlock_acquire(void *lock) { pthread_rwlock_t prwlock; prwlock = (pthread_rwlock_t)lock; _thr_rwlock_wrlock(&prwlock); } static void _thr_rtld_lock_release(void *lock) { pthread_rwlock_t prwlock; prwlock = (pthread_rwlock_t)lock; _thr_rwlock_unlock(&prwlock); } static int _thr_rtld_set_flag(int mask) { struct pthread *curthread; int bits; curthread = _get_curthread(); if (curthread != NULL) { bits = curthread->rtld_bits; curthread->rtld_bits |= mask; } else { bits = 0; PANIC("No current thread in rtld call"); } return (bits); } static int _thr_rtld_clr_flag(int mask) { struct pthread *curthread; int bits; curthread = _get_curthread(); if (curthread != NULL) { bits = curthread->rtld_bits; curthread->rtld_bits &= ~mask; } else { bits = 0; PANIC("No current thread in rtld call"); } return (bits); } void _thr_rtld_init(void) { struct RtldLockInfo li; li.lock_create = _thr_rtld_lock_create; li.lock_destroy = _thr_rtld_lock_destroy; li.rlock_acquire = _thr_rtld_rlock_acquire; li.wlock_acquire = _thr_rtld_wlock_acquire; li.lock_release = _thr_rtld_lock_release; li.thread_set_flag = _thr_rtld_set_flag; li.thread_clr_flag = _thr_rtld_clr_flag; li.at_fork = NULL; _rtld_thread_init(&li); } void _thr_rtld_fini(void) { _rtld_thread_init(NULL); } #endif struct rtld_kse_lock { struct lock lck; struct kse *owner; kse_critical_t crit; int count; int write; }; static void * _thr_rtld_lock_create(void) { struct rtld_kse_lock *l; if ((l = malloc(sizeof(struct rtld_kse_lock))) != NULL) { _lock_init(&l->lck, LCK_ADAPTIVE, _kse_lock_wait, _kse_lock_wakeup, calloc); l->owner = NULL; l->count = 0; l->write = 0; } return (l); } static void _thr_rtld_lock_destroy(void *lock __unused) { /* XXX We really can not free memory after a fork() */ #if 0 struct rtld_kse_lock *l; l = (struct rtld_kse_lock *)lock; _lock_destroy(&l->lck); free(l); #endif return; } static void _thr_rtld_rlock_acquire(void *lock) { struct rtld_kse_lock *l; kse_critical_t crit; struct kse *curkse; l = (struct rtld_kse_lock *)lock; crit = _kse_critical_enter(); curkse = _get_curkse(); if (l->owner == curkse) { l->count++; _kse_critical_leave(crit); /* probably not necessary */ } else { KSE_LOCK_ACQUIRE(curkse, &l->lck); l->crit = crit; l->owner = curkse; l->count = 1; l->write = 0; } } static void _thr_rtld_wlock_acquire(void *lock) { struct rtld_kse_lock *l; kse_critical_t crit; struct kse *curkse; l = (struct rtld_kse_lock *)lock; crit = _kse_critical_enter(); curkse = _get_curkse(); if (l->owner == curkse) { _kse_critical_leave(crit); PANIC("Recursive write lock attempt on rtld lock"); } else { KSE_LOCK_ACQUIRE(curkse, &l->lck); l->crit = crit; l->owner = curkse; l->count = 1; l->write = 1; } } static void _thr_rtld_lock_release(void *lock) { struct rtld_kse_lock *l; kse_critical_t crit; struct kse *curkse; l = (struct rtld_kse_lock *)lock; crit = _kse_critical_enter(); curkse = _get_curkse(); if (l->owner != curkse) { /* * We might want to forcibly unlock the rtld lock * and/or disable threaded mode so there is better * chance that the panic will work. Otherwise, * we could end up trying to take the rtld lock * again. */ _kse_critical_leave(crit); PANIC("Attempt to unlock rtld lock when not owner."); } else { l->count--; if (l->count == 0) { /* * If there ever is a count associated with * _kse_critical_leave(), we'll need to add * another call to it here with the crit * value from above. */ crit = l->crit; l->owner = NULL; l->write = 0; KSE_LOCK_RELEASE(curkse, &l->lck); } _kse_critical_leave(crit); } } static int _thr_rtld_set_flag(int mask __unused) { return (0); } static int _thr_rtld_clr_flag(int mask __unused) { return (0); } void _thr_rtld_init(void) { struct RtldLockInfo li; li.lock_create = _thr_rtld_lock_create; li.lock_destroy = _thr_rtld_lock_destroy; li.rlock_acquire = _thr_rtld_rlock_acquire; li.wlock_acquire = _thr_rtld_wlock_acquire; li.lock_release = _thr_rtld_lock_release; li.thread_set_flag = _thr_rtld_set_flag; li.thread_clr_flag = _thr_rtld_clr_flag; li.at_fork = NULL; _rtld_thread_init(&li); } void _thr_rtld_fini(void) { _rtld_thread_init(NULL); }
dplbsd/zcaplib
head/lib/libkse/thread/thr_rtld.c
C
bsd-2-clause
6,843
/* $Id$ */ #include "platform.h" #include "di_defs.h" #include "pc.h" #include "dqueue.h" #include "adapter.h" #include "entity.h" #include "um_xdi.h" #include "um_idi.h" #include "debuglib.h" #include "divasync.h" #define DIVAS_MAX_XDI_ADAPTERS 64 /* -------------------------------------------------------------------------- IMPORTS -------------------------------------------------------------------------- */ extern void diva_os_wakeup_read(void *os_context); extern void diva_os_wakeup_close(void *os_context); /* -------------------------------------------------------------------------- LOCALS -------------------------------------------------------------------------- */ static LIST_HEAD(adapter_q); static diva_os_spin_lock_t adapter_lock; static diva_um_idi_adapter_t *diva_um_idi_find_adapter(dword nr); static void cleanup_adapter(diva_um_idi_adapter_t *a); static void cleanup_entity(divas_um_idi_entity_t *e); static int diva_user_mode_idi_adapter_features(diva_um_idi_adapter_t *a, diva_um_idi_adapter_features_t *features); static int process_idi_request(divas_um_idi_entity_t *e, const diva_um_idi_req_hdr_t *req); static int process_idi_rc(divas_um_idi_entity_t *e, byte rc); static int process_idi_ind(divas_um_idi_entity_t *e, byte ind); static int write_return_code(divas_um_idi_entity_t *e, byte rc); /* -------------------------------------------------------------------------- MAIN -------------------------------------------------------------------------- */ int diva_user_mode_idi_init(void) { diva_os_initialize_spin_lock(&adapter_lock, "adapter"); return (0); } /* -------------------------------------------------------------------------- Copy adapter features to user supplied buffer -------------------------------------------------------------------------- */ static int diva_user_mode_idi_adapter_features(diva_um_idi_adapter_t *a, diva_um_idi_adapter_features_t * features) { IDI_SYNC_REQ sync_req; if ((a) && (a->d.request)) { features->type = a->d.type; features->features = a->d.features; features->channels = a->d.channels; memset(features->name, 0, sizeof(features->name)); sync_req.GetName.Req = 0; sync_req.GetName.Rc = IDI_SYNC_REQ_GET_NAME; (*(a->d.request)) ((ENTITY *)&sync_req); strlcpy(features->name, sync_req.GetName.name, sizeof(features->name)); sync_req.GetSerial.Req = 0; sync_req.GetSerial.Rc = IDI_SYNC_REQ_GET_SERIAL; sync_req.GetSerial.serial = 0; (*(a->d.request))((ENTITY *)&sync_req); features->serial_number = sync_req.GetSerial.serial; } return ((a) ? 0 : -1); } /* -------------------------------------------------------------------------- REMOVE ADAPTER -------------------------------------------------------------------------- */ void diva_user_mode_idi_remove_adapter(int adapter_nr) { struct list_head *tmp; diva_um_idi_adapter_t *a; list_for_each(tmp, &adapter_q) { a = list_entry(tmp, diva_um_idi_adapter_t, link); if (a->adapter_nr == adapter_nr) { list_del(tmp); cleanup_adapter(a); DBG_LOG(("DIDD: del adapter(%d)", a->adapter_nr)); diva_os_free(0, a); break; } } } /* -------------------------------------------------------------------------- CALLED ON DRIVER EXIT (UNLOAD) -------------------------------------------------------------------------- */ void diva_user_mode_idi_finit(void) { struct list_head *tmp, *safe; diva_um_idi_adapter_t *a; list_for_each_safe(tmp, safe, &adapter_q) { a = list_entry(tmp, diva_um_idi_adapter_t, link); list_del(tmp); cleanup_adapter(a); DBG_LOG(("DIDD: del adapter(%d)", a->adapter_nr)); diva_os_free(0, a); } diva_os_destroy_spin_lock(&adapter_lock, "adapter"); } /* ------------------------------------------------------------------------- CREATE AND INIT IDI ADAPTER ------------------------------------------------------------------------- */ int diva_user_mode_idi_create_adapter(const DESCRIPTOR *d, int adapter_nr) { diva_os_spin_lock_magic_t old_irql; diva_um_idi_adapter_t *a = (diva_um_idi_adapter_t *) diva_os_malloc(0, sizeof (diva_um_idi_adapter_t)); if (!a) { return (-1); } memset(a, 0x00, sizeof(*a)); INIT_LIST_HEAD(&a->entity_q); a->d = *d; a->adapter_nr = adapter_nr; DBG_LOG(("DIDD_ADD A(%d), type:%02x, features:%04x, channels:%d", adapter_nr, a->d.type, a->d.features, a->d.channels)); diva_os_enter_spin_lock(&adapter_lock, &old_irql, "create_adapter"); list_add_tail(&a->link, &adapter_q); diva_os_leave_spin_lock(&adapter_lock, &old_irql, "create_adapter"); return (0); } /* ------------------------------------------------------------------------ Find adapter by Adapter number ------------------------------------------------------------------------ */ static diva_um_idi_adapter_t *diva_um_idi_find_adapter(dword nr) { diva_um_idi_adapter_t *a = NULL; struct list_head *tmp; list_for_each(tmp, &adapter_q) { a = list_entry(tmp, diva_um_idi_adapter_t, link); DBG_TRC(("find_adapter: (%d)-(%d)", nr, a->adapter_nr)); if (a->adapter_nr == (int)nr) break; a = NULL; } return (a); } /* ------------------------------------------------------------------------ Cleanup this adapter and cleanup/delete all entities assigned to this adapter ------------------------------------------------------------------------ */ static void cleanup_adapter(diva_um_idi_adapter_t *a) { struct list_head *tmp, *safe; divas_um_idi_entity_t *e; list_for_each_safe(tmp, safe, &a->entity_q) { e = list_entry(tmp, divas_um_idi_entity_t, link); list_del(tmp); cleanup_entity(e); if (e->os_context) { diva_os_wakeup_read(e->os_context); diva_os_wakeup_close(e->os_context); } } memset(&a->d, 0x00, sizeof(DESCRIPTOR)); } /* ------------------------------------------------------------------------ Cleanup, but NOT delete this entity ------------------------------------------------------------------------ */ static void cleanup_entity(divas_um_idi_entity_t *e) { e->os_ref = NULL; e->status = 0; e->adapter = NULL; e->e.Id = 0; e->rc_count = 0; e->status |= DIVA_UM_IDI_REMOVED; e->status |= DIVA_UM_IDI_REMOVE_PENDING; diva_data_q_finit(&e->data); diva_data_q_finit(&e->rc); } /* ------------------------------------------------------------------------ Create ENTITY, link it to the adapter and remove pointer to entity ------------------------------------------------------------------------ */ void *divas_um_idi_create_entity(dword adapter_nr, void *file) { divas_um_idi_entity_t *e; diva_um_idi_adapter_t *a; diva_os_spin_lock_magic_t old_irql; if ((e = (divas_um_idi_entity_t *) diva_os_malloc(0, sizeof(*e)))) { memset(e, 0x00, sizeof(*e)); if (! (e->os_context = diva_os_malloc(0, diva_os_get_context_size()))) { DBG_LOG(("E(%08x) no memory for os context", e)); diva_os_free(0, e); return NULL; } memset(e->os_context, 0x00, diva_os_get_context_size()); if ((diva_data_q_init(&e->data, 2048 + 512, 16))) { diva_os_free(0, e->os_context); diva_os_free(0, e); return NULL; } if ((diva_data_q_init(&e->rc, sizeof(diva_um_idi_ind_hdr_t), 2))) { diva_data_q_finit(&e->data); diva_os_free(0, e->os_context); diva_os_free(0, e); return NULL; } diva_os_enter_spin_lock(&adapter_lock, &old_irql, "create_entity"); /* Look for Adapter requested */ if (!(a = diva_um_idi_find_adapter(adapter_nr))) { /* No adapter was found, or this adapter was removed */ diva_os_leave_spin_lock(&adapter_lock, &old_irql, "create_entity"); DBG_LOG(("A: no adapter(%ld)", adapter_nr)); cleanup_entity(e); diva_os_free(0, e->os_context); diva_os_free(0, e); return NULL; } e->os_ref = file; /* link to os handle */ e->adapter = a; /* link to adapter */ list_add_tail(&e->link, &a->entity_q); /* link from adapter */ diva_os_leave_spin_lock(&adapter_lock, &old_irql, "create_entity"); DBG_LOG(("A(%ld), create E(%08x)", adapter_nr, e)); } return (e); } /* ------------------------------------------------------------------------ Unlink entity and free memory ------------------------------------------------------------------------ */ int divas_um_idi_delete_entity(int adapter_nr, void *entity) { divas_um_idi_entity_t *e; diva_um_idi_adapter_t *a; diva_os_spin_lock_magic_t old_irql; if (!(e = (divas_um_idi_entity_t *) entity)) return (-1); diva_os_enter_spin_lock(&adapter_lock, &old_irql, "delete_entity"); if ((a = e->adapter)) { list_del(&e->link); } diva_os_leave_spin_lock(&adapter_lock, &old_irql, "delete_entity"); diva_um_idi_stop_wdog(entity); cleanup_entity(e); diva_os_free(0, e->os_context); memset(e, 0x00, sizeof(*e)); diva_os_free(0, e); DBG_LOG(("A(%d) remove E:%08x", adapter_nr, e)); return (0); } /* -------------------------------------------------------------------------- Called by application to read data from IDI -------------------------------------------------------------------------- */ int diva_um_idi_read(void *entity, void *os_handle, void *dst, int max_length, divas_um_idi_copy_to_user_fn_t cp_fn) { divas_um_idi_entity_t *e; diva_um_idi_adapter_t *a; const void *data; int length, ret = 0; diva_um_idi_data_queue_t *q; diva_os_spin_lock_magic_t old_irql; diva_os_enter_spin_lock(&adapter_lock, &old_irql, "read"); e = (divas_um_idi_entity_t *) entity; if (!e || (!(a = e->adapter)) || (e->status & DIVA_UM_IDI_REMOVE_PENDING) || (e->status & DIVA_UM_IDI_REMOVED) || (a->status & DIVA_UM_IDI_ADAPTER_REMOVED)) { diva_os_leave_spin_lock(&adapter_lock, &old_irql, "read"); DBG_ERR(("E(%08x) read failed - adapter removed", e)) return (-1); } DBG_TRC(("A(%d) E(%08x) read(%d)", a->adapter_nr, e, max_length)); /* Try to read return code first */ data = diva_data_q_get_segment4read(&e->rc); q = &e->rc; /* No return codes available, read indications now */ if (!data) { if (!(e->status & DIVA_UM_IDI_RC_PENDING)) { DBG_TRC(("A(%d) E(%08x) read data", a->adapter_nr, e)); data = diva_data_q_get_segment4read(&e->data); q = &e->data; } } else { e->status &= ~DIVA_UM_IDI_RC_PENDING; DBG_TRC(("A(%d) E(%08x) read rc", a->adapter_nr, e)); } if (data) { if ((length = diva_data_q_get_segment_length(q)) > max_length) { /* Not enough space to read message */ DBG_ERR(("A: A(%d) E(%08x) read small buffer", a->adapter_nr, e, ret)); diva_os_leave_spin_lock(&adapter_lock, &old_irql, "read"); return (-2); } /* Copy it to user, this function does access ONLY locked an verified memory, also we can access it witch spin lock held */ if ((ret = (*cp_fn) (os_handle, dst, data, length)) >= 0) { /* Acknowledge only if read was successful */ diva_data_q_ack_segment4read(q); } } DBG_TRC(("A(%d) E(%08x) read=%d", a->adapter_nr, e, ret)); diva_os_leave_spin_lock(&adapter_lock, &old_irql, "read"); return (ret); } int diva_um_idi_write(void *entity, void *os_handle, const void *src, int length, divas_um_idi_copy_from_user_fn_t cp_fn) { divas_um_idi_entity_t *e; diva_um_idi_adapter_t *a; diva_um_idi_req_hdr_t *req; void *data; int ret = 0; diva_os_spin_lock_magic_t old_irql; diva_os_enter_spin_lock(&adapter_lock, &old_irql, "write"); e = (divas_um_idi_entity_t *) entity; if (!e || (!(a = e->adapter)) || (e->status & DIVA_UM_IDI_REMOVE_PENDING) || (e->status & DIVA_UM_IDI_REMOVED) || (a->status & DIVA_UM_IDI_ADAPTER_REMOVED)) { diva_os_leave_spin_lock(&adapter_lock, &old_irql, "write"); DBG_ERR(("E(%08x) write failed - adapter removed", e)) return (-1); } DBG_TRC(("A(%d) E(%08x) write(%d)", a->adapter_nr, e, length)); if ((length < sizeof(*req)) || (length > sizeof(e->buffer))) { diva_os_leave_spin_lock(&adapter_lock, &old_irql, "write"); return (-2); } if (e->status & DIVA_UM_IDI_RC_PENDING) { DBG_ERR(("A: A(%d) E(%08x) rc pending", a->adapter_nr, e)); diva_os_leave_spin_lock(&adapter_lock, &old_irql, "write"); return (-1); /* should wait for RC code first */ } /* Copy function does access only locked verified memory, also it can be called with spin lock held */ if ((ret = (*cp_fn) (os_handle, e->buffer, src, length)) < 0) { DBG_TRC(("A: A(%d) E(%08x) write error=%d", a->adapter_nr, e, ret)); diva_os_leave_spin_lock(&adapter_lock, &old_irql, "write"); return (ret); } req = (diva_um_idi_req_hdr_t *)&e->buffer[0]; switch (req->type) { case DIVA_UM_IDI_GET_FEATURES:{ DBG_LOG(("A(%d) get_features", a->adapter_nr)); if (!(data = diva_data_q_get_segment4write(&e->data))) { DBG_ERR(("A(%d) get_features, no free buffer", a->adapter_nr)); diva_os_leave_spin_lock(&adapter_lock, &old_irql, "write"); return (0); } diva_user_mode_idi_adapter_features(a, &(((diva_um_idi_ind_hdr_t *) data)->hdr.features)); ((diva_um_idi_ind_hdr_t *) data)->type = DIVA_UM_IDI_IND_FEATURES; ((diva_um_idi_ind_hdr_t *) data)->data_length = 0; diva_data_q_ack_segment4write(&e->data, sizeof(diva_um_idi_ind_hdr_t)); diva_os_leave_spin_lock(&adapter_lock, &old_irql, "write"); diva_os_wakeup_read(e->os_context); } break; case DIVA_UM_IDI_REQ: case DIVA_UM_IDI_REQ_MAN: case DIVA_UM_IDI_REQ_SIG: case DIVA_UM_IDI_REQ_NET: DBG_TRC(("A(%d) REQ(%02d)-(%02d)-(%08x)", a->adapter_nr, req->Req, req->ReqCh, req->type & DIVA_UM_IDI_REQ_TYPE_MASK)); switch (process_idi_request(e, req)) { case -1: diva_os_leave_spin_lock(&adapter_lock, &old_irql, "write"); return (-1); case -2: diva_os_leave_spin_lock(&adapter_lock, &old_irql, "write"); diva_os_wakeup_read(e->os_context); break; default: diva_os_leave_spin_lock(&adapter_lock, &old_irql, "write"); break; } break; default: diva_os_leave_spin_lock(&adapter_lock, &old_irql, "write"); return (-1); } DBG_TRC(("A(%d) E(%08x) write=%d", a->adapter_nr, e, ret)); return (ret); } /* -------------------------------------------------------------------------- CALLBACK FROM XDI -------------------------------------------------------------------------- */ static void diva_um_idi_xdi_callback(ENTITY *entity) { divas_um_idi_entity_t *e = DIVAS_CONTAINING_RECORD(entity, divas_um_idi_entity_t, e); diva_os_spin_lock_magic_t old_irql; int call_wakeup = 0; diva_os_enter_spin_lock(&adapter_lock, &old_irql, "xdi_callback"); if (e->e.complete == 255) { if (!(e->status & DIVA_UM_IDI_REMOVE_PENDING)) { diva_um_idi_stop_wdog(e); } if ((call_wakeup = process_idi_rc(e, e->e.Rc))) { if (e->rc_count) { e->rc_count--; } } e->e.Rc = 0; diva_os_leave_spin_lock(&adapter_lock, &old_irql, "xdi_callback"); if (call_wakeup) { diva_os_wakeup_read(e->os_context); diva_os_wakeup_close(e->os_context); } } else { if (e->status & DIVA_UM_IDI_REMOVE_PENDING) { e->e.RNum = 0; e->e.RNR = 2; } else { call_wakeup = process_idi_ind(e, e->e.Ind); } e->e.Ind = 0; diva_os_leave_spin_lock(&adapter_lock, &old_irql, "xdi_callback"); if (call_wakeup) { diva_os_wakeup_read(e->os_context); } } } static int process_idi_request(divas_um_idi_entity_t *e, const diva_um_idi_req_hdr_t *req) { int assign = 0; byte Req = (byte) req->Req; dword type = req->type & DIVA_UM_IDI_REQ_TYPE_MASK; if (!e->e.Id || !e->e.callback) { /* not assigned */ if (Req != ASSIGN) { DBG_ERR(("A: A(%d) E(%08x) not assigned", e->adapter->adapter_nr, e)); return (-1); /* NOT ASSIGNED */ } else { switch (type) { case DIVA_UM_IDI_REQ_TYPE_MAN: e->e.Id = MAN_ID; DBG_TRC(("A(%d) E(%08x) assign MAN", e->adapter->adapter_nr, e)); break; case DIVA_UM_IDI_REQ_TYPE_SIG: e->e.Id = DSIG_ID; DBG_TRC(("A(%d) E(%08x) assign SIG", e->adapter->adapter_nr, e)); break; case DIVA_UM_IDI_REQ_TYPE_NET: e->e.Id = NL_ID; DBG_TRC(("A(%d) E(%08x) assign NET", e->adapter->adapter_nr, e)); break; default: DBG_ERR(("A: A(%d) E(%08x) unknown type=%08x", e->adapter->adapter_nr, e, type)); return (-1); } } e->e.XNum = 1; e->e.RNum = 1; e->e.callback = diva_um_idi_xdi_callback; e->e.X = &e->XData; e->e.R = &e->RData; assign = 1; } e->status |= DIVA_UM_IDI_RC_PENDING; e->e.Req = Req; e->e.ReqCh = (byte) req->ReqCh; e->e.X->PLength = (word) req->data_length; e->e.X->P = (byte *)&req[1]; /* Our buffer is safe */ DBG_TRC(("A(%d) E(%08x) request(%02x-%02x-%02x (%d))", e->adapter->adapter_nr, e, e->e.Id, e->e.Req, e->e.ReqCh, e->e.X->PLength)); e->rc_count++; if (e->adapter && e->adapter->d.request) { diva_um_idi_start_wdog(e); (*(e->adapter->d.request)) (&e->e); } if (assign) { if (e->e.Rc == OUT_OF_RESOURCES) { /* XDI has no entities more, call was not forwarded to the card, no callback will be scheduled */ DBG_ERR(("A: A(%d) E(%08x) XDI out of entities", e->adapter->adapter_nr, e)); e->e.Id = 0; e->e.ReqCh = 0; e->e.RcCh = 0; e->e.Ind = 0; e->e.IndCh = 0; e->e.XNum = 0; e->e.RNum = 0; e->e.callback = NULL; e->e.X = NULL; e->e.R = NULL; write_return_code(e, ASSIGN_RC | OUT_OF_RESOURCES); return (-2); } else { e->status |= DIVA_UM_IDI_ASSIGN_PENDING; } } return (0); } static int process_idi_rc(divas_um_idi_entity_t *e, byte rc) { DBG_TRC(("A(%d) E(%08x) rc(%02x-%02x-%02x)", e->adapter->adapter_nr, e, e->e.Id, rc, e->e.RcCh)); if (e->status & DIVA_UM_IDI_ASSIGN_PENDING) { e->status &= ~DIVA_UM_IDI_ASSIGN_PENDING; if (rc != ASSIGN_OK) { DBG_ERR(("A: A(%d) E(%08x) ASSIGN failed", e->adapter->adapter_nr, e)); e->e.callback = NULL; e->e.Id = 0; e->e.Req = 0; e->e.ReqCh = 0; e->e.Rc = 0; e->e.RcCh = 0; e->e.Ind = 0; e->e.IndCh = 0; e->e.X = NULL; e->e.R = NULL; e->e.XNum = 0; e->e.RNum = 0; } } if ((e->e.Req == REMOVE) && e->e.Id && (rc == 0xff)) { DBG_ERR(("A: A(%d) E(%08x) discard OK in REMOVE", e->adapter->adapter_nr, e)); return (0); /* let us do it in the driver */ } if ((e->e.Req == REMOVE) && (!e->e.Id)) { /* REMOVE COMPLETE */ e->e.callback = NULL; e->e.Id = 0; e->e.Req = 0; e->e.ReqCh = 0; e->e.Rc = 0; e->e.RcCh = 0; e->e.Ind = 0; e->e.IndCh = 0; e->e.X = NULL; e->e.R = NULL; e->e.XNum = 0; e->e.RNum = 0; e->rc_count = 0; } if ((e->e.Req == REMOVE) && (rc != 0xff)) { /* REMOVE FAILED */ DBG_ERR(("A: A(%d) E(%08x) REMOVE FAILED", e->adapter->adapter_nr, e)); } write_return_code(e, rc); return (1); } static int process_idi_ind(divas_um_idi_entity_t *e, byte ind) { int do_wakeup = 0; if (e->e.complete != 0x02) { diva_um_idi_ind_hdr_t *pind = (diva_um_idi_ind_hdr_t *) diva_data_q_get_segment4write(&e->data); if (pind) { e->e.RNum = 1; e->e.R->P = (byte *)&pind[1]; e->e.R->PLength = (word) (diva_data_q_get_max_length(&e->data) - sizeof(*pind)); DBG_TRC(("A(%d) E(%08x) ind_1(%02x-%02x-%02x)-[%d-%d]", e->adapter->adapter_nr, e, e->e.Id, ind, e->e.IndCh, e->e.RLength, e->e.R->PLength)); } else { DBG_TRC(("A(%d) E(%08x) ind(%02x-%02x-%02x)-RNR", e->adapter->adapter_nr, e, e->e.Id, ind, e->e.IndCh)); e->e.RNum = 0; e->e.RNR = 1; do_wakeup = 1; } } else { diva_um_idi_ind_hdr_t *pind = (diva_um_idi_ind_hdr_t *) (e->e.R->P); DBG_TRC(("A(%d) E(%08x) ind(%02x-%02x-%02x)-[%d]", e->adapter->adapter_nr, e, e->e.Id, ind, e->e.IndCh, e->e.R->PLength)); pind--; pind->type = DIVA_UM_IDI_IND; pind->hdr.ind.Ind = ind; pind->hdr.ind.IndCh = e->e.IndCh; pind->data_length = e->e.R->PLength; diva_data_q_ack_segment4write(&e->data, (int) (sizeof(*pind) + e->e.R->PLength)); do_wakeup = 1; } if ((e->status & DIVA_UM_IDI_RC_PENDING) && !e->rc.count) { do_wakeup = 0; } return (do_wakeup); } /* -------------------------------------------------------------------------- Write return code to the return code queue of entity -------------------------------------------------------------------------- */ static int write_return_code(divas_um_idi_entity_t *e, byte rc) { diva_um_idi_ind_hdr_t *prc; if (!(prc = (diva_um_idi_ind_hdr_t *) diva_data_q_get_segment4write(&e->rc))) { DBG_ERR(("A: A(%d) E(%08x) rc(%02x) lost", e->adapter->adapter_nr, e, rc)); e->status &= ~DIVA_UM_IDI_RC_PENDING; return (-1); } prc->type = DIVA_UM_IDI_IND_RC; prc->hdr.rc.Rc = rc; prc->hdr.rc.RcCh = e->e.RcCh; prc->data_length = 0; diva_data_q_ack_segment4write(&e->rc, sizeof(*prc)); return (0); } /* -------------------------------------------------------------------------- Return amount of entries that can be bead from this entity or -1 if adapter was removed -------------------------------------------------------------------------- */ int diva_user_mode_idi_ind_ready(void *entity, void *os_handle) { divas_um_idi_entity_t *e; diva_um_idi_adapter_t *a; diva_os_spin_lock_magic_t old_irql; int ret; if (!entity) return (-1); diva_os_enter_spin_lock(&adapter_lock, &old_irql, "ind_ready"); e = (divas_um_idi_entity_t *) entity; a = e->adapter; if ((!a) || (a->status & DIVA_UM_IDI_ADAPTER_REMOVED)) { /* Adapter was unloaded */ diva_os_leave_spin_lock(&adapter_lock, &old_irql, "ind_ready"); return (-1); /* adapter was removed */ } if (e->status & DIVA_UM_IDI_REMOVED) { /* entity was removed as result of adapter removal user should assign this entity again */ diva_os_leave_spin_lock(&adapter_lock, &old_irql, "ind_ready"); return (-1); } ret = e->rc.count + e->data.count; if ((e->status & DIVA_UM_IDI_RC_PENDING) && !e->rc.count) { ret = 0; } diva_os_leave_spin_lock(&adapter_lock, &old_irql, "ind_ready"); return (ret); } void *diva_um_id_get_os_context(void *entity) { return (((divas_um_idi_entity_t *) entity)->os_context); } int divas_um_idi_entity_assigned(void *entity) { divas_um_idi_entity_t *e; diva_um_idi_adapter_t *a; int ret; diva_os_spin_lock_magic_t old_irql; diva_os_enter_spin_lock(&adapter_lock, &old_irql, "assigned?"); e = (divas_um_idi_entity_t *) entity; if (!e || (!(a = e->adapter)) || (e->status & DIVA_UM_IDI_REMOVED) || (a->status & DIVA_UM_IDI_ADAPTER_REMOVED)) { diva_os_leave_spin_lock(&adapter_lock, &old_irql, "assigned?"); return (0); } e->status |= DIVA_UM_IDI_REMOVE_PENDING; ret = (e->e.Id || e->rc_count || (e->status & DIVA_UM_IDI_ASSIGN_PENDING)); DBG_TRC(("Id:%02x, rc_count:%d, status:%08x", e->e.Id, e->rc_count, e->status)) diva_os_leave_spin_lock(&adapter_lock, &old_irql, "assigned?"); return (ret); } int divas_um_idi_entity_start_remove(void *entity) { divas_um_idi_entity_t *e; diva_um_idi_adapter_t *a; diva_os_spin_lock_magic_t old_irql; diva_os_enter_spin_lock(&adapter_lock, &old_irql, "start_remove"); e = (divas_um_idi_entity_t *) entity; if (!e || (!(a = e->adapter)) || (e->status & DIVA_UM_IDI_REMOVED) || (a->status & DIVA_UM_IDI_ADAPTER_REMOVED)) { diva_os_leave_spin_lock(&adapter_lock, &old_irql, "start_remove"); return (0); } if (e->rc_count) { /* Entity BUSY */ diva_os_leave_spin_lock(&adapter_lock, &old_irql, "start_remove"); return (1); } if (!e->e.Id) { /* Remove request was already pending, and arrived now */ diva_os_leave_spin_lock(&adapter_lock, &old_irql, "start_remove"); return (0); /* REMOVE was pending */ } /* Now send remove request */ e->e.Req = REMOVE; e->e.ReqCh = 0; e->rc_count++; DBG_TRC(("A(%d) E(%08x) request(%02x-%02x-%02x (%d))", e->adapter->adapter_nr, e, e->e.Id, e->e.Req, e->e.ReqCh, e->e.X->PLength)); if (a->d.request) (*(a->d.request)) (&e->e); diva_os_leave_spin_lock(&adapter_lock, &old_irql, "start_remove"); return (0); }
andrewjylee/omniplay
linux-lts-quantal-3.5.0/drivers/isdn/hardware/eicon/um_idi.c
C
bsd-2-clause
24,027
/* -- translated by f2c (version 20100827). You must link the resulting object file with libf2c: on Microsoft Windows system, link with libf2c.lib; on Linux or Unix systems, link with .../path/to/libf2c.a -lm or, if you install libf2c.a in a standard place, with -lf2c -lm -- in that order, at the end of the command line, as in cc *.o -lf2c -lm Source for libf2c is in /netlib/f2c/libf2c.zip, e.g., http://www.netlib.org/f2c/libf2c.zip */ #include "f2c.h" /* Table of constant values */ static doublecomplex c_b1 = {1.,0.}; static blasint c__1 = 1; /** ZSYTRF_REC2 computes a partial factorization of a complex symmetric matrix using the Bunch-Kaufman diagon al pivoting method. * * This routine is a minor modification of LAPACK's zlasyf. * It serves as an unblocked kernel in the recursive algorithms. * The blocked BLAS Level 3 updates were removed and moved to the * recursive algorithm. * */ /* Subroutine */ void RELAPACK_zsytrf_rec2(char *uplo, blasint *n, blasint * nb, blasint *kb, doublecomplex *a, blasint *lda, blasint *ipiv, doublecomplex *w, blasint *ldw, blasint *info, ftnlen uplo_len) { /* System generated locals */ blasint a_dim1, a_offset, w_dim1, w_offset, i__1, i__2, i__3, i__4; double d__1, d__2, d__3, d__4; doublecomplex z__1, z__2, z__3; /* Builtin functions */ double sqrt(double), d_imag(doublecomplex *); void z_div(doublecomplex *, doublecomplex *, doublecomplex *); /* Local variables */ static blasint j, k; static doublecomplex t, r1, d11, d21, d22; static blasint jj, kk, jp, kp, kw, kkw, imax, jmax; static double alpha; extern logical lsame_(char *, char *, ftnlen, ftnlen); extern /* Subroutine */ blasint zscal_(int *, doublecomplex *, doublecomplex *, blasint *); static blasint kstep; extern /* Subroutine */ blasint zgemv_(char *, blasint *, blasint *, doublecomplex *, doublecomplex *, blasint *, doublecomplex *, blasint *, doublecomplex *, doublecomplex *, blasint *, ftnlen), zcopy_(int *, doublecomplex *, blasint *, doublecomplex *, blasint *), zswap_(int *, doublecomplex *, blasint *, doublecomplex *, blasint *); static double absakk, colmax; extern blasint izamax_(int *, doublecomplex *, blasint *); static double rowmax; /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --ipiv; w_dim1 = *ldw; w_offset = 1 + w_dim1; w -= w_offset; /* Function Body */ *info = 0; alpha = (sqrt(17.) + 1.) / 8.; if (lsame_(uplo, "U", (ftnlen)1, (ftnlen)1)) { k = *n; L10: kw = *nb + k - *n; if ((k <= *n - *nb + 1 && *nb < *n) || k < 1) { goto L30; } zcopy_(&k, &a[k * a_dim1 + 1], &c__1, &w[kw * w_dim1 + 1], &c__1); if (k < *n) { i__1 = *n - k; z__1.r = -1., z__1.i = -0.; zgemv_("No transpose", &k, &i__1, &z__1, &a[(k + 1) * a_dim1 + 1], lda, &w[k + (kw + 1) * w_dim1], ldw, &c_b1, &w[kw * w_dim1 + 1], &c__1, (ftnlen)12); } kstep = 1; i__1 = k + kw * w_dim1; absakk = (d__1 = w[i__1].r, abs(d__1)) + (d__2 = d_imag(&w[k + kw * w_dim1]), abs(d__2)); if (k > 1) { i__1 = k - 1; imax = izamax_(&i__1, &w[kw * w_dim1 + 1], &c__1); i__1 = imax + kw * w_dim1; colmax = (d__1 = w[i__1].r, abs(d__1)) + (d__2 = d_imag(&w[imax + kw * w_dim1]), abs(d__2)); } else { colmax = 0.; } if (max(absakk,colmax) == 0.) { if (*info == 0) { *info = k; } kp = k; } else { if (absakk >= alpha * colmax) { kp = k; } else { zcopy_(&imax, &a[imax * a_dim1 + 1], &c__1, &w[(kw - 1) * w_dim1 + 1], &c__1); i__1 = k - imax; zcopy_(&i__1, &a[imax + (imax + 1) * a_dim1], lda, &w[imax + 1 + (kw - 1) * w_dim1], &c__1); if (k < *n) { i__1 = *n - k; z__1.r = -1., z__1.i = -0.; zgemv_("No transpose", &k, &i__1, &z__1, &a[(k + 1) * a_dim1 + 1], lda, &w[imax + (kw + 1) * w_dim1], ldw, &c_b1, &w[(kw - 1) * w_dim1 + 1], &c__1, ( ftnlen)12); } i__1 = k - imax; jmax = imax + izamax_(&i__1, &w[imax + 1 + (kw - 1) * w_dim1], &c__1); i__1 = jmax + (kw - 1) * w_dim1; rowmax = (d__1 = w[i__1].r, abs(d__1)) + (d__2 = d_imag(&w[ jmax + (kw - 1) * w_dim1]), abs(d__2)); if (imax > 1) { i__1 = imax - 1; jmax = izamax_(&i__1, &w[(kw - 1) * w_dim1 + 1], &c__1); /* Computing MAX */ i__1 = jmax + (kw - 1) * w_dim1; d__3 = rowmax, d__4 = (d__1 = w[i__1].r, abs(d__1)) + ( d__2 = d_imag(&w[jmax + (kw - 1) * w_dim1]), abs( d__2)); rowmax = max(d__3,d__4); } if (absakk >= alpha * colmax * (colmax / rowmax)) { kp = k; } else /* if(complicated condition) */ { i__1 = imax + (kw - 1) * w_dim1; if ((d__1 = w[i__1].r, abs(d__1)) + (d__2 = d_imag(&w[ imax + (kw - 1) * w_dim1]), abs(d__2)) >= alpha * rowmax) { kp = imax; zcopy_(&k, &w[(kw - 1) * w_dim1 + 1], &c__1, &w[kw * w_dim1 + 1], &c__1); } else { kp = imax; kstep = 2; } } } kk = k - kstep + 1; kkw = *nb + kk - *n; if (kp != kk) { i__1 = kp + kp * a_dim1; i__2 = kk + kk * a_dim1; a[i__1].r = a[i__2].r, a[i__1].i = a[i__2].i; i__1 = kk - 1 - kp; zcopy_(&i__1, &a[kp + 1 + kk * a_dim1], &c__1, &a[kp + (kp + 1) * a_dim1], lda); if (kp > 1) { i__1 = kp - 1; zcopy_(&i__1, &a[kk * a_dim1 + 1], &c__1, &a[kp * a_dim1 + 1], &c__1); } if (k < *n) { i__1 = *n - k; zswap_(&i__1, &a[kk + (k + 1) * a_dim1], lda, &a[kp + (k + 1) * a_dim1], lda); } i__1 = *n - kk + 1; zswap_(&i__1, &w[kk + kkw * w_dim1], ldw, &w[kp + kkw * w_dim1], ldw); } if (kstep == 1) { zcopy_(&k, &w[kw * w_dim1 + 1], &c__1, &a[k * a_dim1 + 1], & c__1); z_div(&z__1, &c_b1, &a[k + k * a_dim1]); r1.r = z__1.r, r1.i = z__1.i; i__1 = k - 1; zscal_(&i__1, &r1, &a[k * a_dim1 + 1], &c__1); } else { if (k > 2) { i__1 = k - 1 + kw * w_dim1; d21.r = w[i__1].r, d21.i = w[i__1].i; z_div(&z__1, &w[k + kw * w_dim1], &d21); d11.r = z__1.r, d11.i = z__1.i; z_div(&z__1, &w[k - 1 + (kw - 1) * w_dim1], &d21); d22.r = z__1.r, d22.i = z__1.i; z__3.r = d11.r * d22.r - d11.i * d22.i, z__3.i = d11.r * d22.i + d11.i * d22.r; z__2.r = z__3.r - 1., z__2.i = z__3.i - 0.; z_div(&z__1, &c_b1, &z__2); t.r = z__1.r, t.i = z__1.i; z_div(&z__1, &t, &d21); d21.r = z__1.r, d21.i = z__1.i; i__1 = k - 2; for (j = 1; j <= i__1; ++j) { i__2 = j + (k - 1) * a_dim1; i__3 = j + (kw - 1) * w_dim1; z__3.r = d11.r * w[i__3].r - d11.i * w[i__3].i, z__3.i = d11.r * w[i__3].i + d11.i * w[i__3] .r; i__4 = j + kw * w_dim1; z__2.r = z__3.r - w[i__4].r, z__2.i = z__3.i - w[i__4] .i; z__1.r = d21.r * z__2.r - d21.i * z__2.i, z__1.i = d21.r * z__2.i + d21.i * z__2.r; a[i__2].r = z__1.r, a[i__2].i = z__1.i; i__2 = j + k * a_dim1; i__3 = j + kw * w_dim1; z__3.r = d22.r * w[i__3].r - d22.i * w[i__3].i, z__3.i = d22.r * w[i__3].i + d22.i * w[i__3] .r; i__4 = j + (kw - 1) * w_dim1; z__2.r = z__3.r - w[i__4].r, z__2.i = z__3.i - w[i__4] .i; z__1.r = d21.r * z__2.r - d21.i * z__2.i, z__1.i = d21.r * z__2.i + d21.i * z__2.r; a[i__2].r = z__1.r, a[i__2].i = z__1.i; /* L20: */ } } i__1 = k - 1 + (k - 1) * a_dim1; i__2 = k - 1 + (kw - 1) * w_dim1; a[i__1].r = w[i__2].r, a[i__1].i = w[i__2].i; i__1 = k - 1 + k * a_dim1; i__2 = k - 1 + kw * w_dim1; a[i__1].r = w[i__2].r, a[i__1].i = w[i__2].i; i__1 = k + k * a_dim1; i__2 = k + kw * w_dim1; a[i__1].r = w[i__2].r, a[i__1].i = w[i__2].i; } } if (kstep == 1) { ipiv[k] = kp; } else { ipiv[k] = -kp; ipiv[k - 1] = -kp; } k -= kstep; goto L10; L30: j = k + 1; L60: jj = j; jp = ipiv[j]; if (jp < 0) { jp = -jp; ++j; } ++j; if (jp != jj && j <= *n) { i__1 = *n - j + 1; zswap_(&i__1, &a[jp + j * a_dim1], lda, &a[jj + j * a_dim1], lda); } if (j < *n) { goto L60; } *kb = *n - k; } else { k = 1; L70: if ((k >= *nb && *nb < *n) || k > *n) { goto L90; } i__1 = *n - k + 1; zcopy_(&i__1, &a[k + k * a_dim1], &c__1, &w[k + k * w_dim1], &c__1); i__1 = *n - k + 1; i__2 = k - 1; z__1.r = -1., z__1.i = -0.; zgemv_("No transpose", &i__1, &i__2, &z__1, &a[k + a_dim1], lda, &w[k + w_dim1], ldw, &c_b1, &w[k + k * w_dim1], &c__1, (ftnlen)12); kstep = 1; i__1 = k + k * w_dim1; absakk = (d__1 = w[i__1].r, abs(d__1)) + (d__2 = d_imag(&w[k + k * w_dim1]), abs(d__2)); if (k < *n) { i__1 = *n - k; imax = k + izamax_(&i__1, &w[k + 1 + k * w_dim1], &c__1); i__1 = imax + k * w_dim1; colmax = (d__1 = w[i__1].r, abs(d__1)) + (d__2 = d_imag(&w[imax + k * w_dim1]), abs(d__2)); } else { colmax = 0.; } if (max(absakk,colmax) == 0.) { if (*info == 0) { *info = k; } kp = k; } else { if (absakk >= alpha * colmax) { kp = k; } else { i__1 = imax - k; zcopy_(&i__1, &a[imax + k * a_dim1], lda, &w[k + (k + 1) * w_dim1], &c__1); i__1 = *n - imax + 1; zcopy_(&i__1, &a[imax + imax * a_dim1], &c__1, &w[imax + (k + 1) * w_dim1], &c__1); i__1 = *n - k + 1; i__2 = k - 1; z__1.r = -1., z__1.i = -0.; zgemv_("No transpose", &i__1, &i__2, &z__1, &a[k + a_dim1], lda, &w[imax + w_dim1], ldw, &c_b1, &w[k + (k + 1) * w_dim1], &c__1, (ftnlen)12); i__1 = imax - k; jmax = k - 1 + izamax_(&i__1, &w[k + (k + 1) * w_dim1], &c__1) ; i__1 = jmax + (k + 1) * w_dim1; rowmax = (d__1 = w[i__1].r, abs(d__1)) + (d__2 = d_imag(&w[ jmax + (k + 1) * w_dim1]), abs(d__2)); if (imax < *n) { i__1 = *n - imax; jmax = imax + izamax_(&i__1, &w[imax + 1 + (k + 1) * w_dim1], &c__1); /* Computing MAX */ i__1 = jmax + (k + 1) * w_dim1; d__3 = rowmax, d__4 = (d__1 = w[i__1].r, abs(d__1)) + ( d__2 = d_imag(&w[jmax + (k + 1) * w_dim1]), abs( d__2)); rowmax = max(d__3,d__4); } if (absakk >= alpha * colmax * (colmax / rowmax)) { kp = k; } else /* if(complicated condition) */ { i__1 = imax + (k + 1) * w_dim1; if ((d__1 = w[i__1].r, abs(d__1)) + (d__2 = d_imag(&w[ imax + (k + 1) * w_dim1]), abs(d__2)) >= alpha * rowmax) { kp = imax; i__1 = *n - k + 1; zcopy_(&i__1, &w[k + (k + 1) * w_dim1], &c__1, &w[k + k * w_dim1], &c__1); } else { kp = imax; kstep = 2; } } } kk = k + kstep - 1; if (kp != kk) { i__1 = kp + kp * a_dim1; i__2 = kk + kk * a_dim1; a[i__1].r = a[i__2].r, a[i__1].i = a[i__2].i; i__1 = kp - kk - 1; zcopy_(&i__1, &a[kk + 1 + kk * a_dim1], &c__1, &a[kp + (kk + 1) * a_dim1], lda); if (kp < *n) { i__1 = *n - kp; zcopy_(&i__1, &a[kp + 1 + kk * a_dim1], &c__1, &a[kp + 1 + kp * a_dim1], &c__1); } if (k > 1) { i__1 = k - 1; zswap_(&i__1, &a[kk + a_dim1], lda, &a[kp + a_dim1], lda); } zswap_(&kk, &w[kk + w_dim1], ldw, &w[kp + w_dim1], ldw); } if (kstep == 1) { i__1 = *n - k + 1; zcopy_(&i__1, &w[k + k * w_dim1], &c__1, &a[k + k * a_dim1], & c__1); if (k < *n) { z_div(&z__1, &c_b1, &a[k + k * a_dim1]); r1.r = z__1.r, r1.i = z__1.i; i__1 = *n - k; zscal_(&i__1, &r1, &a[k + 1 + k * a_dim1], &c__1); } } else { if (k < *n - 1) { i__1 = k + 1 + k * w_dim1; d21.r = w[i__1].r, d21.i = w[i__1].i; z_div(&z__1, &w[k + 1 + (k + 1) * w_dim1], &d21); d11.r = z__1.r, d11.i = z__1.i; z_div(&z__1, &w[k + k * w_dim1], &d21); d22.r = z__1.r, d22.i = z__1.i; z__3.r = d11.r * d22.r - d11.i * d22.i, z__3.i = d11.r * d22.i + d11.i * d22.r; z__2.r = z__3.r - 1., z__2.i = z__3.i - 0.; z_div(&z__1, &c_b1, &z__2); t.r = z__1.r, t.i = z__1.i; z_div(&z__1, &t, &d21); d21.r = z__1.r, d21.i = z__1.i; i__1 = *n; for (j = k + 2; j <= i__1; ++j) { i__2 = j + k * a_dim1; i__3 = j + k * w_dim1; z__3.r = d11.r * w[i__3].r - d11.i * w[i__3].i, z__3.i = d11.r * w[i__3].i + d11.i * w[i__3] .r; i__4 = j + (k + 1) * w_dim1; z__2.r = z__3.r - w[i__4].r, z__2.i = z__3.i - w[i__4] .i; z__1.r = d21.r * z__2.r - d21.i * z__2.i, z__1.i = d21.r * z__2.i + d21.i * z__2.r; a[i__2].r = z__1.r, a[i__2].i = z__1.i; i__2 = j + (k + 1) * a_dim1; i__3 = j + (k + 1) * w_dim1; z__3.r = d22.r * w[i__3].r - d22.i * w[i__3].i, z__3.i = d22.r * w[i__3].i + d22.i * w[i__3] .r; i__4 = j + k * w_dim1; z__2.r = z__3.r - w[i__4].r, z__2.i = z__3.i - w[i__4] .i; z__1.r = d21.r * z__2.r - d21.i * z__2.i, z__1.i = d21.r * z__2.i + d21.i * z__2.r; a[i__2].r = z__1.r, a[i__2].i = z__1.i; /* L80: */ } } i__1 = k + k * a_dim1; i__2 = k + k * w_dim1; a[i__1].r = w[i__2].r, a[i__1].i = w[i__2].i; i__1 = k + 1 + k * a_dim1; i__2 = k + 1 + k * w_dim1; a[i__1].r = w[i__2].r, a[i__1].i = w[i__2].i; i__1 = k + 1 + (k + 1) * a_dim1; i__2 = k + 1 + (k + 1) * w_dim1; a[i__1].r = w[i__2].r, a[i__1].i = w[i__2].i; } } if (kstep == 1) { ipiv[k] = kp; } else { ipiv[k] = -kp; ipiv[k + 1] = -kp; } k += kstep; goto L70; L90: j = k - 1; L120: jj = j; jp = ipiv[j]; if (jp < 0) { jp = -jp; --j; } --j; if (jp != jj && j >= 1) { zswap_(&j, &a[jp + a_dim1], lda, &a[jj + a_dim1], lda); } if (j > 1) { goto L120; } *kb = k - 1; } return; }
xianyi/OpenBLAS
relapack/src/zsytrf_rec2.c
C
bsd-3-clause
13,490
/*============================================================================* * * * This file is part of the Zoto Software suite. * * * * Copyright (C) 2004 Zoto, Inc. 123 South Hudson, OKC, OK 73102 * * * * Original algorithms taken from RFC 1321 * * Copyright (C) 1990-2, RSA Data Security, Inc. * * * *============================================================================*/ #include <Python.h> #include "ZTypes.h" #include "ZGlobals.h" extern void initialize_zsp_header(PyObject *m); extern void initialize_zsp_auth(PyObject *m); extern void initialize_zsp_auth_resp(PyObject *m); extern void initialize_zsp_version(PyObject *m); extern void initialize_zsp_version_resp(PyObject *m); extern void initialize_zsp_flag(PyObject *m); extern void initialize_zsp_flag_resp(PyObject *m); extern void initialize_zsp_file(PyObject *m); extern void initialize_zsp_file_resp(PyObject *m); extern void initialize_zsp_done(PyObject *m); extern void initialize_zsp_done_resp(PyObject *m); extern void initialize_zsp_error(PyObject *m); #ifndef PyMODINIT_FUNC #define PyMODINIT_FUNC void #endif static PyMethodDef module_methods[] = { {NULL} /* Sentinel */ }; PyMODINIT_FUNC initzsp_packets(void) { PyObject *m; m = Py_InitModule3("zsp_packets", module_methods, "Authorization packet."); if (m == NULL) return; PyModule_AddIntConstant(m, "ZSP_NONE", ZSP_NONE); PyModule_AddIntConstant(m, "ZSP_QUIT", ZSP_QUIT); PyModule_AddIntConstant(m, "ZSP_AUTH", ZSP_AUTH); PyModule_AddIntConstant(m, "ZSP_VERSION", ZSP_VERSION); PyModule_AddIntConstant(m, "ZSP_FLAG", ZSP_FLAG); PyModule_AddIntConstant(m, "ZSP_FILE", ZSP_FILE); PyModule_AddIntConstant(m, "ZSP_DONE", ZSP_DONE); PyModule_AddIntConstant(m, "ZSP_QUIT_RESP", ZSP_QUIT_RESP); PyModule_AddIntConstant(m, "ZSP_AUTH_RESP", ZSP_AUTH_RESP); PyModule_AddIntConstant(m, "ZSP_VERSION_RESP", ZSP_VERSION_RESP); PyModule_AddIntConstant(m, "ZSP_FLAG_RESP", ZSP_FLAG_RESP); PyModule_AddIntConstant(m, "ZSP_FILE_RESP", ZSP_FILE_RESP); PyModule_AddIntConstant(m, "ZSP_DONE_RESP", ZSP_DONE_RESP); PyModule_AddIntConstant(m, "ZSP_ERROR", ZSP_ERROR); PyModule_AddIntConstant(m, "ZSP_JPEG", ZSP_JPEG); PyModule_AddIntConstant(m, "ZSP_PNG", ZSP_PNG); PyModule_AddIntConstant(m, "ZSP_GIF", ZSP_GIF); PyModule_AddIntConstant(m, "ZSP_BMP", ZSP_BMP); PyModule_AddIntConstant(m, "ZSP_TIFF", ZSP_TIFF); PyModule_AddIntConstant(m, "ZSP_TARGA", ZSP_TARGA); // Return codes PyModule_AddIntConstant(m, "ZSP_AUTH_OK", ZSP_AUTH_OK); PyModule_AddIntConstant(m, "ZSP_AUTH_BAD", ZSP_AUTH_BAD); PyModule_AddIntConstant(m, "ZSP_VERS_GOOD", ZSP_VERS_GOOD); PyModule_AddIntConstant(m, "ZSP_VERS_OLD", ZSP_VERS_OLD); PyModule_AddIntConstant(m, "ZSP_VERS_BAD", ZSP_VERS_BAD); PyModule_AddIntConstant(m, "ZSP_FILE_OK", ZSP_FILE_OK); PyModule_AddIntConstant(m, "ZSP_FILE_NO_FLAG", ZSP_FILE_NO_FLAG); PyModule_AddIntConstant(m, "ZSP_FILE_BAD", ZSP_FILE_BAD); PyModule_AddIntConstant(m, "ZSP_DONE_OK", ZSP_DONE_OK); PyModule_AddIntConstant(m, "ZSP_DONE_BAD_SUM", ZSP_DONE_BAD_SUM); PyModule_AddIntConstant(m, "ZSP_DONE_BAD_SYNC", ZSP_DONE_BAD_SYNC); PyModule_AddIntConstant(m, "ZSP_DONE_BAD_SYNC2", ZSP_DONE_BAD_SYNC2); PyModule_AddIntConstant(m, "ZSP_DONE_CORRUPT", ZSP_DONE_CORRUPT); PyModule_AddIntConstant(m, "ZSP_DONE_BAD_WRITE", ZSP_DONE_BAD_WRITE); initialize_zsp_header(m); initialize_zsp_auth(m); initialize_zsp_auth_resp(m); initialize_zsp_version(m); initialize_zsp_version_resp(m); initialize_zsp_flag(m); initialize_zsp_flag_resp(m); initialize_zsp_file(m); initialize_zsp_file_resp(m); initialize_zsp_done(m); initialize_zsp_done_resp(m); initialize_zsp_error(m); }
kordless/zoto-server
zulu-2.0/python_module/zsp_packets.c
C
bsd-3-clause
3,830
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE90_LDAP_Injection__w32_wchar_t_connect_socket_31.c Label Definition File: CWE90_LDAP_Injection__w32.label.xml Template File: sources-sink-31.tmpl.c */ /* * @description * CWE: 90 LDAP Injection * BadSource: connect_socket Read data using a connect socket (client side) * GoodSource: Use a fixed string * Sinks: * BadSink : data concatenated into LDAP search, which could result in LDAP Injection * Flow Variant: 31 Data flow using a copy of data within the same function * * */ #include "std_testcase.h" #ifdef _WIN32 #include <winsock2.h> #include <windows.h> #include <direct.h> #pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */ #define CLOSE_SOCKET closesocket #else /* NOT _WIN32 */ #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #define INVALID_SOCKET -1 #define SOCKET_ERROR -1 #define CLOSE_SOCKET close #define SOCKET int #endif #define TCP_PORT 27015 #define IP_ADDRESS "127.0.0.1" #include <Winldap.h> #pragma comment(lib, "wldap32") #ifndef OMITBAD void CWE90_LDAP_Injection__w32_wchar_t_connect_socket_31_bad() { wchar_t * data; wchar_t dataBuffer[256] = L""; data = dataBuffer; { #ifdef _WIN32 WSADATA wsaData; int wsaDataInit = 0; #endif int recvResult; struct sockaddr_in service; wchar_t *replace; SOCKET connectSocket = INVALID_SOCKET; size_t dataLen = wcslen(data); do { #ifdef _WIN32 if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR) { break; } wsaDataInit = 1; #endif /* POTENTIAL FLAW: Read data using a connect socket */ connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (connectSocket == INVALID_SOCKET) { break; } memset(&service, 0, sizeof(service)); service.sin_family = AF_INET; service.sin_addr.s_addr = inet_addr(IP_ADDRESS); service.sin_port = htons(TCP_PORT); if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR) { break; } /* Abort on error or the connection was closed, make sure to recv one * less char than is in the recv_buf in order to append a terminator */ /* Abort on error or the connection was closed */ recvResult = recv(connectSocket, (char *)(data + dataLen), sizeof(wchar_t) * (256 - dataLen - 1), 0); if (recvResult == SOCKET_ERROR || recvResult == 0) { break; } /* Append null terminator */ data[dataLen + recvResult / sizeof(wchar_t)] = L'\0'; /* Eliminate CRLF */ replace = wcschr(data, L'\r'); if (replace) { *replace = L'\0'; } replace = wcschr(data, L'\n'); if (replace) { *replace = L'\0'; } } while (0); if (connectSocket != INVALID_SOCKET) { CLOSE_SOCKET(connectSocket); } #ifdef _WIN32 if (wsaDataInit) { WSACleanup(); } #endif } { wchar_t * dataCopy = data; wchar_t * data = dataCopy; { LDAP* pLdapConnection = NULL; ULONG connectSuccess = 0L; ULONG searchSuccess = 0L; LDAPMessage *pMessage = NULL; wchar_t filter[256]; /* POTENTIAL FLAW: data concatenated into LDAP search, which could result in LDAP Injection*/ _snwprintf(filter, 256-1, L"(cn=%s)", data); pLdapConnection = ldap_initW(L"localhost", LDAP_PORT); if (pLdapConnection == NULL) { printLine("Initialization failed"); exit(1); } connectSuccess = ldap_connect(pLdapConnection, NULL); if (connectSuccess != LDAP_SUCCESS) { printLine("Connection failed"); exit(1); } searchSuccess = ldap_search_ext_sW( pLdapConnection, L"base", LDAP_SCOPE_SUBTREE, filter, NULL, 0, NULL, NULL, LDAP_NO_LIMIT, LDAP_NO_LIMIT, &pMessage); if (searchSuccess != LDAP_SUCCESS) { printLine("Search failed"); if (pMessage != NULL) { ldap_msgfree(pMessage); } exit(1); } /* Typically you would do something with the search results, but this is a test case and we can ignore them */ /* Free the results to avoid incidentals */ if (pMessage != NULL) { ldap_msgfree(pMessage); } /* Close the connection */ ldap_unbind(pLdapConnection); } } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B() uses the GoodSource with the BadSink */ static void goodG2B() { wchar_t * data; wchar_t dataBuffer[256] = L""; data = dataBuffer; /* FIX: Use a fixed file name */ wcscat(data, L"Doe, XXXXX"); { wchar_t * dataCopy = data; wchar_t * data = dataCopy; { LDAP* pLdapConnection = NULL; ULONG connectSuccess = 0L; ULONG searchSuccess = 0L; LDAPMessage *pMessage = NULL; wchar_t filter[256]; /* POTENTIAL FLAW: data concatenated into LDAP search, which could result in LDAP Injection*/ _snwprintf(filter, 256-1, L"(cn=%s)", data); pLdapConnection = ldap_initW(L"localhost", LDAP_PORT); if (pLdapConnection == NULL) { printLine("Initialization failed"); exit(1); } connectSuccess = ldap_connect(pLdapConnection, NULL); if (connectSuccess != LDAP_SUCCESS) { printLine("Connection failed"); exit(1); } searchSuccess = ldap_search_ext_sW( pLdapConnection, L"base", LDAP_SCOPE_SUBTREE, filter, NULL, 0, NULL, NULL, LDAP_NO_LIMIT, LDAP_NO_LIMIT, &pMessage); if (searchSuccess != LDAP_SUCCESS) { printLine("Search failed"); if (pMessage != NULL) { ldap_msgfree(pMessage); } exit(1); } /* Typically you would do something with the search results, but this is a test case and we can ignore them */ /* Free the results to avoid incidentals */ if (pMessage != NULL) { ldap_msgfree(pMessage); } /* Close the connection */ ldap_unbind(pLdapConnection); } } } void CWE90_LDAP_Injection__w32_wchar_t_connect_socket_31_good() { goodG2B(); } #endif /* OMITGOOD */ /* Below is the main(). It is only used when building this testcase on * its own for testing or for building a binary to use in testing binary * analysis tools. It is not used when compiling all the testcases as one * application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); CWE90_LDAP_Injection__w32_wchar_t_connect_socket_31_good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); CWE90_LDAP_Injection__w32_wchar_t_connect_socket_31_bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
JianpingZeng/xcc
xcc/test/juliet/testcases/CWE90_LDAP_Injection/CWE90_LDAP_Injection__w32_wchar_t_connect_socket_31.c
C
bsd-3-clause
8,856
/* Copyright 2021 The Chromium OS Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ /* MT SCP RV32i configuration */ #include "cache.h" #include "csr.h" #include "hooks.h" #include "registers.h" #define SCP_SRAM_END (CONFIG_IPC_SHARED_OBJ_ADDR & (~(0x400 - 1))) struct mpu_entry mpu_entries[NR_MPU_ENTRIES] = { /* SRAM (for most code, data) */ {0, SCP_SRAM_END, MPU_ATTR_C | MPU_ATTR_W | MPU_ATTR_R}, /* SRAM (for IPI shared buffer) */ {SCP_SRAM_END, SCP_FW_END, MPU_ATTR_W | MPU_ATTR_R}, /* For AP domain */ #ifdef CHIP_VARIANT_MT8195 {0x60000000, 0x70000000, MPU_ATTR_W | MPU_ATTR_R | MPU_ATTR_P}, #else {0x60000000, 0x70000000, MPU_ATTR_W | MPU_ATTR_R}, #endif /* For SCP sys */ {0x70000000, 0x80000000, MPU_ATTR_W | MPU_ATTR_R}, #ifdef CHIP_VARIANT_MT8195 {0x10000000, 0x11400000, MPU_ATTR_C | MPU_ATTR_W | MPU_ATTR_R}, {CONFIG_PANIC_DRAM_BASE, CONFIG_PANIC_DRAM_BASE + CONFIG_PANIC_DRAM_SIZE, MPU_ATTR_W | MPU_ATTR_R}, #else {0x10000000, 0x11400000, MPU_ATTR_W | MPU_ATTR_R}, #endif }; #include "gpio_list.h" #ifdef CONFIG_PANIC_CONSOLE_OUTPUT static void report_previous_panic(void) { struct panic_data * panic = panic_get_data(); if (panic == NULL && SCP_CORE0_MON_PC_LATCH == 0) return; ccprintf("[Previous Panic]\n"); if (panic) { panic_data_ccprint(panic); } else { ccprintf("No panic data\n"); } ccprintf("Latch PC:%x LR:%x SP:%x\n", SCP_CORE0_MON_PC_LATCH, SCP_CORE0_MON_LR_LATCH, SCP_CORE0_MON_SP_LATCH); } DECLARE_HOOK(HOOK_INIT, report_previous_panic, HOOK_PRIO_DEFAULT); #endif
coreboot/chrome-ec
baseboard/mtscp-rv32i/baseboard.c
C
bsd-3-clause
1,621
/* this ALWAYS GENERATED file contains the IIDs and CLSIDs */ /* link this file in with the server and any clients */ /* File created by MIDL compiler version 7.00.0499 */ /* at Mon Dec 01 09:02:10 2008 */ /* Compiler settings for e:/builds/tinderbox/XR-Trunk/WINNT_5.2_Depend/mozilla/other-licenses/ia2/Accessible2.idl: Oicf, W1, Zp8, env=Win32 (32b run) protocol : dce , ms_ext, app_config, c_ext error checks: allocation ref bounds_check enum stub_data VC __declspec() decoration level: __declspec(uuid()), __declspec(selectany), __declspec(novtable) DECLSPEC_UUID(), MIDL_INTERFACE() */ //@@MIDL_FILE_HEADING( ) #pragma warning( disable: 4049 ) /* more than 64k source lines */ #ifdef __cplusplus extern "C"{ #endif #include <rpc.h> #include <rpcndr.h> #ifdef _MIDL_USE_GUIDDEF_ #ifndef INITGUID #define INITGUID #include <guiddef.h> #undef INITGUID #else #include <guiddef.h> #endif #define MIDL_DEFINE_GUID(type,name,l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8) \ DEFINE_GUID(name,l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8) #else // !_MIDL_USE_GUIDDEF_ #ifndef __IID_DEFINED__ #define __IID_DEFINED__ typedef struct _IID { unsigned long x; unsigned short s1; unsigned short s2; unsigned char c[8]; } IID; #endif // __IID_DEFINED__ #ifndef CLSID_DEFINED #define CLSID_DEFINED typedef IID CLSID; #endif // CLSID_DEFINED #define MIDL_DEFINE_GUID(type,name,l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8) \ const type name = {l,w1,w2,{b1,b2,b3,b4,b5,b6,b7,b8}} #endif !_MIDL_USE_GUIDDEF_ MIDL_DEFINE_GUID(IID, IID_IAccessible2,0xE89F726E,0xC4F4,0x4c19,0xBB,0x19,0xB6,0x47,0xD7,0xFA,0x84,0x78); #undef MIDL_DEFINE_GUID #ifdef __cplusplus } #endif
leighpauls/k2cro4
third_party/xulrunner-sdk/win/include/accessibility/Accessible2_i.c
C
bsd-3-clause
1,711
/* * @description Expression is always true via if (unsigned int >= 0) * * */ #include "std_testcase.h" #ifndef OMITBAD void CWE571_Expression_Always_True__unsigned_int_01_bad() { /* Ensure (0 <= intBad < UINT_MAX) and that uIntBad is pseudo-random */ unsigned int uIntBad = (unsigned int)(rand() * 2); /* FLAW: This expression is always true */ if (uIntBad >= 0) { printLine("Always prints"); } } #endif /* OMITBAD */ #ifndef OMITGOOD static void good1() { int intGood = rand(); /* FIX: Possibly evaluate to true */ if (intGood > (RAND_MAX / 2)) { printLine("Sometimes prints"); } } void CWE571_Expression_Always_True__unsigned_int_01_good() { good1(); } #endif /* OMITGOOD */ /* Below is the main(). It is only used when building this testcase on * its own for testing or for building a binary to use in testing binary * analysis tools. It is not used when compiling all the testcases as one * application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); CWE571_Expression_Always_True__unsigned_int_01_good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); CWE571_Expression_Always_True__unsigned_int_01_bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
JianpingZeng/xcc
xcc/test/juliet/testcases/CWE571_Expression_Always_True/CWE571_Expression_Always_True__unsigned_int_01.c
C
bsd-3-clause
1,609
#include "Stencil1D.h" int cncMain(int argc, char *argv[]) { CNC_REQUIRE(argc == 4, "Usage: %s NUM_TILES TILE_SIZE NUM_TIMESTEPS\n", argv[0]); // Create a new graph context Stencil1DCtx *context = Stencil1D_create(); // initialize graph context parameters context->numTiles = atoi(argv[1]); context->tileSize = atoi(argv[2]); context->lastTimestep = atoi(argv[3]); // Launch the graph for execution Stencil1D_launch(NULL, context); // Exit when the graph execution completes CNC_SHUTDOWN_ON_FINISH(context); return 0; }
habanero-rice/cnc-framework
examples/tutorial/4-improved.app/Main.c
C
bsd-3-clause
575
/* * Copyright (c) 2013 The WebM 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 in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "vp9/common/vp9_convolve.h" #include <assert.h> #include "./vpx_config.h" #include "./vp9_rtcd.h" #include "vp9/common/vp9_common.h" #include "vpx/vpx_integer.h" #include "vpx_ports/mem.h" #define VP9_FILTER_WEIGHT 128 #define VP9_FILTER_SHIFT 7 /* Assume a bank of 16 filters to choose from. There are two implementations * for filter wrapping behavior, since we want to be able to pick which filter * to start with. We could either: * * 1) make filter_ a pointer to the base of the filter array, and then add an * additional offset parameter, to choose the starting filter. * 2) use a pointer to 2 periods worth of filters, so that even if the original * phase offset is at 15/16, we'll have valid data to read. The filter * tables become [32][8], and the second half is duplicated. * 3) fix the alignment of the filter tables, so that we know the 0/16 is * always 256 byte aligned. * * Implementations 2 and 3 are likely preferable, as they avoid an extra 2 * parameters, and switching between them is trivial, with the * ALIGN_FILTERS_256 macro, below. */ #define ALIGN_FILTERS_256 1 static void convolve_horiz_c(const uint8_t *src, int src_stride, uint8_t *dst, int dst_stride, const int16_t *filter_x0, int x_step_q4, const int16_t *filter_y, int y_step_q4, int w, int h, int taps) { int x, y, k, sum; const int16_t *filter_x_base = filter_x0; #if ALIGN_FILTERS_256 filter_x_base = (const int16_t *)(((intptr_t)filter_x0) & ~(intptr_t)0xff); #endif /* Adjust base pointer address for this source line */ src -= taps / 2 - 1; for (y = 0; y < h; ++y) { /* Pointer to filter to use */ const int16_t *filter_x = filter_x0; /* Initial phase offset */ int x0_q4 = (filter_x - filter_x_base) / taps; int x_q4 = x0_q4; for (x = 0; x < w; ++x) { /* Per-pixel src offset */ int src_x = (x_q4 - x0_q4) >> 4; for (sum = 0, k = 0; k < taps; ++k) { sum += src[src_x + k] * filter_x[k]; } sum += (VP9_FILTER_WEIGHT >> 1); dst[x] = clip_pixel(sum >> VP9_FILTER_SHIFT); /* Adjust source and filter to use for the next pixel */ x_q4 += x_step_q4; filter_x = filter_x_base + (x_q4 & 0xf) * taps; } src += src_stride; dst += dst_stride; } } static void convolve_avg_horiz_c(const uint8_t *src, int src_stride, uint8_t *dst, int dst_stride, const int16_t *filter_x0, int x_step_q4, const int16_t *filter_y, int y_step_q4, int w, int h, int taps) { int x, y, k, sum; const int16_t *filter_x_base = filter_x0; #if ALIGN_FILTERS_256 filter_x_base = (const int16_t *)(((intptr_t)filter_x0) & ~(intptr_t)0xff); #endif /* Adjust base pointer address for this source line */ src -= taps / 2 - 1; for (y = 0; y < h; ++y) { /* Pointer to filter to use */ const int16_t *filter_x = filter_x0; /* Initial phase offset */ int x0_q4 = (filter_x - filter_x_base) / taps; int x_q4 = x0_q4; for (x = 0; x < w; ++x) { /* Per-pixel src offset */ int src_x = (x_q4 - x0_q4) >> 4; for (sum = 0, k = 0; k < taps; ++k) { sum += src[src_x + k] * filter_x[k]; } sum += (VP9_FILTER_WEIGHT >> 1); dst[x] = (dst[x] + clip_pixel(sum >> VP9_FILTER_SHIFT) + 1) >> 1; /* Adjust source and filter to use for the next pixel */ x_q4 += x_step_q4; filter_x = filter_x_base + (x_q4 & 0xf) * taps; } src += src_stride; dst += dst_stride; } } static void convolve_vert_c(const uint8_t *src, int src_stride, uint8_t *dst, int dst_stride, const int16_t *filter_x, int x_step_q4, const int16_t *filter_y0, int y_step_q4, int w, int h, int taps) { int x, y, k, sum; const int16_t *filter_y_base = filter_y0; #if ALIGN_FILTERS_256 filter_y_base = (const int16_t *)(((intptr_t)filter_y0) & ~(intptr_t)0xff); #endif /* Adjust base pointer address for this source column */ src -= src_stride * (taps / 2 - 1); for (x = 0; x < w; ++x) { /* Pointer to filter to use */ const int16_t *filter_y = filter_y0; /* Initial phase offset */ int y0_q4 = (filter_y - filter_y_base) / taps; int y_q4 = y0_q4; for (y = 0; y < h; ++y) { /* Per-pixel src offset */ int src_y = (y_q4 - y0_q4) >> 4; for (sum = 0, k = 0; k < taps; ++k) { sum += src[(src_y + k) * src_stride] * filter_y[k]; } sum += (VP9_FILTER_WEIGHT >> 1); dst[y * dst_stride] = clip_pixel(sum >> VP9_FILTER_SHIFT); /* Adjust source and filter to use for the next pixel */ y_q4 += y_step_q4; filter_y = filter_y_base + (y_q4 & 0xf) * taps; } ++src; ++dst; } } static void convolve_avg_vert_c(const uint8_t *src, int src_stride, uint8_t *dst, int dst_stride, const int16_t *filter_x, int x_step_q4, const int16_t *filter_y0, int y_step_q4, int w, int h, int taps) { int x, y, k, sum; const int16_t *filter_y_base = filter_y0; #if ALIGN_FILTERS_256 filter_y_base = (const int16_t *)(((intptr_t)filter_y0) & ~(intptr_t)0xff); #endif /* Adjust base pointer address for this source column */ src -= src_stride * (taps / 2 - 1); for (x = 0; x < w; ++x) { /* Pointer to filter to use */ const int16_t *filter_y = filter_y0; /* Initial phase offset */ int y0_q4 = (filter_y - filter_y_base) / taps; int y_q4 = y0_q4; for (y = 0; y < h; ++y) { /* Per-pixel src offset */ int src_y = (y_q4 - y0_q4) >> 4; for (sum = 0, k = 0; k < taps; ++k) { sum += src[(src_y + k) * src_stride] * filter_y[k]; } sum += (VP9_FILTER_WEIGHT >> 1); dst[y * dst_stride] = (dst[y * dst_stride] + clip_pixel(sum >> VP9_FILTER_SHIFT) + 1) >> 1; /* Adjust source and filter to use for the next pixel */ y_q4 += y_step_q4; filter_y = filter_y_base + (y_q4 & 0xf) * taps; } ++src; ++dst; } } static void convolve_c(const uint8_t *src, int src_stride, uint8_t *dst, int dst_stride, const int16_t *filter_x, int x_step_q4, const int16_t *filter_y, int y_step_q4, int w, int h, int taps) { /* Fixed size intermediate buffer places limits on parameters. * Maximum intermediate_height is 135, for y_step_q4 == 32, * h == 64, taps == 8. */ uint8_t temp[64 * 135]; int intermediate_height = ((h * y_step_q4) >> 4) + taps - 1; assert(w <= 64); assert(h <= 64); assert(taps <= 8); assert(y_step_q4 <= 32); if (intermediate_height < h) intermediate_height = h; convolve_horiz_c(src - src_stride * (taps / 2 - 1), src_stride, temp, 64, filter_x, x_step_q4, filter_y, y_step_q4, w, intermediate_height, taps); convolve_vert_c(temp + 64 * (taps / 2 - 1), 64, dst, dst_stride, filter_x, x_step_q4, filter_y, y_step_q4, w, h, taps); } static void convolve_avg_c(const uint8_t *src, int src_stride, uint8_t *dst, int dst_stride, const int16_t *filter_x, int x_step_q4, const int16_t *filter_y, int y_step_q4, int w, int h, int taps) { /* Fixed size intermediate buffer places limits on parameters. * Maximum intermediate_height is 135, for y_step_q4 == 32, * h == 64, taps == 8. */ uint8_t temp[64 * 135]; int intermediate_height = ((h * y_step_q4) >> 4) + taps - 1; assert(w <= 64); assert(h <= 64); assert(taps <= 8); assert(y_step_q4 <= 32); if (intermediate_height < h) intermediate_height = h; convolve_horiz_c(src - src_stride * (taps / 2 - 1), src_stride, temp, 64, filter_x, x_step_q4, filter_y, y_step_q4, w, intermediate_height, taps); convolve_avg_vert_c(temp + 64 * (taps / 2 - 1), 64, dst, dst_stride, filter_x, x_step_q4, filter_y, y_step_q4, w, h, taps); } void vp9_convolve8_horiz_c(const uint8_t *src, int src_stride, uint8_t *dst, int dst_stride, const int16_t *filter_x, int x_step_q4, const int16_t *filter_y, int y_step_q4, int w, int h) { convolve_horiz_c(src, src_stride, dst, dst_stride, filter_x, x_step_q4, filter_y, y_step_q4, w, h, 8); } void vp9_convolve8_avg_horiz_c(const uint8_t *src, int src_stride, uint8_t *dst, int dst_stride, const int16_t *filter_x, int x_step_q4, const int16_t *filter_y, int y_step_q4, int w, int h) { convolve_avg_horiz_c(src, src_stride, dst, dst_stride, filter_x, x_step_q4, filter_y, y_step_q4, w, h, 8); } void vp9_convolve8_vert_c(const uint8_t *src, int src_stride, uint8_t *dst, int dst_stride, const int16_t *filter_x, int x_step_q4, const int16_t *filter_y, int y_step_q4, int w, int h) { convolve_vert_c(src, src_stride, dst, dst_stride, filter_x, x_step_q4, filter_y, y_step_q4, w, h, 8); } void vp9_convolve8_avg_vert_c(const uint8_t *src, int src_stride, uint8_t *dst, int dst_stride, const int16_t *filter_x, int x_step_q4, const int16_t *filter_y, int y_step_q4, int w, int h) { convolve_avg_vert_c(src, src_stride, dst, dst_stride, filter_x, x_step_q4, filter_y, y_step_q4, w, h, 8); } void vp9_convolve8_c(const uint8_t *src, int src_stride, uint8_t *dst, int dst_stride, const int16_t *filter_x, int x_step_q4, const int16_t *filter_y, int y_step_q4, int w, int h) { convolve_c(src, src_stride, dst, dst_stride, filter_x, x_step_q4, filter_y, y_step_q4, w, h, 8); } void vp9_convolve8_avg_c(const uint8_t *src, int src_stride, uint8_t *dst, int dst_stride, const int16_t *filter_x, int x_step_q4, const int16_t *filter_y, int y_step_q4, int w, int h) { /* Fixed size intermediate buffer places limits on parameters. */ DECLARE_ALIGNED_ARRAY(16, uint8_t, temp, 64 * 64); assert(w <= 64); assert(h <= 64); vp9_convolve8(src, src_stride, temp, 64, filter_x, x_step_q4, filter_y, y_step_q4, w, h); vp9_convolve_avg(temp, 64, dst, dst_stride, NULL, 0, /* These unused parameter should be removed! */ NULL, 0, /* These unused parameter should be removed! */ w, h); } void vp9_convolve_copy(const uint8_t *src, int src_stride, uint8_t *dst, int dst_stride, const int16_t *filter_x, int filter_x_stride, const int16_t *filter_y, int filter_y_stride, int w, int h) { if (w == 16 && h == 16) { vp9_copy_mem16x16(src, src_stride, dst, dst_stride); } else if (w == 8 && h == 8) { vp9_copy_mem8x8(src, src_stride, dst, dst_stride); } else if (w == 8 && h == 4) { vp9_copy_mem8x4(src, src_stride, dst, dst_stride); } else { int r; for (r = h; r > 0; --r) { memcpy(dst, src, w); src += src_stride; dst += dst_stride; } } } void vp9_convolve_avg(const uint8_t *src, int src_stride, uint8_t *dst, int dst_stride, const int16_t *filter_x, int filter_x_stride, const int16_t *filter_y, int filter_y_stride, int w, int h) { int x, y; for (y = 0; y < h; ++y) { for (x = 0; x < w; ++x) { dst[x] = (dst[x] + src[x] + 1) >> 1; } src += src_stride; dst += dst_stride; } }
windyuuy/opera
chromium/src/third_party/libvpx/source/libvpx/vp9/common/vp9_convolve.c
C
bsd-3-clause
13,122
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE457_Use_of_Uninitialized_Variable__char_pointer_64b.c Label Definition File: CWE457_Use_of_Uninitialized_Variable.c.label.xml Template File: sources-sinks-64b.tmpl.c */ /* * @description * CWE: 457 Use of Uninitialized Variable * BadSource: no_init Don't initialize data * GoodSource: Initialize data * Sinks: use * GoodSink: Initialize then use data * BadSink : Use data * Flow Variant: 64 Data flow: void pointer to data passed from one function to another in different source files * * */ #include "std_testcase.h" #include <wchar.h> #ifndef OMITBAD void CWE457_Use_of_Uninitialized_Variable__char_pointer_64b_badSink(void * dataVoidPtr) { /* cast void pointer to a pointer of the appropriate type */ char * * dataPtr = (char * *)dataVoidPtr; /* dereference dataPtr into data */ char * data = (*dataPtr); /* POTENTIAL FLAW: Use data without initializing it */ printLine(data); } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ void CWE457_Use_of_Uninitialized_Variable__char_pointer_64b_goodG2BSink(void * dataVoidPtr) { /* cast void pointer to a pointer of the appropriate type */ char * * dataPtr = (char * *)dataVoidPtr; /* dereference dataPtr into data */ char * data = (*dataPtr); /* POTENTIAL FLAW: Use data without initializing it */ printLine(data); } /* goodB2G uses the BadSource with the GoodSink */ void CWE457_Use_of_Uninitialized_Variable__char_pointer_64b_goodB2GSink(void * dataVoidPtr) { /* cast void pointer to a pointer of the appropriate type */ char * * dataPtr = (char * *)dataVoidPtr; /* dereference dataPtr into data */ char * data = (*dataPtr); /* FIX: Ensure data is initialized before use */ data = "string"; printLine(data); } #endif /* OMITGOOD */
JianpingZeng/xcc
xcc/test/juliet/testcases/CWE457_Use_of_Uninitialized_Variable/s01/CWE457_Use_of_Uninitialized_Variable__char_pointer_64b.c
C
bsd-3-clause
1,932
/*********************************************************************** * Copyright (c) 2009, Secure Endpoints Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * **********************************************************************/ #include <config.h> #include <roken.h> #include <strsafe.h> #ifndef _WIN32 #error This implementation is Windows specific. #endif /** * wait_for_process_timed waits for a process to terminate or until a * specified timeout occurs. * * @param[in] pid Process id for the monitored process * @param[in] func Timeout callback function. When the wait times out, * the callback function is called. The possible return values * from the callback function are: * * - ((time_t) -2) Exit loop without killing child and return SE_E_EXECTIMEOUT. * - ((time_t) -1) Kill child with SIGTERM and wait for child to exit. * - 0 Don't timeout again * - n Seconds to next timeout * * @param[in] ptr Optional parameter for func() * * @param[in] timeout Seconds to first timeout. * * @retval SE_E_UNSPECIFIED Unspecified system error * @retval SE_E_FORKFAILED Fork failure (not applicable for _WIN32 targets) * @retval SE_E_WAITPIDFAILED waitpid errors * @retval SE_E_EXECTIMEOUT exec timeout * @retval 0 <= Return value from subprocess * @retval SE_E_NOTFOUND The program coudln't be found * @retval 128- The signal that killed the subprocess +128. */ ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL wait_for_process_timed(pid_t pid, time_t (*func)(void *), void *ptr, time_t timeout) { HANDLE hProcess; DWORD wrv = 0; DWORD dtimeout; int rv = 0; hProcess = OpenProcess(SYNCHRONIZE, FALSE, pid); if (hProcess == NULL) { return SE_E_WAITPIDFAILED; } dtimeout = (DWORD) ((timeout == 0)? INFINITE: timeout * 1000); do { wrv = WaitForSingleObject(hProcess, dtimeout); if (wrv == WAIT_OBJECT_0) { DWORD prv = 0; GetExitCodeProcess(hProcess, &prv); rv = (int) prv; break; } else if (wrv == WAIT_TIMEOUT) { if (func == NULL) continue; timeout = (*func)(ptr); if (timeout == (time_t)-1) { if (TerminateProcess(hProcess, 128 + 9)) { dtimeout = INFINITE; continue; } rv = SE_E_UNSPECIFIED; break; } else if (timeout == (time_t) -2) { rv = SE_E_EXECTIMEOUT; break; } else { dtimeout = (DWORD) ((timeout == 0)? INFINITE: timeout * 1000); continue; } } else { rv = SE_E_UNSPECIFIED; break; } } while(TRUE); CloseHandle(hProcess); return rv; } ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL wait_for_process(pid_t pid) { return wait_for_process_timed(pid, NULL, NULL, 0); } static char * collect_commandline(const char * fn, va_list * ap) { size_t len = 0; size_t alloc_len = 0; const char * s; char * cmd = NULL; for (s = fn; s; s = (char *) va_arg(*ap, char *)) { size_t cmp_len; int need_quote = FALSE; if (FAILED(StringCchLength(s, MAX_PATH, &cmp_len))) { if (cmd) free(cmd); return NULL; } if (cmp_len == 0) continue; if (strchr(s, ' ') && /* need to quote any component that has embedded spaces, but not if they are already quoted. */ s[0] != '"' && s[cmp_len - 1] != '"') { need_quote = TRUE; cmp_len += 2 * sizeof(char); } if (s != fn) cmp_len += 1 * sizeof(char); if (alloc_len < len + cmp_len + 1) { char * nc; alloc_len += ((len + cmp_len - alloc_len) / MAX_PATH + 1) * MAX_PATH; nc = (char *) realloc(cmd, alloc_len * sizeof(char)); if (nc == NULL) { if (cmd) free(cmd); return NULL; } } if (cmd == NULL) return NULL; if (s != fn) cmd[len++] = ' '; if (need_quote) { StringCchPrintf(cmd + len, alloc_len - len, "\"%s\"", s); } else { StringCchCopy(cmd + len, alloc_len - len, s); } len += cmp_len; } return cmd; } ROKEN_LIB_FUNCTION pid_t ROKEN_LIB_CALL pipe_execv(FILE **stdin_fd, FILE **stdout_fd, FILE **stderr_fd, const char *file, ...) { HANDLE hOut_r = NULL; HANDLE hOut_w = NULL; HANDLE hIn_r = NULL; HANDLE hIn_w = NULL; HANDLE hErr_r = NULL; HANDLE hErr_w = NULL; SECURITY_ATTRIBUTES sa; STARTUPINFO si; PROCESS_INFORMATION pi; char * commandline = NULL; pid_t rv = (pid_t) -1; { va_list ap; va_start(ap, file); commandline = collect_commandline(file, &ap); if (commandline == NULL) return rv; } ZeroMemory(&si, sizeof(si)); ZeroMemory(&pi, sizeof(pi)); ZeroMemory(&sa, sizeof(sa)); pi.hProcess = NULL; pi.hThread = NULL; sa.nLength = sizeof(sa); sa.bInheritHandle = TRUE; sa.lpSecurityDescriptor = NULL; if ((stdout_fd && !CreatePipe(&hOut_r, &hOut_w, &sa, 0 /* Use default */)) || (stdin_fd && !CreatePipe(&hIn_r, &hIn_w, &sa, 0)) || (stderr_fd && !CreatePipe(&hErr_r, &hErr_w, &sa, 0)) || (!stdout_fd && (hOut_w = CreateFile("CON", GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, &sa, OPEN_EXISTING, 0, NULL)) == INVALID_HANDLE_VALUE) || (!stdin_fd && (hIn_r = CreateFile("CON",GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE, &sa, OPEN_EXISTING, 0, NULL)) == INVALID_HANDLE_VALUE) || (!stderr_fd && (hErr_w = CreateFile("CON", GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, &sa, OPEN_EXISTING, 0, NULL)) == INVALID_HANDLE_VALUE)) goto _exit; /* We don't want the child processes inheriting these */ if (hOut_r) SetHandleInformation(hOut_r, HANDLE_FLAG_INHERIT, FALSE); if (hIn_w) SetHandleInformation(hIn_w, HANDLE_FLAG_INHERIT, FALSE); if (hErr_r) SetHandleInformation(hErr_r, HANDLE_FLAG_INHERIT, FALSE); si.cb = sizeof(si); si.lpReserved = NULL; si.lpDesktop = NULL; si.lpTitle = NULL; si.dwFlags = STARTF_USESTDHANDLES; si.hStdInput = hIn_r; si.hStdOutput = hOut_w; si.hStdError = hErr_w; if (!CreateProcess(file, commandline, NULL, NULL, TRUE, /* bInheritHandles */ CREATE_NO_WINDOW, /* dwCreationFlags */ NULL, /* lpEnvironment */ NULL, /* lpCurrentDirectory */ &si, &pi)) { rv = (pid_t) (GetLastError() == ERROR_FILE_NOT_FOUND)? 127 : -1; goto _exit; } if (stdin_fd) { *stdin_fd = _fdopen(_open_osfhandle((intptr_t) hIn_w, 0), "wb"); if (*stdin_fd) hIn_w = NULL; } if (stdout_fd) { *stdout_fd = _fdopen(_open_osfhandle((intptr_t) hOut_r, _O_RDONLY), "rb"); if (*stdout_fd) hOut_r = NULL; } if (stderr_fd) { *stderr_fd = _fdopen(_open_osfhandle((intptr_t) hErr_r, _O_RDONLY), "rb"); if (*stderr_fd) hErr_r = NULL; } rv = (pid_t) pi.dwProcessId; _exit: if (pi.hProcess) CloseHandle(pi.hProcess); if (pi.hThread) CloseHandle(pi.hThread); if (hIn_r) CloseHandle(hIn_r); if (hIn_w) CloseHandle(hIn_w); if (hOut_r) CloseHandle(hOut_r); if (hOut_w) CloseHandle(hOut_w); if (hErr_r) CloseHandle(hErr_r); if (hErr_w) CloseHandle(hErr_w); return rv; } ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL simple_execvp_timed(const char *file, char *const args[], time_t (*func)(void *), void *ptr, time_t timeout) { intptr_t hp; int rv; hp = spawnvp(_P_NOWAIT, file, args); if (hp == -1) return (errno == ENOENT)? 127: 126; else if (hp == 0) return 0; rv = wait_for_process_timed(GetProcessId((HANDLE) hp), func, ptr, timeout); CloseHandle((HANDLE) hp); return rv; } ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL simple_execvp(const char *file, char *const args[]) { return simple_execvp_timed(file, args, NULL, NULL, 0); } ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL simple_execve_timed(const char *file, char *const args[], char *const envp[], time_t (*func)(void *), void *ptr, time_t timeout) { intptr_t hp; int rv; hp = spawnve(_P_NOWAIT, file, args, envp); if (hp == -1) return (errno == ENOENT)? 127: 126; else if (hp == 0) return 0; rv = wait_for_process_timed(GetProcessId((HANDLE) hp), func, ptr, timeout); CloseHandle((HANDLE) hp); return rv; } ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL simple_execve(const char *file, char *const args[], char *const envp[]) { return simple_execve_timed(file, args, envp, NULL, NULL, 0); } ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL simple_execlp(const char *file, ...) { va_list ap; char **argv; int ret; va_start(ap, file); argv = vstrcollect(&ap); va_end(ap); if(argv == NULL) return SE_E_UNSPECIFIED; ret = simple_execvp(file, argv); free(argv); return ret; } ROKEN_LIB_FUNCTION int ROKEN_LIB_CALL simple_execle(const char *file, ... /* ,char *const envp[] */) { va_list ap; char **argv; char *const* envp; int ret; va_start(ap, file); argv = vstrcollect(&ap); envp = va_arg(ap, char **); va_end(ap); if(argv == NULL) return SE_E_UNSPECIFIED; ret = simple_execve(file, argv, envp); free(argv); return ret; }
pexip/os-heimdal
lib/roken/simple_exec_w32.c
C
bsd-3-clause
10,338
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_memcpy_22a.c Label Definition File: CWE122_Heap_Based_Buffer_Overflow__c_CWE805.label.xml Template File: sources-sink-22a.tmpl.c */ /* * @description * CWE: 122 Heap Based Buffer Overflow * BadSource: Allocate using malloc() and set data pointer to a small buffer * GoodSource: Allocate using malloc() and set data pointer to a large buffer * Sink: memcpy * BadSink : Copy twoIntsStruct array to data using memcpy * Flow Variant: 22 Control flow: Flow controlled by value of a global variable. Sink functions are in a separate file from sources. * * */ #include "std_testcase.h" #ifndef OMITBAD /* The global variable below is used to drive control flow in the source function */ int CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_memcpy_22_badGlobal = 0; twoIntsStruct * CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_memcpy_22_badSource(twoIntsStruct * data); void CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_memcpy_22_bad() { twoIntsStruct * data; data = NULL; CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_memcpy_22_badGlobal = 1; /* true */ data = CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_memcpy_22_badSource(data); { twoIntsStruct source[100]; { size_t i; /* Initialize array */ for (i = 0; i < 100; i++) { source[i].intOne = 0; source[i].intTwo = 0; } } /* POTENTIAL FLAW: Possible buffer overflow if data < 100 */ memcpy(data, source, 100*sizeof(twoIntsStruct)); printStructLine(&data[0]); free(data); } } #endif /* OMITBAD */ #ifndef OMITGOOD /* The global variables below are used to drive control flow in the source functions. */ int CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_memcpy_22_goodG2B1Global = 0; int CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_memcpy_22_goodG2B2Global = 0; /* goodG2B1() - use goodsource and badsink by setting the static variable to false instead of true */ twoIntsStruct * CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_memcpy_22_goodG2B1Source(twoIntsStruct * data); static void goodG2B1() { twoIntsStruct * data; data = NULL; CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_memcpy_22_goodG2B1Global = 0; /* false */ data = CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_memcpy_22_goodG2B1Source(data); { twoIntsStruct source[100]; { size_t i; /* Initialize array */ for (i = 0; i < 100; i++) { source[i].intOne = 0; source[i].intTwo = 0; } } /* POTENTIAL FLAW: Possible buffer overflow if data < 100 */ memcpy(data, source, 100*sizeof(twoIntsStruct)); printStructLine(&data[0]); free(data); } } /* goodG2B2() - use goodsource and badsink by reversing the blocks in the if in the source function */ twoIntsStruct * CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_memcpy_22_goodG2B2Source(twoIntsStruct * data); static void goodG2B2() { twoIntsStruct * data; data = NULL; CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_memcpy_22_goodG2B2Global = 1; /* true */ data = CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_memcpy_22_goodG2B2Source(data); { twoIntsStruct source[100]; { size_t i; /* Initialize array */ for (i = 0; i < 100; i++) { source[i].intOne = 0; source[i].intTwo = 0; } } /* POTENTIAL FLAW: Possible buffer overflow if data < 100 */ memcpy(data, source, 100*sizeof(twoIntsStruct)); printStructLine(&data[0]); free(data); } } void CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_memcpy_22_good() { goodG2B1(); goodG2B2(); } #endif /* OMITGOOD */ /* Below is the main(). It is only used when building this testcase on * its own for testing or for building a binary to use in testing binary * analysis tools. It is not used when compiling all the testcases as one * application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_memcpy_22_good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_memcpy_22_bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
JianpingZeng/xcc
xcc/test/juliet/testcases/CWE122_Heap_Based_Buffer_Overflow/s08/CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_memcpy_22a.c
C
bsd-3-clause
4,955
/* * * Copyright 2015, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include "src/core/lib/surface/completion_queue.h" #include <stdio.h> #include <string.h> #include <grpc/support/alloc.h> #include <grpc/support/atm.h> #include <grpc/support/log.h> #include <grpc/support/time.h> #include "src/core/lib/iomgr/pollset.h" #include "src/core/lib/iomgr/timer.h" #include "src/core/lib/profiling/timers.h" #include "src/core/lib/support/string.h" #include "src/core/lib/surface/api_trace.h" #include "src/core/lib/surface/call.h" #include "src/core/lib/surface/event_string.h" #include "src/core/lib/surface/surface_trace.h" typedef struct { grpc_pollset_worker **worker; void *tag; } plucker; /* Completion queue structure */ struct grpc_completion_queue { /** owned by pollset */ gpr_mu *mu; /** completed events */ grpc_cq_completion completed_head; grpc_cq_completion *completed_tail; /** Number of pending events (+1 if we're not shutdown) */ gpr_refcount pending_events; /** Once owning_refs drops to zero, we will destroy the cq */ gpr_refcount owning_refs; /** 0 initially, 1 once we've begun shutting down */ int shutdown; int shutdown_called; int is_server_cq; int num_pluckers; plucker pluckers[GRPC_MAX_COMPLETION_QUEUE_PLUCKERS]; grpc_closure pollset_shutdown_done; #ifndef NDEBUG void **outstanding_tags; size_t outstanding_tag_count; size_t outstanding_tag_capacity; #endif grpc_completion_queue *next_free; }; #define POLLSET_FROM_CQ(cq) ((grpc_pollset *)(cq + 1)) static gpr_mu g_freelist_mu; static grpc_completion_queue *g_freelist; static void on_pollset_shutdown_done(grpc_exec_ctx *exec_ctx, void *cc, bool success); void grpc_cq_global_init(void) { gpr_mu_init(&g_freelist_mu); } void grpc_cq_global_shutdown(void) { gpr_mu_destroy(&g_freelist_mu); while (g_freelist) { grpc_completion_queue *next = g_freelist->next_free; grpc_pollset_destroy(POLLSET_FROM_CQ(g_freelist)); #ifndef NDEBUG gpr_free(g_freelist->outstanding_tags); #endif gpr_free(g_freelist); g_freelist = next; } } struct grpc_cq_alarm { grpc_timer alarm; grpc_cq_completion completion; /** completion queue where events about this alarm will be posted */ grpc_completion_queue *cq; /** user supplied tag */ void *tag; }; grpc_completion_queue *grpc_completion_queue_create(void *reserved) { grpc_completion_queue *cc; GPR_ASSERT(!reserved); GPR_TIMER_BEGIN("grpc_completion_queue_create", 0); GRPC_API_TRACE("grpc_completion_queue_create(reserved=%p)", 1, (reserved)); gpr_mu_lock(&g_freelist_mu); if (g_freelist == NULL) { gpr_mu_unlock(&g_freelist_mu); cc = gpr_malloc(sizeof(grpc_completion_queue) + grpc_pollset_size()); grpc_pollset_init(POLLSET_FROM_CQ(cc), &cc->mu); #ifndef NDEBUG cc->outstanding_tags = NULL; cc->outstanding_tag_capacity = 0; #endif } else { cc = g_freelist; g_freelist = g_freelist->next_free; gpr_mu_unlock(&g_freelist_mu); /* pollset already initialized */ } /* Initial ref is dropped by grpc_completion_queue_shutdown */ gpr_ref_init(&cc->pending_events, 1); /* One for destroy(), one for pollset_shutdown */ gpr_ref_init(&cc->owning_refs, 2); cc->completed_tail = &cc->completed_head; cc->completed_head.next = (uintptr_t)cc->completed_tail; cc->shutdown = 0; cc->shutdown_called = 0; cc->is_server_cq = 0; cc->num_pluckers = 0; #ifndef NDEBUG cc->outstanding_tag_count = 0; #endif grpc_closure_init(&cc->pollset_shutdown_done, on_pollset_shutdown_done, cc); GPR_TIMER_END("grpc_completion_queue_create", 0); return cc; } #ifdef GRPC_CQ_REF_COUNT_DEBUG void grpc_cq_internal_ref(grpc_completion_queue *cc, const char *reason, const char *file, int line) { gpr_log(file, line, GPR_LOG_SEVERITY_DEBUG, "CQ:%p ref %d -> %d %s", cc, (int)cc->owning_refs.count, (int)cc->owning_refs.count + 1, reason); #else void grpc_cq_internal_ref(grpc_completion_queue *cc) { #endif gpr_ref(&cc->owning_refs); } static void on_pollset_shutdown_done(grpc_exec_ctx *exec_ctx, void *arg, bool success) { grpc_completion_queue *cc = arg; GRPC_CQ_INTERNAL_UNREF(cc, "pollset_destroy"); } #ifdef GRPC_CQ_REF_COUNT_DEBUG void grpc_cq_internal_unref(grpc_completion_queue *cc, const char *reason, const char *file, int line) { gpr_log(file, line, GPR_LOG_SEVERITY_DEBUG, "CQ:%p unref %d -> %d %s", cc, (int)cc->owning_refs.count, (int)cc->owning_refs.count - 1, reason); #else void grpc_cq_internal_unref(grpc_completion_queue *cc) { #endif if (gpr_unref(&cc->owning_refs)) { GPR_ASSERT(cc->completed_head.next == (uintptr_t)&cc->completed_head); grpc_pollset_reset(POLLSET_FROM_CQ(cc)); gpr_mu_lock(&g_freelist_mu); cc->next_free = g_freelist; g_freelist = cc; gpr_mu_unlock(&g_freelist_mu); } } void grpc_cq_begin_op(grpc_completion_queue *cc, void *tag) { #ifndef NDEBUG gpr_mu_lock(cc->mu); GPR_ASSERT(!cc->shutdown_called); if (cc->outstanding_tag_count == cc->outstanding_tag_capacity) { cc->outstanding_tag_capacity = GPR_MAX(4, 2 * cc->outstanding_tag_capacity); cc->outstanding_tags = gpr_realloc(cc->outstanding_tags, sizeof(*cc->outstanding_tags) * cc->outstanding_tag_capacity); } cc->outstanding_tags[cc->outstanding_tag_count++] = tag; gpr_mu_unlock(cc->mu); #endif gpr_ref(&cc->pending_events); } /* Signal the end of an operation - if this is the last waiting-to-be-queued event, then enter shutdown mode */ /* Queue a GRPC_OP_COMPLETED operation */ void grpc_cq_end_op(grpc_exec_ctx *exec_ctx, grpc_completion_queue *cc, void *tag, int success, void (*done)(grpc_exec_ctx *exec_ctx, void *done_arg, grpc_cq_completion *storage), void *done_arg, grpc_cq_completion *storage) { int shutdown; int i; grpc_pollset_worker *pluck_worker; #ifndef NDEBUG int found = 0; #endif GPR_TIMER_BEGIN("grpc_cq_end_op", 0); storage->tag = tag; storage->done = done; storage->done_arg = done_arg; storage->next = ((uintptr_t)&cc->completed_head) | ((uintptr_t)(success != 0)); gpr_mu_lock(cc->mu); #ifndef NDEBUG for (i = 0; i < (int)cc->outstanding_tag_count; i++) { if (cc->outstanding_tags[i] == tag) { cc->outstanding_tag_count--; GPR_SWAP(void *, cc->outstanding_tags[i], cc->outstanding_tags[cc->outstanding_tag_count]); found = 1; break; } } GPR_ASSERT(found); #endif shutdown = gpr_unref(&cc->pending_events); if (!shutdown) { cc->completed_tail->next = ((uintptr_t)storage) | (1u & (uintptr_t)cc->completed_tail->next); cc->completed_tail = storage; pluck_worker = NULL; for (i = 0; i < cc->num_pluckers; i++) { if (cc->pluckers[i].tag == tag) { pluck_worker = *cc->pluckers[i].worker; break; } } grpc_pollset_kick(POLLSET_FROM_CQ(cc), pluck_worker); gpr_mu_unlock(cc->mu); } else { cc->completed_tail->next = ((uintptr_t)storage) | (1u & (uintptr_t)cc->completed_tail->next); cc->completed_tail = storage; GPR_ASSERT(!cc->shutdown); GPR_ASSERT(cc->shutdown_called); cc->shutdown = 1; grpc_pollset_shutdown(exec_ctx, POLLSET_FROM_CQ(cc), &cc->pollset_shutdown_done); gpr_mu_unlock(cc->mu); } GPR_TIMER_END("grpc_cq_end_op", 0); } grpc_event grpc_completion_queue_next(grpc_completion_queue *cc, gpr_timespec deadline, void *reserved) { grpc_event ret; grpc_pollset_worker *worker = NULL; int first_loop = 1; gpr_timespec now; grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; GPR_TIMER_BEGIN("grpc_completion_queue_next", 0); GRPC_API_TRACE( "grpc_completion_queue_next(" "cc=%p, " "deadline=gpr_timespec { tv_sec: %lld, tv_nsec: %d, clock_type: %d }, " "reserved=%p)", 5, (cc, (long long)deadline.tv_sec, (int)deadline.tv_nsec, (int)deadline.clock_type, reserved)); GPR_ASSERT(!reserved); deadline = gpr_convert_clock_type(deadline, GPR_CLOCK_MONOTONIC); GRPC_CQ_INTERNAL_REF(cc, "next"); gpr_mu_lock(cc->mu); for (;;) { if (cc->completed_tail != &cc->completed_head) { grpc_cq_completion *c = (grpc_cq_completion *)cc->completed_head.next; cc->completed_head.next = c->next & ~(uintptr_t)1; if (c == cc->completed_tail) { cc->completed_tail = &cc->completed_head; } gpr_mu_unlock(cc->mu); ret.type = GRPC_OP_COMPLETE; ret.success = c->next & 1u; ret.tag = c->tag; c->done(&exec_ctx, c->done_arg, c); break; } if (cc->shutdown) { gpr_mu_unlock(cc->mu); memset(&ret, 0, sizeof(ret)); ret.type = GRPC_QUEUE_SHUTDOWN; break; } now = gpr_now(GPR_CLOCK_MONOTONIC); if (!first_loop && gpr_time_cmp(now, deadline) >= 0) { gpr_mu_unlock(cc->mu); memset(&ret, 0, sizeof(ret)); ret.type = GRPC_QUEUE_TIMEOUT; break; } first_loop = 0; /* Check alarms - these are a global resource so we just ping each time through on every pollset. May update deadline to ensure timely wakeups. TODO(ctiller): can this work be localized? */ gpr_timespec iteration_deadline = deadline; if (grpc_timer_check(&exec_ctx, now, &iteration_deadline)) { GPR_TIMER_MARK("alarm_triggered", 0); gpr_mu_unlock(cc->mu); grpc_exec_ctx_flush(&exec_ctx); gpr_mu_lock(cc->mu); continue; } else { grpc_pollset_work(&exec_ctx, POLLSET_FROM_CQ(cc), &worker, now, iteration_deadline); } } GRPC_SURFACE_TRACE_RETURNED_EVENT(cc, &ret); GRPC_CQ_INTERNAL_UNREF(cc, "next"); grpc_exec_ctx_finish(&exec_ctx); GPR_TIMER_END("grpc_completion_queue_next", 0); return ret; } static int add_plucker(grpc_completion_queue *cc, void *tag, grpc_pollset_worker **worker) { if (cc->num_pluckers == GRPC_MAX_COMPLETION_QUEUE_PLUCKERS) { return 0; } cc->pluckers[cc->num_pluckers].tag = tag; cc->pluckers[cc->num_pluckers].worker = worker; cc->num_pluckers++; return 1; } static void del_plucker(grpc_completion_queue *cc, void *tag, grpc_pollset_worker **worker) { int i; for (i = 0; i < cc->num_pluckers; i++) { if (cc->pluckers[i].tag == tag && cc->pluckers[i].worker == worker) { cc->num_pluckers--; GPR_SWAP(plucker, cc->pluckers[i], cc->pluckers[cc->num_pluckers]); return; } } GPR_UNREACHABLE_CODE(return ); } grpc_event grpc_completion_queue_pluck(grpc_completion_queue *cc, void *tag, gpr_timespec deadline, void *reserved) { grpc_event ret; grpc_cq_completion *c; grpc_cq_completion *prev; grpc_pollset_worker *worker = NULL; gpr_timespec now; int first_loop = 1; grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; GPR_TIMER_BEGIN("grpc_completion_queue_pluck", 0); GRPC_API_TRACE( "grpc_completion_queue_pluck(" "cc=%p, tag=%p, " "deadline=gpr_timespec { tv_sec: %lld, tv_nsec: %d, clock_type: %d }, " "reserved=%p)", 6, (cc, tag, (long long)deadline.tv_sec, (int)deadline.tv_nsec, (int)deadline.clock_type, reserved)); GPR_ASSERT(!reserved); deadline = gpr_convert_clock_type(deadline, GPR_CLOCK_MONOTONIC); GRPC_CQ_INTERNAL_REF(cc, "pluck"); gpr_mu_lock(cc->mu); for (;;) { prev = &cc->completed_head; while ((c = (grpc_cq_completion *)(prev->next & ~(uintptr_t)1)) != &cc->completed_head) { if (c->tag == tag) { prev->next = (prev->next & (uintptr_t)1) | (c->next & ~(uintptr_t)1); if (c == cc->completed_tail) { cc->completed_tail = prev; } gpr_mu_unlock(cc->mu); ret.type = GRPC_OP_COMPLETE; ret.success = c->next & 1u; ret.tag = c->tag; c->done(&exec_ctx, c->done_arg, c); goto done; } prev = c; } if (cc->shutdown) { gpr_mu_unlock(cc->mu); memset(&ret, 0, sizeof(ret)); ret.type = GRPC_QUEUE_SHUTDOWN; break; } if (!add_plucker(cc, tag, &worker)) { gpr_log(GPR_DEBUG, "Too many outstanding grpc_completion_queue_pluck calls: maximum " "is %d", GRPC_MAX_COMPLETION_QUEUE_PLUCKERS); gpr_mu_unlock(cc->mu); memset(&ret, 0, sizeof(ret)); /* TODO(ctiller): should we use a different result here */ ret.type = GRPC_QUEUE_TIMEOUT; break; } now = gpr_now(GPR_CLOCK_MONOTONIC); if (!first_loop && gpr_time_cmp(now, deadline) >= 0) { del_plucker(cc, tag, &worker); gpr_mu_unlock(cc->mu); memset(&ret, 0, sizeof(ret)); ret.type = GRPC_QUEUE_TIMEOUT; break; } first_loop = 0; /* Check alarms - these are a global resource so we just ping each time through on every pollset. May update deadline to ensure timely wakeups. TODO(ctiller): can this work be localized? */ gpr_timespec iteration_deadline = deadline; if (grpc_timer_check(&exec_ctx, now, &iteration_deadline)) { GPR_TIMER_MARK("alarm_triggered", 0); gpr_mu_unlock(cc->mu); grpc_exec_ctx_flush(&exec_ctx); gpr_mu_lock(cc->mu); } else { grpc_pollset_work(&exec_ctx, POLLSET_FROM_CQ(cc), &worker, now, iteration_deadline); } del_plucker(cc, tag, &worker); } done: GRPC_SURFACE_TRACE_RETURNED_EVENT(cc, &ret); GRPC_CQ_INTERNAL_UNREF(cc, "pluck"); grpc_exec_ctx_finish(&exec_ctx); GPR_TIMER_END("grpc_completion_queue_pluck", 0); return ret; } /* Shutdown simply drops a ref that we reserved at creation time; if we drop to zero here, then enter shutdown mode and wake up any waiters */ void grpc_completion_queue_shutdown(grpc_completion_queue *cc) { grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; GPR_TIMER_BEGIN("grpc_completion_queue_shutdown", 0); GRPC_API_TRACE("grpc_completion_queue_shutdown(cc=%p)", 1, (cc)); gpr_mu_lock(cc->mu); if (cc->shutdown_called) { gpr_mu_unlock(cc->mu); GPR_TIMER_END("grpc_completion_queue_shutdown", 0); return; } cc->shutdown_called = 1; if (gpr_unref(&cc->pending_events)) { GPR_ASSERT(!cc->shutdown); cc->shutdown = 1; grpc_pollset_shutdown(&exec_ctx, POLLSET_FROM_CQ(cc), &cc->pollset_shutdown_done); } gpr_mu_unlock(cc->mu); grpc_exec_ctx_finish(&exec_ctx); GPR_TIMER_END("grpc_completion_queue_shutdown", 0); } void grpc_completion_queue_destroy(grpc_completion_queue *cc) { GRPC_API_TRACE("grpc_completion_queue_destroy(cc=%p)", 1, (cc)); GPR_TIMER_BEGIN("grpc_completion_queue_destroy", 0); grpc_completion_queue_shutdown(cc); GRPC_CQ_INTERNAL_UNREF(cc, "destroy"); GPR_TIMER_END("grpc_completion_queue_destroy", 0); } grpc_pollset *grpc_cq_pollset(grpc_completion_queue *cc) { return POLLSET_FROM_CQ(cc); } void grpc_cq_mark_server_cq(grpc_completion_queue *cc) { cc->is_server_cq = 1; } int grpc_cq_is_server_cq(grpc_completion_queue *cc) { return cc->is_server_cq; }
miselin/grpc
src/core/lib/surface/completion_queue.c
C
bsd-3-clause
16,842
//***************************************************************************** // // fontcmss46b.c - Font definition for the 46 point Cmss bold font. // // Copyright (c) 2008-2010 Texas Instruments Incorporated. All rights reserved. // Software License Agreement // // Texas Instruments (TI) is supplying this software for use solely and // exclusively on TI's microcontroller products. The software is owned by // TI and/or its suppliers, and is protected under applicable copyright // laws. You may not combine this software with "viral" open-source // software in order to form a larger program. // // THIS SOFTWARE IS PROVIDED "AS IS" AND WITH ALL FAULTS. // NO WARRANTIES, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, BUT // NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. TI SHALL NOT, UNDER ANY // CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR CONSEQUENTIAL // DAMAGES, FOR ANY REASON WHATSOEVER. // // This is part of revision 6288 of the Stellaris Graphics Library. // //***************************************************************************** //***************************************************************************** // // This file is generated by ftrasterize; DO NOT EDIT BY HAND! // //***************************************************************************** #include "grlib.h" //***************************************************************************** // // Details of this font: // Style: cmss // Size: 46 point // Bold: yes // Italic: no // Memory usage: 5636 bytes // //***************************************************************************** //***************************************************************************** // // The compressed data for the 46 point Cmss bold font. // //***************************************************************************** static const unsigned char g_pucCmss46bData[5434] = { 5, 18, 0, 101, 32, 37, 10, 240, 86, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 240, 240, 70, 70, 70, 70, 70, 70, 0, 14, 32, 29, 20, 240, 240, 166, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 84, 100, 100, 100, 99, 115, 100, 100, 99, 115, 0, 80, 112, 129, 40, 0, 12, 18, 131, 240, 180, 115, 240, 180, 100, 240, 180, 100, 240, 164, 116, 240, 164, 116, 240, 164, 100, 240, 164, 116, 240, 164, 116, 240, 164, 100, 240, 180, 100, 240, 164, 116, 240, 164, 116, 223, 15, 4, 95, 15, 6, 79, 15, 6, 95, 15, 4, 240, 36, 100, 240, 164, 116, 240, 164, 116, 240, 164, 100, 240, 164, 116, 240, 164, 116, 240, 164, 100, 240, 47, 15, 4, 95, 15, 6, 79, 15, 6, 95, 15, 4, 228, 100, 240, 164, 116, 240, 164, 115, 240, 180, 100, 240, 164, 116, 240, 164, 116, 240, 164, 100, 240, 179, 116, 240, 164, 116, 240, 164, 115, 240, 180, 100, 240, 179, 116, 240, 179, 130, 0, 12, 80, 70, 23, 131, 240, 83, 240, 56, 206, 143, 1, 111, 2, 102, 19, 37, 86, 35, 67, 85, 51, 197, 51, 197, 51, 198, 35, 198, 35, 203, 219, 205, 190, 174, 173, 189, 218, 219, 195, 38, 195, 38, 195, 53, 195, 53, 195, 53, 66, 99, 53, 68, 67, 38, 70, 35, 22, 95, 3, 95, 2, 127, 172, 230, 240, 67, 240, 83, 0, 24, 64, 124, 44, 86, 240, 82, 234, 240, 36, 204, 245, 181, 54, 213, 196, 85, 212, 197, 101, 181, 197, 101, 165, 213, 101, 164, 229, 101, 149, 229, 101, 133, 245, 101, 117, 240, 21, 101, 116, 240, 53, 70, 101, 240, 53, 54, 101, 240, 78, 85, 240, 108, 100, 240, 152, 117, 240, 240, 133, 240, 240, 148, 104, 240, 165, 91, 240, 117, 92, 240, 101, 85, 54, 240, 84, 101, 69, 240, 69, 85, 101, 240, 37, 101, 101, 240, 36, 117, 101, 240, 20, 133, 101, 245, 133, 101, 229, 149, 101, 228, 165, 101, 213, 165, 101, 197, 181, 101, 181, 213, 69, 196, 229, 54, 181, 252, 196, 240, 42, 226, 240, 86, 0, 45, 16, 93, 37, 0, 6, 5, 240, 249, 240, 203, 240, 165, 53, 240, 133, 69, 240, 132, 101, 240, 101, 101, 240, 101, 101, 240, 101, 101, 240, 101, 101, 240, 101, 85, 240, 117, 69, 240, 134, 53, 240, 149, 22, 132, 219, 149, 201, 181, 200, 196, 230, 197, 215, 197, 201, 165, 188, 149, 165, 39, 117, 166, 39, 102, 165, 71, 85, 166, 87, 54, 166, 103, 22, 182, 109, 198, 123, 215, 121, 247, 91, 114, 95, 15, 2, 111, 15, 1, 126, 61, 167, 168, 0, 47, 17, 10, 240, 86, 70, 70, 70, 70, 70, 84, 100, 99, 100, 99, 0, 40, 112, 48, 16, 147, 196, 180, 180, 181, 180, 181, 165, 181, 181, 165, 181, 166, 166, 166, 165, 181, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 181, 182, 166, 166, 181, 181, 182, 181, 181, 197, 196, 197, 196, 212, 212, 211, 64, 48, 16, 3, 212, 212, 212, 197, 196, 197, 197, 181, 182, 181, 181, 182, 166, 166, 181, 182, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 166, 165, 181, 166, 166, 165, 181, 166, 165, 181, 165, 180, 181, 180, 180, 180, 195, 208, 52, 23, 131, 240, 69, 240, 53, 240, 53, 195, 67, 67, 85, 51, 53, 70, 35, 38, 71, 19, 23, 95, 2, 155, 240, 19, 240, 27, 159, 2, 87, 19, 23, 70, 35, 38, 69, 51, 53, 83, 67, 67, 197, 240, 53, 240, 53, 240, 67, 0, 70, 64, 103, 38, 0, 30, 66, 240, 240, 84, 240, 240, 68, 240, 240, 68, 240, 240, 68, 240, 240, 68, 240, 240, 68, 240, 240, 68, 240, 240, 68, 240, 240, 68, 240, 240, 68, 240, 240, 68, 240, 240, 68, 240, 240, 68, 240, 95, 15, 2, 95, 15, 4, 79, 15, 4, 95, 15, 2, 240, 84, 240, 240, 68, 240, 240, 68, 240, 240, 68, 240, 240, 68, 240, 240, 68, 240, 240, 68, 240, 240, 68, 240, 240, 68, 240, 240, 68, 240, 240, 68, 240, 240, 68, 240, 240, 68, 240, 240, 68, 240, 240, 82, 0, 31, 18, 10, 0, 35, 6, 70, 70, 70, 70, 70, 84, 100, 99, 100, 99, 0, 8, 48, 9, 17, 0, 46, 109, 77, 77, 0, 43, 13, 10, 0, 35, 6, 70, 70, 70, 70, 70, 0, 14, 32, 94, 23, 240, 18, 240, 84, 240, 68, 240, 68, 240, 52, 240, 68, 240, 52, 240, 68, 240, 68, 240, 52, 240, 68, 240, 68, 240, 52, 240, 68, 240, 52, 240, 68, 240, 68, 240, 52, 240, 68, 240, 68, 240, 52, 240, 68, 240, 67, 240, 68, 240, 68, 240, 52, 240, 68, 240, 68, 240, 52, 240, 68, 240, 68, 240, 52, 240, 68, 240, 52, 240, 68, 240, 68, 240, 52, 240, 68, 240, 68, 240, 52, 240, 68, 240, 52, 240, 68, 240, 68, 240, 82, 240, 80, 71, 24, 240, 240, 22, 240, 26, 221, 165, 69, 149, 101, 133, 102, 102, 102, 101, 133, 101, 133, 86, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 85, 133, 101, 133, 102, 102, 102, 102, 118, 85, 149, 69, 174, 202, 240, 22, 0, 31, 48, 44, 21, 240, 243, 240, 21, 231, 156, 156, 156, 162, 54, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 175, 1, 79, 2, 95, 1, 0, 29, 48, 69, 24, 0, 6, 103, 252, 190, 159, 1, 118, 72, 85, 119, 85, 135, 83, 166, 98, 166, 98, 166, 240, 54, 240, 54, 240, 54, 240, 38, 240, 54, 240, 38, 240, 53, 240, 53, 240, 53, 240, 53, 240, 53, 240, 53, 240, 53, 240, 53, 240, 53, 240, 53, 240, 53, 240, 63, 4, 95, 4, 95, 4, 95, 4, 95, 4, 0, 33, 64, 66, 24, 240, 240, 23, 236, 190, 159, 1, 118, 86, 116, 134, 114, 150, 114, 150, 240, 54, 240, 54, 240, 53, 240, 54, 240, 53, 240, 54, 218, 233, 251, 240, 70, 240, 70, 240, 69, 240, 70, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 81, 198, 67, 182, 68, 150, 87, 87, 95, 3, 143, 173, 232, 0, 31, 32, 70, 25, 0, 7, 86, 240, 55, 240, 40, 240, 40, 240, 25, 240, 25, 244, 21, 244, 21, 229, 21, 228, 37, 213, 37, 212, 53, 197, 53, 196, 69, 181, 69, 180, 85, 165, 85, 149, 101, 149, 101, 133, 117, 133, 117, 143, 6, 79, 6, 79, 6, 79, 6, 240, 21, 240, 85, 240, 85, 240, 85, 240, 85, 240, 85, 240, 85, 0, 35, 48, 68, 24, 0, 6, 47, 1, 143, 1, 143, 1, 143, 1, 143, 1, 134, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 240, 61, 191, 159, 1, 135, 70, 117, 102, 117, 117, 131, 134, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 82, 182, 83, 165, 85, 134, 87, 87, 111, 2, 143, 188, 231, 0, 31, 48, 67, 24, 240, 240, 55, 235, 204, 189, 167, 82, 150, 240, 54, 240, 38, 240, 54, 240, 53, 240, 69, 240, 54, 54, 150, 41, 118, 27, 104, 70, 103, 102, 87, 117, 87, 118, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 85, 134, 85, 134, 85, 134, 86, 117, 117, 102, 118, 71, 143, 173, 203, 247, 0, 31, 32, 73, 24, 0, 6, 15, 4, 95, 5, 79, 5, 79, 5, 79, 4, 240, 53, 240, 54, 240, 53, 240, 53, 240, 54, 240, 53, 240, 54, 240, 53, 240, 54, 240, 53, 240, 54, 240, 53, 240, 54, 240, 54, 240, 54, 240, 38, 240, 54, 240, 54, 240, 54, 240, 53, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 0, 31, 96, 65, 24, 240, 248, 236, 190, 159, 1, 118, 87, 101, 133, 101, 133, 101, 133, 101, 133, 101, 133, 101, 133, 101, 133, 102, 102, 118, 70, 158, 202, 206, 150, 70, 118, 102, 101, 133, 86, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 86, 102, 103, 71, 127, 1, 158, 188, 232, 0, 31, 32, 67, 24, 240, 240, 22, 251, 206, 159, 150, 70, 118, 101, 117, 118, 86, 133, 86, 133, 86, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 119, 85, 119, 86, 103, 102, 57, 107, 22, 121, 38, 150, 54, 240, 53, 240, 69, 240, 69, 240, 54, 240, 53, 145, 134, 132, 86, 158, 158, 188, 247, 0, 31, 64, 21, 10, 0, 16, 38, 70, 70, 70, 70, 70, 0, 11, 102, 70, 70, 70, 70, 70, 0, 14, 32, 26, 10, 0, 16, 38, 70, 70, 70, 70, 70, 0, 11, 102, 70, 70, 70, 70, 70, 84, 100, 99, 100, 99, 0, 8, 48, 37, 10, 0, 13, 102, 70, 70, 70, 70, 70, 240, 240, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 240, 144, 32, 37, 0, 69, 79, 15, 1, 95, 15, 3, 79, 15, 3, 95, 15, 1, 0, 33, 31, 15, 1, 95, 15, 3, 79, 15, 3, 95, 15, 1, 0, 70, 57, 22, 0, 31, 5, 240, 23, 247, 247, 247, 240, 21, 0, 10, 53, 240, 37, 240, 37, 240, 37, 240, 37, 240, 37, 240, 21, 240, 37, 240, 22, 240, 21, 240, 22, 246, 247, 246, 246, 240, 22, 240, 22, 240, 22, 146, 86, 132, 86, 86, 95, 2, 111, 153, 0, 6, 80, 49, 21, 0, 5, 104, 174, 111, 1, 85, 86, 84, 118, 81, 150, 246, 246, 246, 231, 215, 230, 230, 230, 245, 240, 21, 245, 240, 21, 240, 21, 240, 20, 240, 36, 240, 36, 240, 36, 0, 9, 118, 246, 246, 246, 246, 246, 0, 30, 16, 84, 31, 0, 9, 25, 240, 78, 255, 3, 199, 102, 182, 165, 149, 198, 117, 124, 117, 94, 101, 95, 1, 85, 69, 72, 85, 53, 118, 84, 69, 118, 69, 53, 149, 69, 53, 149, 69, 53, 149, 69, 53, 149, 69, 53, 149, 69, 53, 149, 69, 53, 149, 69, 53, 149, 69, 53, 149, 85, 53, 117, 101, 53, 117, 101, 70, 69, 133, 77, 149, 91, 181, 103, 215, 240, 168, 150, 175, 4, 239, 240, 73, 0, 44, 80, 33, 0, 9, 87, 240, 169, 240, 139, 240, 123, 240, 123, 240, 109, 240, 93, 240, 86, 22, 240, 70, 39, 240, 54, 39, 240, 54, 39, 240, 38, 71, 240, 22, 71, 240, 22, 71, 246, 103, 230, 103, 230, 103, 214, 135, 198, 135, 198, 135, 182, 167, 175, 8, 175, 8, 159, 10, 143, 10, 134, 214, 118, 231, 102, 231, 102, 246, 86, 240, 23, 70, 240, 23, 69, 240, 54, 0, 45, 112, 71, 30, 0, 7, 79, 3, 207, 6, 159, 7, 143, 8, 118, 153, 102, 183, 102, 199, 86, 214, 86, 214, 86, 214, 86, 198, 102, 198, 102, 182, 118, 151, 143, 6, 159, 4, 191, 7, 134, 168, 102, 199, 86, 214, 86, 215, 70, 230, 70, 230, 70, 230, 70, 230, 70, 215, 70, 214, 86, 184, 95, 9, 111, 8, 127, 7, 143, 4, 0, 42, 80, 71, 30, 0, 8, 122, 240, 47, 2, 191, 4, 175, 5, 152, 118, 135, 195, 119, 225, 134, 240, 134, 240, 150, 240, 150, 240, 134, 240, 150, 240, 150, 240, 150, 240, 150, 240, 150, 240, 150, 240, 150, 240, 150, 240, 150, 240, 166, 240, 150, 240, 150, 240, 166, 240, 151, 241, 135, 211, 137, 118, 143, 7, 175, 5, 207, 1, 240, 42, 0, 42, 48, 87, 33, 0, 8, 47, 4, 239, 7, 191, 9, 159, 10, 134, 170, 118, 215, 118, 231, 102, 246, 102, 240, 22, 86, 240, 22, 86, 240, 37, 86, 240, 38, 70, 240, 38, 70, 240, 38, 70, 240, 38, 70, 240, 38, 70, 240, 38, 70, 240, 38, 70, 240, 38, 70, 240, 38, 70, 240, 38, 70, 240, 38, 70, 240, 22, 86, 240, 22, 86, 247, 86, 231, 102, 215, 118, 185, 127, 10, 143, 9, 159, 7, 191, 4, 0, 47, 16, 71, 26, 0, 6, 79, 6, 95, 6, 95, 6, 95, 6, 95, 6, 86, 240, 86, 240, 86, 240, 86, 240, 86, 240, 86, 240, 86, 240, 86, 240, 86, 240, 95, 5, 111, 5, 111, 5, 111, 5, 102, 240, 86, 240, 86, 240, 86, 240, 86, 240, 86, 240, 86, 240, 86, 240, 86, 240, 95, 7, 79, 7, 79, 7, 79, 7, 79, 7, 0, 36, 32, 70, 25, 0, 6, 47, 5, 95, 6, 79, 6, 79, 6, 79, 5, 86, 240, 70, 240, 70, 240, 70, 240, 70, 240, 70, 240, 70, 240, 70, 240, 70, 240, 79, 3, 127, 4, 111, 4, 111, 3, 118, 240, 70, 240, 70, 240, 70, 240, 70, 240, 70, 240, 70, 240, 70, 240, 70, 240, 70, 240, 70, 240, 70, 240, 70, 240, 70, 0, 36, 96, 72, 30, 0, 8, 122, 240, 47, 1, 207, 5, 159, 6, 136, 134, 119, 195, 119, 226, 118, 240, 17, 102, 240, 150, 240, 150, 240, 134, 240, 150, 240, 150, 240, 150, 240, 150, 240, 150, 240, 150, 170, 70, 170, 70, 170, 70, 170, 86, 214, 86, 214, 87, 198, 102, 198, 103, 182, 119, 166, 136, 134, 159, 6, 175, 5, 207, 1, 240, 42, 0, 42, 48, 71, 31, 0, 7, 102, 246, 70, 246, 70, 246, 70, 246, 70, 246, 70, 246, 70, 246, 70, 246, 70, 246, 70, 246, 70, 246, 70, 246, 70, 246, 70, 246, 79, 12, 79, 12, 79, 12, 79, 12, 70, 246, 70, 246, 70, 246, 70, 246, 70, 246, 70, 246, 70, 246, 70, 246, 70, 246, 70, 246, 70, 246, 70, 246, 70, 246, 70, 246, 0, 43, 16, 38, 10, 240, 86, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 0, 14, 32, 43, 21, 0, 6, 86, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 246, 81, 150, 82, 134, 84, 71, 111, 95, 125, 184, 0, 27, 48, 75, 32, 0, 8, 6, 246, 86, 231, 86, 215, 102, 199, 118, 183, 134, 167, 150, 151, 166, 135, 182, 119, 198, 103, 214, 87, 230, 71, 246, 55, 240, 22, 24, 240, 47, 1, 240, 31, 2, 255, 2, 255, 3, 234, 39, 217, 71, 200, 87, 199, 119, 182, 151, 166, 166, 166, 167, 150, 183, 134, 199, 118, 199, 118, 215, 102, 231, 86, 247, 70, 240, 21, 0, 44, 80, 71, 23, 0, 5, 102, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 47, 4, 79, 4, 79, 4, 79, 4, 79, 4, 0, 32, 16, 117, 40, 0, 10, 8, 240, 88, 73, 240, 57, 74, 240, 26, 74, 240, 26, 74, 240, 26, 75, 235, 75, 235, 70, 20, 228, 22, 70, 21, 197, 22, 70, 21, 197, 22, 70, 37, 165, 38, 70, 37, 165, 38, 70, 37, 165, 38, 70, 53, 133, 54, 70, 53, 133, 54, 70, 54, 101, 70, 70, 69, 101, 70, 70, 69, 101, 70, 70, 85, 69, 86, 70, 85, 69, 86, 70, 85, 69, 86, 70, 101, 37, 102, 70, 101, 37, 102, 70, 107, 118, 70, 122, 118, 70, 122, 118, 70, 136, 134, 70, 136, 134, 70, 135, 150, 70, 150, 150, 70, 164, 166, 70, 240, 150, 0, 55, 64, 89, 32, 0, 8, 24, 229, 74, 198, 74, 198, 75, 182, 75, 182, 76, 166, 76, 166, 70, 22, 150, 70, 22, 150, 70, 38, 134, 70, 38, 134, 70, 54, 118, 70, 54, 118, 70, 70, 102, 70, 70, 102, 70, 86, 86, 70, 86, 86, 70, 102, 70, 70, 102, 70, 70, 118, 54, 70, 118, 54, 70, 134, 38, 70, 134, 38, 70, 150, 22, 70, 150, 22, 70, 172, 70, 172, 70, 187, 70, 187, 70, 202, 70, 202, 70, 217, 0, 44, 64, 86, 33, 240, 240, 217, 240, 111, 240, 47, 3, 223, 6, 199, 120, 166, 182, 150, 214, 134, 214, 118, 246, 102, 246, 102, 246, 101, 240, 38, 70, 240, 38, 70, 240, 38, 70, 240, 38, 70, 240, 38, 70, 240, 38, 70, 240, 38, 70, 240, 38, 70, 240, 38, 70, 240, 38, 70, 240, 38, 70, 240, 38, 86, 246, 102, 246, 102, 246, 118, 214, 135, 183, 151, 151, 169, 104, 191, 6, 223, 4, 240, 31, 240, 105, 0, 43, 70, 29, 0, 7, 47, 3, 191, 6, 143, 7, 127, 8, 102, 168, 86, 198, 86, 199, 70, 214, 70, 214, 70, 214, 70, 214, 70, 214, 70, 214, 70, 199, 70, 198, 86, 168, 95, 8, 111, 7, 127, 6, 143, 3, 182, 240, 134, 240, 134, 240, 134, 240, 134, 240, 134, 240, 134, 240, 134, 240, 134, 240, 134, 240, 134, 240, 134, 0, 42, 96, 104, 34, 240, 240, 234, 240, 127, 240, 47, 3, 255, 6, 200, 104, 183, 167, 151, 199, 134, 230, 118, 240, 22, 102, 240, 22, 102, 240, 22, 101, 240, 54, 70, 240, 54, 70, 240, 54, 70, 240, 54, 70, 240, 54, 70, 240, 54, 70, 240, 54, 70, 240, 54, 70, 240, 54, 70, 240, 54, 70, 240, 54, 70, 240, 54, 86, 240, 23, 86, 102, 70, 102, 103, 54, 118, 103, 23, 119, 94, 151, 93, 153, 75, 191, 7, 239, 3, 240, 47, 3, 240, 79, 1, 240, 200, 240, 184, 240, 200, 240, 199, 0, 26, 32, 71, 29, 0, 7, 47, 3, 191, 6, 143, 7, 127, 8, 102, 168, 86, 198, 86, 199, 70, 214, 70, 214, 70, 214, 70, 214, 70, 214, 70, 199, 70, 198, 86, 167, 111, 7, 127, 6, 143, 4, 166, 103, 166, 103, 166, 119, 150, 134, 150, 135, 134, 150, 134, 151, 118, 167, 102, 182, 102, 183, 86, 198, 86, 199, 70, 214, 70, 229, 0, 40, 48, 65, 26, 0, 7, 57, 239, 159, 3, 143, 3, 119, 102, 118, 148, 102, 193, 118, 240, 86, 240, 86, 240, 87, 240, 73, 240, 59, 255, 207, 1, 191, 1, 191, 1, 207, 236, 240, 56, 240, 87, 240, 71, 240, 86, 240, 86, 66, 230, 67, 214, 69, 167, 71, 119, 95, 6, 95, 5, 127, 3, 175, 233, 0, 33, 112, 70, 32, 0, 8, 15, 13, 79, 13, 79, 13, 79, 13, 79, 13, 246, 240, 182, 240, 182, 240, 182, 240, 182, 240, 182, 240, 182, 240, 182, 240, 182, 240, 182, 240, 182, 240, 182, 240, 182, 240, 182, 240, 182, 240, 182, 240, 182, 240, 182, 240, 182, 240, 182, 240, 182, 240, 182, 240, 182, 240, 182, 240, 182, 240, 182, 240, 182, 0, 45, 112, 72, 30, 0, 7, 70, 230, 70, 230, 70, 230, 70, 230, 70, 230, 70, 230, 70, 230, 70, 230, 70, 230, 70, 230, 70, 230, 70, 230, 70, 230, 70, 230, 70, 230, 70, 230, 70, 230, 70, 230, 70, 230, 70, 230, 70, 230, 70, 230, 70, 230, 70, 230, 70, 230, 86, 199, 86, 198, 103, 167, 120, 104, 159, 5, 191, 3, 223, 240, 57, 0, 39, 16, 82, 35, 0, 8, 102, 240, 70, 71, 240, 54, 87, 240, 22, 103, 240, 22, 103, 247, 119, 230, 135, 230, 135, 215, 151, 198, 167, 198, 167, 183, 183, 166, 199, 166, 214, 150, 231, 134, 231, 119, 247, 102, 240, 23, 102, 240, 23, 87, 240, 39, 70, 240, 55, 70, 240, 55, 55, 240, 71, 38, 240, 87, 38, 240, 102, 22, 240, 125, 240, 125, 240, 139, 240, 155, 240, 155, 240, 169, 240, 185, 0, 50, 122, 49, 0, 12, 37, 231, 228, 86, 216, 198, 70, 201, 197, 102, 185, 197, 102, 185, 197, 102, 171, 166, 102, 171, 165, 134, 149, 21, 165, 134, 149, 21, 165, 134, 133, 38, 134, 134, 133, 38, 133, 166, 117, 53, 133, 166, 117, 54, 102, 166, 101, 70, 102, 166, 101, 70, 101, 198, 85, 85, 101, 198, 85, 86, 70, 198, 69, 102, 69, 230, 53, 102, 69, 230, 53, 117, 69, 230, 53, 118, 38, 230, 37, 134, 37, 240, 22, 21, 134, 37, 240, 22, 21, 149, 37, 240, 22, 20, 172, 240, 27, 171, 240, 58, 186, 240, 58, 186, 240, 57, 202, 240, 57, 201, 240, 88, 216, 240, 87, 231, 0, 69, 77, 34, 0, 8, 87, 215, 120, 184, 136, 167, 152, 151, 184, 120, 200, 103, 232, 71, 240, 23, 56, 240, 24, 39, 240, 63, 240, 93, 240, 124, 240, 123, 240, 153, 240, 184, 240, 184, 240, 169, 240, 170, 240, 140, 240, 110, 240, 71, 23, 240, 71, 39, 240, 39, 56, 247, 88, 216, 103, 215, 135, 183, 152, 152, 168, 135, 199, 119, 216, 88, 232, 71, 240, 23, 0, 47, 32, 74, 34, 0, 8, 71, 240, 38, 72, 247, 87, 231, 104, 215, 120, 183, 151, 167, 168, 151, 184, 119, 215, 103, 232, 87, 248, 55, 240, 39, 39, 240, 56, 23, 240, 78, 240, 108, 240, 124, 240, 138, 240, 168, 240, 199, 240, 198, 240, 214, 240, 214, 240, 214, 240, 214, 240, 214, 240, 214, 240, 214, 240, 214, 240, 214, 240, 214, 240, 214, 240, 214, 0, 48, 96, 72, 29, 0, 7, 63, 9, 95, 9, 95, 9, 95, 9, 95, 9, 240, 88, 240, 103, 240, 103, 240, 104, 240, 103, 240, 103, 240, 103, 240, 104, 240, 103, 240, 103, 240, 103, 240, 104, 240, 103, 240, 103, 240, 104, 240, 103, 240, 103, 240, 103, 240, 104, 240, 103, 240, 103, 240, 103, 240, 127, 9, 79, 10, 79, 10, 79, 10, 79, 10, 0, 40, 48, 48, 15, 10, 91, 74, 86, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 154, 91, 74, 80, 29, 21, 240, 240, 243, 131, 100, 116, 99, 131, 100, 116, 100, 116, 86, 86, 70, 86, 70, 86, 70, 86, 70, 86, 70, 86, 0, 84, 64, 48, 15, 26, 75, 90, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 150, 90, 75, 90, 64, 17, 19, 240, 240, 213, 215, 185, 149, 21, 117, 52, 100, 100, 83, 132, 0, 86, 10, 10, 240, 86, 70, 70, 70, 70, 0, 48, 17, 10, 240, 131, 100, 99, 100, 100, 86, 70, 70, 70, 70, 70, 0, 40, 64, 48, 24, 0, 36, 105, 206, 159, 2, 117, 102, 115, 150, 98, 166, 240, 54, 240, 54, 240, 54, 204, 143, 1, 103, 86, 87, 102, 86, 118, 70, 134, 70, 134, 70, 134, 71, 103, 87, 72, 92, 22, 106, 38, 134, 84, 0, 33, 80, 71, 24, 0, 6, 6, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 54, 150, 26, 127, 3, 104, 71, 86, 118, 86, 118, 86, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 118, 86, 118, 87, 86, 111, 3, 102, 25, 149, 38, 0, 34, 32, 45, 23, 0, 35, 56, 205, 159, 127, 1, 103, 100, 102, 146, 101, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 54, 161, 102, 146, 103, 101, 111, 2, 127, 157, 200, 0, 32, 96, 69, 25, 0, 8, 37, 240, 70, 240, 70, 240, 70, 240, 70, 240, 70, 240, 70, 240, 70, 240, 70, 240, 70, 240, 70, 166, 54, 138, 22, 127, 3, 103, 87, 86, 134, 86, 134, 70, 150, 70, 150, 70, 150, 70, 150, 70, 150, 70, 150, 70, 150, 70, 150, 70, 150, 86, 134, 86, 134, 102, 88, 111, 4, 138, 22, 166, 68, 0, 35, 45, 25, 0, 41, 72, 253, 175, 1, 135, 86, 102, 133, 102, 148, 101, 165, 70, 165, 70, 165, 79, 6, 79, 6, 70, 240, 70, 240, 70, 240, 86, 240, 70, 194, 102, 163, 103, 102, 127, 3, 158, 232, 0, 35, 64, 41, 20, 0, 6, 8, 170, 155, 134, 66, 118, 97, 118, 230, 230, 230, 230, 230, 204, 125, 140, 166, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 0, 28, 112, 63, 27, 0, 44, 89, 68, 143, 4, 127, 5, 102, 70, 181, 102, 150, 102, 150, 102, 150, 102, 150, 102, 150, 102, 150, 102, 166, 70, 206, 221, 225, 40, 243, 240, 147, 240, 159, 1, 191, 3, 175, 4, 143, 4, 111, 7, 85, 182, 69, 213, 69, 213, 70, 197, 86, 150, 127, 4, 159, 2, 219, 0, 8, 71, 23, 0, 5, 102, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 240, 38, 70, 118, 42, 86, 27, 89, 55, 71, 102, 71, 102, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 0, 32, 16, 35, 10, 240, 86, 70, 70, 70, 70, 70, 0, 6, 102, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 0, 14, 32, 46, 17, 240, 240, 182, 167, 167, 167, 167, 182, 0, 12, 6, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 66, 71, 76, 92, 91, 150, 240, 240, 192, 65, 23, 0, 5, 101, 240, 53, 240, 53, 240, 53, 240, 53, 240, 53, 240, 53, 240, 53, 240, 53, 240, 53, 240, 53, 240, 53, 118, 85, 103, 85, 87, 101, 71, 117, 55, 133, 39, 149, 23, 172, 187, 203, 204, 189, 174, 150, 38, 149, 70, 133, 86, 117, 87, 101, 102, 101, 118, 85, 134, 69, 134, 0, 32, 16, 38, 10, 240, 86, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 70, 0, 14, 32, 71, 37, 0, 60, 22, 70, 134, 118, 42, 58, 102, 27, 44, 86, 18, 58, 71, 71, 104, 102, 71, 103, 118, 70, 118, 134, 70, 118, 134, 70, 118, 134, 70, 118, 134, 70, 118, 134, 70, 118, 134, 70, 118, 134, 70, 118, 134, 70, 118, 134, 70, 118, 134, 70, 118, 134, 70, 118, 134, 70, 118, 134, 70, 118, 134, 70, 118, 134, 0, 51, 48, 50, 23, 0, 37, 54, 70, 118, 42, 86, 27, 86, 18, 55, 71, 102, 71, 102, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 0, 32, 16, 45, 26, 0, 43, 24, 254, 191, 1, 150, 102, 118, 134, 102, 134, 101, 165, 86, 166, 70, 166, 70, 166, 70, 166, 70, 166, 70, 166, 70, 166, 86, 135, 86, 134, 104, 87, 127, 3, 159, 1, 190, 248, 0, 37, 16, 67, 24, 0, 37, 37, 150, 41, 118, 27, 111, 4, 88, 71, 86, 118, 86, 119, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 118, 86, 118, 87, 71, 111, 2, 118, 25, 134, 38, 166, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 0, 8, 32, 69, 24, 0, 36, 101, 69, 137, 22, 127, 2, 111, 3, 88, 56, 86, 103, 86, 118, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 70, 134, 86, 118, 86, 103, 102, 72, 111, 3, 122, 22, 150, 54, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 240, 54, 0, 6, 64, 32, 17, 0, 27, 86, 67, 70, 37, 70, 22, 70, 22, 74, 120, 151, 167, 166, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 0, 24, 96, 34, 19, 0, 29, 8, 156, 109, 101, 68, 85, 114, 85, 229, 231, 203, 156, 140, 139, 170, 214, 244, 81, 148, 67, 132, 69, 85, 78, 94, 123, 167, 0, 27, 16, 35, 20, 0, 17, 118, 230, 230, 230, 230, 230, 191, 95, 95, 134, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 231, 51, 125, 140, 138, 197, 0, 28, 80, 50, 23, 0, 37, 54, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 118, 70, 103, 70, 103, 71, 72, 91, 22, 105, 37, 135, 0, 30, 48, 43, 24, 0, 39, 5, 165, 70, 149, 70, 134, 85, 133, 101, 133, 102, 102, 117, 101, 133, 101, 134, 70, 149, 69, 165, 69, 166, 38, 166, 38, 181, 37, 204, 204, 218, 234, 234, 248, 240, 24, 0, 34, 32, 71, 35, 0, 56, 117, 147, 149, 69, 133, 133, 70, 117, 118, 85, 102, 117, 101, 103, 101, 102, 87, 101, 102, 87, 86, 117, 67, 21, 69, 133, 67, 21, 69, 134, 51, 21, 69, 134, 36, 21, 53, 165, 36, 37, 37, 165, 35, 53, 37, 166, 19, 53, 22, 185, 53, 21, 201, 74, 200, 90, 200, 90, 215, 89, 230, 120, 245, 119, 0, 49, 48, 45, 24, 0, 39, 6, 133, 86, 118, 102, 86, 134, 70, 150, 38, 188, 203, 233, 240, 24, 240, 38, 240, 54, 240, 39, 240, 40, 250, 213, 37, 182, 38, 150, 69, 149, 101, 118, 102, 86, 134, 69, 165, 0, 33, 64, 61, 24, 0, 39, 5, 165, 70, 149, 70, 134, 86, 117, 102, 117, 118, 86, 118, 85, 149, 70, 150, 54, 165, 53, 182, 37, 182, 21, 213, 21, 219, 233, 249, 240, 24, 240, 23, 240, 54, 240, 54, 240, 53, 240, 69, 240, 69, 240, 68, 240, 69, 194, 69, 219, 218, 233, 240, 22, 0, 8, 16, 34, 22, 0, 35, 127, 2, 95, 2, 95, 2, 246, 247, 231, 246, 246, 247, 231, 246, 246, 247, 246, 246, 246, 247, 246, 255, 3, 79, 3, 79, 3, 0, 30, 96, 13, 29, 0, 72, 79, 10, 79, 10, 79, 10, 0, 80, 32, 22, 54, 0, 127, 0, 8, 15, 15, 15, 5, 79, 15, 15, 5, 79, 15, 15, 5, 0, 127, 0, 22, 21, 19, 240, 240, 150, 38, 85, 53, 101, 53, 85, 68, 100, 69, 100, 68, 115, 83, 0, 86, 64, 19, 20, 240, 240, 212, 99, 103, 67, 90, 20, 68, 26, 83, 72, 83, 100, 0, 93, 48, }; //***************************************************************************** // // The font definition for the 46 point Cmss bold font. // //***************************************************************************** const tFont g_sFontCmss46b = { // // The format of the font. // FONT_FMT_PIXEL_RLE, // // The maximum width of the font. // 49, // // The height of the font. // 45, // // The baseline of the font. // 34, // // The offset to each character in the font. // { 0, 5, 42, 71, 200, 270, 394, 487, 504, 552, 600, 652, 755, 773, 782, 795, 889, 960, 1004, 1073, 1139, 1209, 1277, 1344, 1417, 1482, 1549, 1570, 1596, 1633, 1665, 1722, 1771, 1855, 1935, 2006, 2077, 2164, 2235, 2305, 2377, 2448, 2486, 2529, 2604, 2675, 2792, 2881, 2967, 3037, 3141, 3212, 3277, 3347, 3419, 3501, 3623, 3700, 3774, 3846, 3894, 3923, 3971, 3988, 3998, 4015, 4063, 4134, 4179, 4248, 4293, 4334, 4397, 4468, 4503, 4549, 4614, 4652, 4723, 4773, 4818, 4885, 4954, 4986, 5020, 5055, 5105, 5148, 5219, 5264, 5325, 5359, 5372, 5394, 5415, }, // // A pointer to the actual font data // g_pucCmss46bData };
vastsoun/bbmc-starterware
grlib/fonts/fontcmss46b.c
C
bsd-3-clause
32,274
#include <omp.h> #include <math.h> #define ceild(n,d) ceil(((double)(n))/((double)(d))) #define floord(n,d) floor(((double)(n))/((double)(d))) #define max(x,y) ((x) > (y)? (x) : (y)) #define min(x,y) ((x) < (y)? (x) : (y)) /* * Order-1, 3D 7 point stencil * Adapted from PLUTO and Pochoir test bench * * Tareq Malas */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #ifdef LIKWID_PERFMON #include <likwid.h> #endif #include "print_utils.h" #define TESTS 2 #define MAX(a,b) ((a) > (b) ? a : b) #define MIN(a,b) ((a) < (b) ? a : b) /* Subtract the `struct timeval' values X and Y, * storing the result in RESULT. * * Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. * tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } int main(int argc, char *argv[]) { int t, i, j, k, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+2; Ny = atoi(argv[2])+2; Nz = atoi(argv[3])+2; } if (argc > 4) Nt = atoi(argv[4]); double ****A = (double ****) malloc(sizeof(double***)*2); A[0] = (double ***) malloc(sizeof(double**)*Nz); A[1] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[0][i] = (double**) malloc(sizeof(double*)*Ny); A[1][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[0][i][j] = (double*) malloc(sizeof(double)*Nx); A[1][i][j] = (double*) malloc(sizeof(double)*Nx); } } // tile size information, including extra element to decide the list length int *tile_size = (int*) malloc(sizeof(int)); tile_size[0] = -1; // The list is modified here before source-to-source transformations tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5); tile_size[0] = 4; tile_size[1] = 4; tile_size[2] = 8; tile_size[3] = 64; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; const double alpha = 0.0876; const double beta = 0.0765; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); } } } #ifdef LIKWID_PERFMON LIKWID_MARKER_INIT; #pragma omp parallel { LIKWID_MARKER_THREADINIT; #pragma omp barrier LIKWID_MARKER_START("calc"); } #endif int num_threads = 1; #if defined(_OPENMP) num_threads = omp_get_max_threads(); #endif for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 /* Copyright (C) 1991-2014 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C 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. The GNU C 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 the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ /* This header is separate from features.h so that the compiler can include it implicitly at the start of every compilation. It must not itself include <features.h> or any other header that includes <features.h> because the implicit include comes before any feature test macros that may be defined in a source file before it first explicitly includes a system header. GCC knows the name of this header in order to preinclude it. */ /* glibc's intent is to support the IEC 559 math functionality, real and complex. If the GCC (4.9 and later) predefined macros specifying compiler intent are available, use them to determine whether the overall intent is to support these features; otherwise, presume an older compiler has intent to support these features and define these macros by default. */ /* wchar_t uses ISO/IEC 10646 (2nd ed., published 2011-03-15) / Unicode 6.0. */ /* We do not support C11 <threads.h>. */ int t1, t2, t3, t4, t5, t6, t7, t8; int lb, ub, lbp, ubp, lb2, ub2; register int lbv, ubv; /* Start of CLooG code */ if ((Nt >= 2) && (Nx >= 3) && (Ny >= 3) && (Nz >= 3)) { for (t1=-1;t1<=floord(Nt-2,2);t1++) { lbp=max(ceild(t1,2),ceild(4*t1-Nt+3,4)); ubp=min(floord(Nt+Nz-4,4),floord(2*t1+Nz-1,4)); #pragma omp parallel for private(lbv,ubv,t3,t4,t5,t6,t7,t8) for (t2=lbp;t2<=ubp;t2++) { for (t3=max(max(0,ceild(t1-3,4)),ceild(4*t2-Nz-4,8));t3<=min(min(min(floord(4*t2+Ny,8),floord(Nt+Ny-4,8)),floord(2*t1+Ny+1,8)),floord(4*t1-4*t2+Nz+Ny-1,8));t3++) { for (t4=max(max(max(0,ceild(t1-31,32)),ceild(4*t2-Nz-60,64)),ceild(8*t3-Ny-60,64));t4<=min(min(min(min(floord(4*t2+Nx,64),floord(Nt+Nx-4,64)),floord(2*t1+Nx+1,64)),floord(8*t3+Nx+4,64)),floord(4*t1-4*t2+Nz+Nx-1,64));t4++) { for (t5=max(max(max(max(max(0,2*t1),4*t1-4*t2+1),4*t2-Nz+2),8*t3-Ny+2),64*t4-Nx+2);t5<=min(min(min(min(min(Nt-2,2*t1+3),4*t2+2),8*t3+6),64*t4+62),4*t1-4*t2+Nz+1);t5++) { for (t6=max(max(4*t2,t5+1),-4*t1+4*t2+2*t5-3);t6<=min(min(4*t2+3,-4*t1+4*t2+2*t5),t5+Nz-2);t6++) { for (t7=max(8*t3,t5+1);t7<=min(8*t3+7,t5+Ny-2);t7++) { lbv=max(64*t4,t5+1); ubv=min(64*t4+63,t5+Nx-2); #pragma ivdep #pragma vector always for (t8=lbv;t8<=ubv;t8++) { A[( t5 + 1) % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] = ((alpha * A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)]) + (beta * (((((A[ t5 % 2][ (-t5+t6) - 1][ (-t5+t7)][ (-t5+t8)] + A[ t5 % 2][ (-t5+t6)][ (-t5+t7) - 1][ (-t5+t8)]) + A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8) - 1]) + A[ t5 % 2][ (-t5+t6) + 1][ (-t5+t7)][ (-t5+t8)]) + A[ t5 % 2][ (-t5+t6)][ (-t5+t7) + 1][ (-t5+t8)]) + A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8) + 1])));; } } } } } } } } } /* End of CLooG code */ gettimeofday(&end, 0); ts_return = timeval_subtract(&result, &end, &start); tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6); min_tdiff = min(min_tdiff, tdiff); printf("Rank 0 TEST# %d time: %f\n", test, tdiff); } PRINT_RESULTS(1, "constant") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays (Causing performance degradation /* for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(A[0][i][j]); free(A[1][i][j]); } free(A[0][i]); free(A[1][i]); } free(A[0]); free(A[1]); */ return 0; }
tareqmalas/girih
pluto_examples/gen_kernels/lbpar_3d7pt4_4_8_64/3d7pt.lbpar.c
C
bsd-3-clause
7,590
/* * Copyright © 2018-2019, VideoLAN and dav1d authors * Copyright © 2018-2019, Two Orioles, LLC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include <stddef.h> #include <stdint.h> #include <string.h> #include "common/attributes.h" #include "common/intops.h" #include "src/itx.h" #include "src/itx_1d.h" static NOINLINE void inv_txfm_add_c(pixel *dst, const ptrdiff_t stride, coef *const coeff, const int eob, const int w, const int h, const int shift, const itx_1d_fn first_1d_fn, const itx_1d_fn second_1d_fn, const int has_dconly HIGHBD_DECL_SUFFIX) { assert(w >= 4 && w <= 64); assert(h >= 4 && h <= 64); assert(eob >= 0); const int is_rect2 = w * 2 == h || h * 2 == w; const int rnd = (1 << shift) >> 1; if (eob < has_dconly) { int dc = coeff[0]; coeff[0] = 0; if (is_rect2) dc = (dc * 181 + 128) >> 8; dc = (dc * 181 + 128) >> 8; dc = (dc + rnd) >> shift; dc = (dc * 181 + 128 + 2048) >> 12; for (int y = 0; y < h; y++, dst += PXSTRIDE(stride)) for (int x = 0; x < w; x++) dst[x] = iclip_pixel(dst[x] + dc); return; } const int sh = imin(h, 32), sw = imin(w, 32); #if BITDEPTH == 8 const int row_clip_min = INT16_MIN; const int col_clip_min = INT16_MIN; #else const int row_clip_min = (int) ((unsigned) ~bitdepth_max << 7); const int col_clip_min = (int) ((unsigned) ~bitdepth_max << 5); #endif const int row_clip_max = ~row_clip_min; const int col_clip_max = ~col_clip_min; int32_t tmp[64 * 64], *c = tmp; for (int y = 0; y < sh; y++, c += w) { if (is_rect2) for (int x = 0; x < sw; x++) c[x] = (coeff[y + x * sh] * 181 + 128) >> 8; else for (int x = 0; x < sw; x++) c[x] = coeff[y + x * sh]; first_1d_fn(c, 1, row_clip_min, row_clip_max); } memset(coeff, 0, sizeof(*coeff) * sw * sh); for (int i = 0; i < w * sh; i++) tmp[i] = iclip((tmp[i] + rnd) >> shift, col_clip_min, col_clip_max); for (int x = 0; x < w; x++) second_1d_fn(&tmp[x], w, col_clip_min, col_clip_max); c = tmp; for (int y = 0; y < h; y++, dst += PXSTRIDE(stride)) for (int x = 0; x < w; x++) dst[x] = iclip_pixel(dst[x] + ((*c++ + 8) >> 4)); } #define inv_txfm_fn(type1, type2, w, h, shift, has_dconly) \ static void \ inv_txfm_add_##type1##_##type2##_##w##x##h##_c(pixel *dst, \ const ptrdiff_t stride, \ coef *const coeff, \ const int eob \ HIGHBD_DECL_SUFFIX) \ { \ inv_txfm_add_c(dst, stride, coeff, eob, w, h, shift, \ dav1d_inv_##type1##w##_1d_c, dav1d_inv_##type2##h##_1d_c, \ has_dconly HIGHBD_TAIL_SUFFIX); \ } #define inv_txfm_fn64(w, h, shift) \ inv_txfm_fn(dct, dct, w, h, shift, 1) #define inv_txfm_fn32(w, h, shift) \ inv_txfm_fn64(w, h, shift) \ inv_txfm_fn(identity, identity, w, h, shift, 0) #define inv_txfm_fn16(w, h, shift) \ inv_txfm_fn32(w, h, shift) \ inv_txfm_fn(adst, dct, w, h, shift, 0) \ inv_txfm_fn(dct, adst, w, h, shift, 0) \ inv_txfm_fn(adst, adst, w, h, shift, 0) \ inv_txfm_fn(dct, flipadst, w, h, shift, 0) \ inv_txfm_fn(flipadst, dct, w, h, shift, 0) \ inv_txfm_fn(adst, flipadst, w, h, shift, 0) \ inv_txfm_fn(flipadst, adst, w, h, shift, 0) \ inv_txfm_fn(flipadst, flipadst, w, h, shift, 0) \ inv_txfm_fn(identity, dct, w, h, shift, 0) \ inv_txfm_fn(dct, identity, w, h, shift, 0) \ #define inv_txfm_fn84(w, h, shift) \ inv_txfm_fn16(w, h, shift) \ inv_txfm_fn(identity, flipadst, w, h, shift, 0) \ inv_txfm_fn(flipadst, identity, w, h, shift, 0) \ inv_txfm_fn(identity, adst, w, h, shift, 0) \ inv_txfm_fn(adst, identity, w, h, shift, 0) \ inv_txfm_fn84( 4, 4, 0) inv_txfm_fn84( 4, 8, 0) inv_txfm_fn84( 4, 16, 1) inv_txfm_fn84( 8, 4, 0) inv_txfm_fn84( 8, 8, 1) inv_txfm_fn84( 8, 16, 1) inv_txfm_fn32( 8, 32, 2) inv_txfm_fn84(16, 4, 1) inv_txfm_fn84(16, 8, 1) inv_txfm_fn16(16, 16, 2) inv_txfm_fn32(16, 32, 1) inv_txfm_fn64(16, 64, 2) inv_txfm_fn32(32, 8, 2) inv_txfm_fn32(32, 16, 1) inv_txfm_fn32(32, 32, 2) inv_txfm_fn64(32, 64, 1) inv_txfm_fn64(64, 16, 2) inv_txfm_fn64(64, 32, 1) inv_txfm_fn64(64, 64, 2) static void inv_txfm_add_wht_wht_4x4_c(pixel *dst, const ptrdiff_t stride, coef *const coeff, const int eob HIGHBD_DECL_SUFFIX) { int32_t tmp[4 * 4], *c = tmp; for (int y = 0; y < 4; y++, c += 4) { for (int x = 0; x < 4; x++) c[x] = coeff[y + x * 4] >> 2; dav1d_inv_wht4_1d_c(c, 1); } memset(coeff, 0, sizeof(*coeff) * 4 * 4); for (int x = 0; x < 4; x++) dav1d_inv_wht4_1d_c(&tmp[x], 4); c = tmp; for (int y = 0; y < 4; y++, dst += PXSTRIDE(stride)) for (int x = 0; x < 4; x++) dst[x] = iclip_pixel(dst[x] + *c++); } COLD void bitfn(dav1d_itx_dsp_init)(Dav1dInvTxfmDSPContext *const c) { #define assign_itx_all_fn64(w, h, pfx) \ c->itxfm_add[pfx##TX_##w##X##h][DCT_DCT ] = \ inv_txfm_add_dct_dct_##w##x##h##_c #define assign_itx_all_fn32(w, h, pfx) \ assign_itx_all_fn64(w, h, pfx); \ c->itxfm_add[pfx##TX_##w##X##h][IDTX] = \ inv_txfm_add_identity_identity_##w##x##h##_c #define assign_itx_all_fn16(w, h, pfx) \ assign_itx_all_fn32(w, h, pfx); \ c->itxfm_add[pfx##TX_##w##X##h][DCT_ADST ] = \ inv_txfm_add_adst_dct_##w##x##h##_c; \ c->itxfm_add[pfx##TX_##w##X##h][ADST_DCT ] = \ inv_txfm_add_dct_adst_##w##x##h##_c; \ c->itxfm_add[pfx##TX_##w##X##h][ADST_ADST] = \ inv_txfm_add_adst_adst_##w##x##h##_c; \ c->itxfm_add[pfx##TX_##w##X##h][ADST_FLIPADST] = \ inv_txfm_add_flipadst_adst_##w##x##h##_c; \ c->itxfm_add[pfx##TX_##w##X##h][FLIPADST_ADST] = \ inv_txfm_add_adst_flipadst_##w##x##h##_c; \ c->itxfm_add[pfx##TX_##w##X##h][DCT_FLIPADST] = \ inv_txfm_add_flipadst_dct_##w##x##h##_c; \ c->itxfm_add[pfx##TX_##w##X##h][FLIPADST_DCT] = \ inv_txfm_add_dct_flipadst_##w##x##h##_c; \ c->itxfm_add[pfx##TX_##w##X##h][FLIPADST_FLIPADST] = \ inv_txfm_add_flipadst_flipadst_##w##x##h##_c; \ c->itxfm_add[pfx##TX_##w##X##h][H_DCT] = \ inv_txfm_add_dct_identity_##w##x##h##_c; \ c->itxfm_add[pfx##TX_##w##X##h][V_DCT] = \ inv_txfm_add_identity_dct_##w##x##h##_c #define assign_itx_all_fn84(w, h, pfx) \ assign_itx_all_fn16(w, h, pfx); \ c->itxfm_add[pfx##TX_##w##X##h][H_FLIPADST] = \ inv_txfm_add_flipadst_identity_##w##x##h##_c; \ c->itxfm_add[pfx##TX_##w##X##h][V_FLIPADST] = \ inv_txfm_add_identity_flipadst_##w##x##h##_c; \ c->itxfm_add[pfx##TX_##w##X##h][H_ADST] = \ inv_txfm_add_adst_identity_##w##x##h##_c; \ c->itxfm_add[pfx##TX_##w##X##h][V_ADST] = \ inv_txfm_add_identity_adst_##w##x##h##_c; \ memset(c, 0, sizeof(*c)); /* Zero unused function pointer elements. */ c->itxfm_add[TX_4X4][WHT_WHT] = inv_txfm_add_wht_wht_4x4_c; assign_itx_all_fn84( 4, 4, ); assign_itx_all_fn84( 4, 8, R); assign_itx_all_fn84( 4, 16, R); assign_itx_all_fn84( 8, 4, R); assign_itx_all_fn84( 8, 8, ); assign_itx_all_fn84( 8, 16, R); assign_itx_all_fn32( 8, 32, R); assign_itx_all_fn84(16, 4, R); assign_itx_all_fn84(16, 8, R); assign_itx_all_fn16(16, 16, ); assign_itx_all_fn32(16, 32, R); assign_itx_all_fn64(16, 64, R); assign_itx_all_fn32(32, 8, R); assign_itx_all_fn32(32, 16, R); assign_itx_all_fn32(32, 32, ); assign_itx_all_fn64(32, 64, R); assign_itx_all_fn64(64, 16, R); assign_itx_all_fn64(64, 32, R); assign_itx_all_fn64(64, 64, ); #if HAVE_ASM #if ARCH_AARCH64 || ARCH_ARM bitfn(dav1d_itx_dsp_init_arm)(c); #endif #if ARCH_X86 bitfn(dav1d_itx_dsp_init_x86)(c); #endif #endif }
endlessm/chromium-browser
third_party/dav1d/libdav1d/src/itx_tmpl.c
C
bsd-3-clause
9,450
/* Copyright (c) 2007-2016, The Tor Project, Inc. */ /* See LICENSE for licensing information */ /** * \file geoip.c * \brief Functions related to maintaining an IP-to-country database; * to summarizing client connections by country to entry guards, bridges, * and directory servers; and for statistics on answering network status * requests. * * There are two main kinds of functions in this module: geoip functions, * which map groups of IPv4 and IPv6 addresses to country codes, and * statistical functions, which collect statistics about different kinds of * per-country usage. * * The geoip lookup tables are implemented as sorted lists of disjoint address * ranges, each mapping to a singleton geoip_country_t. These country objects * are also indexed by their names in a hashtable. * * The tables are populated from disk at startup by the geoip_load_file() * function. For more information on the file format they read, see that * function. See the scripts and the README file in src/config for more * information about how those files are generated. * * Tor uses GeoIP information in order to implement user requests (such as * ExcludeNodes {cc}), and to keep track of how much usage relays are getting * for each country. */ #define GEOIP_PRIVATE #include "or.h" #include "ht.h" #include "config.h" #include "control.h" #include "dnsserv.h" #include "geoip.h" #include "routerlist.h" static void init_geoip_countries(void); /** An entry from the GeoIP IPv4 file: maps an IPv4 range to a country. */ typedef struct geoip_ipv4_entry_t { uint32_t ip_low; /**< The lowest IP in the range, in host order */ uint32_t ip_high; /**< The highest IP in the range, in host order */ intptr_t country; /**< An index into geoip_countries */ } geoip_ipv4_entry_t; /** An entry from the GeoIP IPv6 file: maps an IPv6 range to a country. */ typedef struct geoip_ipv6_entry_t { struct in6_addr ip_low; /**< The lowest IP in the range, in host order */ struct in6_addr ip_high; /**< The highest IP in the range, in host order */ intptr_t country; /**< An index into geoip_countries */ } geoip_ipv6_entry_t; /** A per-country record for GeoIP request history. */ typedef struct geoip_country_t { char countrycode[3]; uint32_t n_v3_ns_requests; } geoip_country_t; /** A list of geoip_country_t */ static smartlist_t *geoip_countries = NULL; /** A map from lowercased country codes to their position in geoip_countries. * The index is encoded in the pointer, and 1 is added so that NULL can mean * not found. */ static strmap_t *country_idxplus1_by_lc_code = NULL; /** Lists of all known geoip_ipv4_entry_t and geoip_ipv6_entry_t, sorted * by their respective ip_low. */ static smartlist_t *geoip_ipv4_entries = NULL, *geoip_ipv6_entries = NULL; /** SHA1 digest of the GeoIP files to include in extra-info descriptors. */ static char geoip_digest[DIGEST_LEN]; static char geoip6_digest[DIGEST_LEN]; /** Return the index of the <b>country</b>'s entry in the GeoIP * country list if it is a valid 2-letter country code, otherwise * return -1. */ MOCK_IMPL(country_t, geoip_get_country,(const char *country)) { void *idxplus1_; intptr_t idx; idxplus1_ = strmap_get_lc(country_idxplus1_by_lc_code, country); if (!idxplus1_) return -1; idx = ((uintptr_t)idxplus1_)-1; return (country_t)idx; } /** Add an entry to a GeoIP table, mapping all IP addresses between <b>low</b> * and <b>high</b>, inclusive, to the 2-letter country code <b>country</b>. */ static void geoip_add_entry(const tor_addr_t *low, const tor_addr_t *high, const char *country) { intptr_t idx; void *idxplus1_; IF_BUG_ONCE(tor_addr_family(low) != tor_addr_family(high)) return; IF_BUG_ONCE(tor_addr_compare(high, low, CMP_EXACT) < 0) return; idxplus1_ = strmap_get_lc(country_idxplus1_by_lc_code, country); if (!idxplus1_) { geoip_country_t *c = tor_malloc_zero(sizeof(geoip_country_t)); strlcpy(c->countrycode, country, sizeof(c->countrycode)); tor_strlower(c->countrycode); smartlist_add(geoip_countries, c); idx = smartlist_len(geoip_countries) - 1; strmap_set_lc(country_idxplus1_by_lc_code, country, (void*)(idx+1)); } else { idx = ((uintptr_t)idxplus1_)-1; } { geoip_country_t *c = smartlist_get(geoip_countries, idx); tor_assert(!strcasecmp(c->countrycode, country)); } if (tor_addr_family(low) == AF_INET) { geoip_ipv4_entry_t *ent = tor_malloc_zero(sizeof(geoip_ipv4_entry_t)); ent->ip_low = tor_addr_to_ipv4h(low); ent->ip_high = tor_addr_to_ipv4h(high); ent->country = idx; smartlist_add(geoip_ipv4_entries, ent); } else if (tor_addr_family(low) == AF_INET6) { geoip_ipv6_entry_t *ent = tor_malloc_zero(sizeof(geoip_ipv6_entry_t)); ent->ip_low = *tor_addr_to_in6_assert(low); ent->ip_high = *tor_addr_to_in6_assert(high); ent->country = idx; smartlist_add(geoip_ipv6_entries, ent); } } /** Add an entry to the GeoIP table indicated by <b>family</b>, * parsing it from <b>line</b>. The format is as for geoip_load_file(). */ STATIC int geoip_parse_entry(const char *line, sa_family_t family) { tor_addr_t low_addr, high_addr; char c[3]; char *country = NULL; if (!geoip_countries) init_geoip_countries(); if (family == AF_INET) { if (!geoip_ipv4_entries) geoip_ipv4_entries = smartlist_new(); } else if (family == AF_INET6) { if (!geoip_ipv6_entries) geoip_ipv6_entries = smartlist_new(); } else { log_warn(LD_GENERAL, "Unsupported family: %d", family); return -1; } while (TOR_ISSPACE(*line)) ++line; if (*line == '#') return 0; char buf[512]; if (family == AF_INET) { unsigned int low, high; if (tor_sscanf(line,"%u,%u,%2s", &low, &high, c) == 3 || tor_sscanf(line,"\"%u\",\"%u\",\"%2s\",", &low, &high, c) == 3) { tor_addr_from_ipv4h(&low_addr, low); tor_addr_from_ipv4h(&high_addr, high); } else goto fail; country = c; } else { /* AF_INET6 */ char *low_str, *high_str; struct in6_addr low, high; char *strtok_state; strlcpy(buf, line, sizeof(buf)); low_str = tor_strtok_r(buf, ",", &strtok_state); if (!low_str) goto fail; high_str = tor_strtok_r(NULL, ",", &strtok_state); if (!high_str) goto fail; country = tor_strtok_r(NULL, "\n", &strtok_state); if (!country) goto fail; if (strlen(country) != 2) goto fail; if (tor_inet_pton(AF_INET6, low_str, &low) <= 0) goto fail; tor_addr_from_in6(&low_addr, &low); if (tor_inet_pton(AF_INET6, high_str, &high) <= 0) goto fail; tor_addr_from_in6(&high_addr, &high); } geoip_add_entry(&low_addr, &high_addr, country); return 0; fail: log_warn(LD_GENERAL, "Unable to parse line from GEOIP %s file: %s", family == AF_INET ? "IPv4" : "IPv6", escaped(line)); return -1; } /** Sorting helper: return -1, 1, or 0 based on comparison of two * geoip_ipv4_entry_t */ static int geoip_ipv4_compare_entries_(const void **_a, const void **_b) { const geoip_ipv4_entry_t *a = *_a, *b = *_b; if (a->ip_low < b->ip_low) return -1; else if (a->ip_low > b->ip_low) return 1; else return 0; } /** bsearch helper: return -1, 1, or 0 based on comparison of an IP (a pointer * to a uint32_t in host order) to a geoip_ipv4_entry_t */ static int geoip_ipv4_compare_key_to_entry_(const void *_key, const void **_member) { /* No alignment issue here, since _key really is a pointer to uint32_t */ const uint32_t addr = *(uint32_t *)_key; const geoip_ipv4_entry_t *entry = *_member; if (addr < entry->ip_low) return -1; else if (addr > entry->ip_high) return 1; else return 0; } /** Sorting helper: return -1, 1, or 0 based on comparison of two * geoip_ipv6_entry_t */ static int geoip_ipv6_compare_entries_(const void **_a, const void **_b) { const geoip_ipv6_entry_t *a = *_a, *b = *_b; return fast_memcmp(a->ip_low.s6_addr, b->ip_low.s6_addr, sizeof(struct in6_addr)); } /** bsearch helper: return -1, 1, or 0 based on comparison of an IPv6 * (a pointer to a in6_addr) to a geoip_ipv6_entry_t */ static int geoip_ipv6_compare_key_to_entry_(const void *_key, const void **_member) { const struct in6_addr *addr = (struct in6_addr *)_key; const geoip_ipv6_entry_t *entry = *_member; if (fast_memcmp(addr->s6_addr, entry->ip_low.s6_addr, sizeof(struct in6_addr)) < 0) return -1; else if (fast_memcmp(addr->s6_addr, entry->ip_high.s6_addr, sizeof(struct in6_addr)) > 0) return 1; else return 0; } /** Return 1 if we should collect geoip stats on bridge users, and * include them in our extrainfo descriptor. Else return 0. */ int should_record_bridge_info(const or_options_t *options) { return options->BridgeRelay && options->BridgeRecordUsageByCountry; } /** Set up a new list of geoip countries with no countries (yet) set in it, * except for the unknown country. */ static void init_geoip_countries(void) { geoip_country_t *geoip_unresolved; geoip_countries = smartlist_new(); /* Add a geoip_country_t for requests that could not be resolved to a * country as first element (index 0) to geoip_countries. */ geoip_unresolved = tor_malloc_zero(sizeof(geoip_country_t)); strlcpy(geoip_unresolved->countrycode, "??", sizeof(geoip_unresolved->countrycode)); smartlist_add(geoip_countries, geoip_unresolved); country_idxplus1_by_lc_code = strmap_new(); strmap_set_lc(country_idxplus1_by_lc_code, "??", (void*)(1)); } /** Clear appropriate GeoIP database, based on <b>family</b>, and * reload it from the file <b>filename</b>. Return 0 on success, -1 on * failure. * * Recognized line formats for IPv4 are: * INTIPLOW,INTIPHIGH,CC * and * "INTIPLOW","INTIPHIGH","CC","CC3","COUNTRY NAME" * where INTIPLOW and INTIPHIGH are IPv4 addresses encoded as 4-byte unsigned * integers, and CC is a country code. * * Recognized line format for IPv6 is: * IPV6LOW,IPV6HIGH,CC * where IPV6LOW and IPV6HIGH are IPv6 addresses and CC is a country code. * * It also recognizes, and skips over, blank lines and lines that start * with '#' (comments). */ int geoip_load_file(sa_family_t family, const char *filename) { FILE *f; const char *msg = ""; const or_options_t *options = get_options(); int severity = options_need_geoip_info(options, &msg) ? LOG_WARN : LOG_INFO; crypto_digest_t *geoip_digest_env = NULL; tor_assert(family == AF_INET || family == AF_INET6); if (!(f = tor_fopen_cloexec(filename, "r"))) { log_fn(severity, LD_GENERAL, "Failed to open GEOIP file %s. %s", filename, msg); return -1; } if (!geoip_countries) init_geoip_countries(); if (family == AF_INET) { if (geoip_ipv4_entries) { SMARTLIST_FOREACH(geoip_ipv4_entries, geoip_ipv4_entry_t *, e, tor_free(e)); smartlist_free(geoip_ipv4_entries); } geoip_ipv4_entries = smartlist_new(); } else { /* AF_INET6 */ if (geoip_ipv6_entries) { SMARTLIST_FOREACH(geoip_ipv6_entries, geoip_ipv6_entry_t *, e, tor_free(e)); smartlist_free(geoip_ipv6_entries); } geoip_ipv6_entries = smartlist_new(); } geoip_digest_env = crypto_digest_new(); log_notice(LD_GENERAL, "Parsing GEOIP %s file %s.", (family == AF_INET) ? "IPv4" : "IPv6", filename); while (!feof(f)) { char buf[512]; if (fgets(buf, (int)sizeof(buf), f) == NULL) break; crypto_digest_add_bytes(geoip_digest_env, buf, strlen(buf)); /* FFFF track full country name. */ geoip_parse_entry(buf, family); } /*XXXX abort and return -1 if no entries/illformed?*/ fclose(f); /* Sort list and remember file digests so that we can include it in * our extra-info descriptors. */ if (family == AF_INET) { smartlist_sort(geoip_ipv4_entries, geoip_ipv4_compare_entries_); /* Okay, now we need to maybe change our mind about what is in * which country. We do this for IPv4 only since that's what we * store in node->country. */ refresh_all_country_info(); crypto_digest_get_digest(geoip_digest_env, geoip_digest, DIGEST_LEN); } else { /* AF_INET6 */ smartlist_sort(geoip_ipv6_entries, geoip_ipv6_compare_entries_); crypto_digest_get_digest(geoip_digest_env, geoip6_digest, DIGEST_LEN); } crypto_digest_free(geoip_digest_env); return 0; } /** Given an IP address in host order, return a number representing the * country to which that address belongs, -1 for "No geoip information * available", or 0 for the 'unknown country'. The return value will always * be less than geoip_get_n_countries(). To decode it, call * geoip_get_country_name(). */ STATIC int geoip_get_country_by_ipv4(uint32_t ipaddr) { geoip_ipv4_entry_t *ent; if (!geoip_ipv4_entries) return -1; ent = smartlist_bsearch(geoip_ipv4_entries, &ipaddr, geoip_ipv4_compare_key_to_entry_); return ent ? (int)ent->country : 0; } /** Given an IPv6 address, return a number representing the country to * which that address belongs, -1 for "No geoip information available", or * 0 for the 'unknown country'. The return value will always be less than * geoip_get_n_countries(). To decode it, call geoip_get_country_name(). */ STATIC int geoip_get_country_by_ipv6(const struct in6_addr *addr) { geoip_ipv6_entry_t *ent; if (!geoip_ipv6_entries) return -1; ent = smartlist_bsearch(geoip_ipv6_entries, addr, geoip_ipv6_compare_key_to_entry_); return ent ? (int)ent->country : 0; } /** Given an IP address, return a number representing the country to which * that address belongs, -1 for "No geoip information available", or 0 for * the 'unknown country'. The return value will always be less than * geoip_get_n_countries(). To decode it, call geoip_get_country_name(). */ MOCK_IMPL(int, geoip_get_country_by_addr,(const tor_addr_t *addr)) { if (tor_addr_family(addr) == AF_INET) { return geoip_get_country_by_ipv4(tor_addr_to_ipv4h(addr)); } else if (tor_addr_family(addr) == AF_INET6) { return geoip_get_country_by_ipv6(tor_addr_to_in6(addr)); } else { return -1; } } /** Return the number of countries recognized by the GeoIP country list. */ MOCK_IMPL(int, geoip_get_n_countries,(void)) { if (!geoip_countries) init_geoip_countries(); return (int) smartlist_len(geoip_countries); } /** Return the two-letter country code associated with the number <b>num</b>, * or "??" for an unknown value. */ const char * geoip_get_country_name(country_t num) { if (geoip_countries && num >= 0 && num < smartlist_len(geoip_countries)) { geoip_country_t *c = smartlist_get(geoip_countries, num); return c->countrycode; } else return "??"; } /** Return true iff we have loaded a GeoIP database.*/ MOCK_IMPL(int, geoip_is_loaded,(sa_family_t family)) { tor_assert(family == AF_INET || family == AF_INET6); if (geoip_countries == NULL) return 0; if (family == AF_INET) return geoip_ipv4_entries != NULL; else /* AF_INET6 */ return geoip_ipv6_entries != NULL; } /** Return the hex-encoded SHA1 digest of the loaded GeoIP file. The * result does not need to be deallocated, but will be overwritten by the * next call of hex_str(). */ const char * geoip_db_digest(sa_family_t family) { tor_assert(family == AF_INET || family == AF_INET6); if (family == AF_INET) return hex_str(geoip_digest, DIGEST_LEN); else /* AF_INET6 */ return hex_str(geoip6_digest, DIGEST_LEN); } /** Entry in a map from IP address to the last time we've seen an incoming * connection from that IP address. Used by bridges only, to track which * countries have them blocked. */ typedef struct clientmap_entry_t { HT_ENTRY(clientmap_entry_t) node; tor_addr_t addr; /* Name of pluggable transport used by this client. NULL if no pluggable transport was used. */ char *transport_name; /** Time when we last saw this IP address, in MINUTES since the epoch. * * (This will run out of space around 4011 CE. If Tor is still in use around * 4000 CE, please remember to add more bits to last_seen_in_minutes.) */ unsigned int last_seen_in_minutes:30; unsigned int action:2; } clientmap_entry_t; /** Largest allowable value for last_seen_in_minutes. (It's a 30-bit field, * so it can hold up to (1u<<30)-1, or 0x3fffffffu. */ #define MAX_LAST_SEEN_IN_MINUTES 0X3FFFFFFFu /** Map from client IP address to last time seen. */ static HT_HEAD(clientmap, clientmap_entry_t) client_history = HT_INITIALIZER(); /** Hashtable helper: compute a hash of a clientmap_entry_t. */ static inline unsigned clientmap_entry_hash(const clientmap_entry_t *a) { unsigned h = (unsigned) tor_addr_hash(&a->addr); if (a->transport_name) h += (unsigned) siphash24g(a->transport_name, strlen(a->transport_name)); return h; } /** Hashtable helper: compare two clientmap_entry_t values for equality. */ static inline int clientmap_entries_eq(const clientmap_entry_t *a, const clientmap_entry_t *b) { if (strcmp_opt(a->transport_name, b->transport_name)) return 0; return !tor_addr_compare(&a->addr, &b->addr, CMP_EXACT) && a->action == b->action; } HT_PROTOTYPE(clientmap, clientmap_entry_t, node, clientmap_entry_hash, clientmap_entries_eq) HT_GENERATE2(clientmap, clientmap_entry_t, node, clientmap_entry_hash, clientmap_entries_eq, 0.6, tor_reallocarray_, tor_free_) /** Free all storage held by <b>ent</b>. */ static void clientmap_entry_free(clientmap_entry_t *ent) { if (!ent) return; tor_free(ent->transport_name); tor_free(ent); } /** Clear history of connecting clients used by entry and bridge stats. */ static void client_history_clear(void) { clientmap_entry_t **ent, **next, *this; for (ent = HT_START(clientmap, &client_history); ent != NULL; ent = next) { if ((*ent)->action == GEOIP_CLIENT_CONNECT) { this = *ent; next = HT_NEXT_RMV(clientmap, &client_history, ent); clientmap_entry_free(this); } else { next = HT_NEXT(clientmap, &client_history, ent); } } } /** Note that we've seen a client connect from the IP <b>addr</b> * at time <b>now</b>. Ignored by all but bridges and directories if * configured accordingly. */ void geoip_note_client_seen(geoip_client_action_t action, const tor_addr_t *addr, const char *transport_name, time_t now) { const or_options_t *options = get_options(); clientmap_entry_t lookup, *ent; memset(&lookup, 0, sizeof(clientmap_entry_t)); if (action == GEOIP_CLIENT_CONNECT) { /* Only remember statistics as entry guard or as bridge. */ if (!options->EntryStatistics && (!(options->BridgeRelay && options->BridgeRecordUsageByCountry))) return; } else { /* Only gather directory-request statistics if configured, and * forcibly disable them on bridge authorities. */ if (!options->DirReqStatistics || options->BridgeAuthoritativeDir) return; } log_debug(LD_GENERAL, "Seen client from '%s' with transport '%s'.", safe_str_client(fmt_addr((addr))), transport_name ? transport_name : "<no transport>"); tor_addr_copy(&lookup.addr, addr); lookup.action = (int)action; lookup.transport_name = (char*) transport_name; ent = HT_FIND(clientmap, &client_history, &lookup); if (! ent) { ent = tor_malloc_zero(sizeof(clientmap_entry_t)); tor_addr_copy(&ent->addr, addr); if (transport_name) ent->transport_name = tor_strdup(transport_name); ent->action = (int)action; HT_INSERT(clientmap, &client_history, ent); } if (now / 60 <= (int)MAX_LAST_SEEN_IN_MINUTES && now >= 0) ent->last_seen_in_minutes = (unsigned)(now/60); else ent->last_seen_in_minutes = 0; if (action == GEOIP_CLIENT_NETWORKSTATUS) { int country_idx = geoip_get_country_by_addr(addr); if (country_idx < 0) country_idx = 0; /** unresolved requests are stored at index 0. */ if (country_idx >= 0 && country_idx < smartlist_len(geoip_countries)) { geoip_country_t *country = smartlist_get(geoip_countries, country_idx); ++country->n_v3_ns_requests; } } } /** HT_FOREACH helper: remove a clientmap_entry_t from the hashtable if it's * older than a certain time. */ static int remove_old_client_helper_(struct clientmap_entry_t *ent, void *_cutoff) { time_t cutoff = *(time_t*)_cutoff / 60; if (ent->last_seen_in_minutes < cutoff) { clientmap_entry_free(ent); return 1; } else { return 0; } } /** Forget about all clients that haven't connected since <b>cutoff</b>. */ void geoip_remove_old_clients(time_t cutoff) { clientmap_HT_FOREACH_FN(&client_history, remove_old_client_helper_, &cutoff); } /** How many responses are we giving to clients requesting v3 network * statuses? */ static uint32_t ns_v3_responses[GEOIP_NS_RESPONSE_NUM]; /** Note that we've rejected a client's request for a v3 network status * for reason <b>reason</b> at time <b>now</b>. */ void geoip_note_ns_response(geoip_ns_response_t response) { static int arrays_initialized = 0; if (!get_options()->DirReqStatistics) return; if (!arrays_initialized) { memset(ns_v3_responses, 0, sizeof(ns_v3_responses)); arrays_initialized = 1; } tor_assert(response < GEOIP_NS_RESPONSE_NUM); ns_v3_responses[response]++; } /** Do not mention any country from which fewer than this number of IPs have * connected. This conceivably avoids reporting information that could * deanonymize users, though analysis is lacking. */ #define MIN_IPS_TO_NOTE_COUNTRY 1 /** Do not report any geoip data at all if we have fewer than this number of * IPs to report about. */ #define MIN_IPS_TO_NOTE_ANYTHING 1 /** When reporting geoip data about countries, round up to the nearest * multiple of this value. */ #define IP_GRANULARITY 8 /** Helper type: used to sort per-country totals by value. */ typedef struct c_hist_t { char country[3]; /**< Two-letter country code. */ unsigned total; /**< Total IP addresses seen in this country. */ } c_hist_t; /** Sorting helper: return -1, 1, or 0 based on comparison of two * geoip_ipv4_entry_t. Sort in descending order of total, and then by country * code. */ static int c_hist_compare_(const void **_a, const void **_b) { const c_hist_t *a = *_a, *b = *_b; if (a->total > b->total) return -1; else if (a->total < b->total) return 1; else return strcmp(a->country, b->country); } /** When there are incomplete directory requests at the end of a 24-hour * period, consider those requests running for longer than this timeout as * failed, the others as still running. */ #define DIRREQ_TIMEOUT (10*60) /** Entry in a map from either chan->global_identifier for direct requests * or a unique circuit identifier for tunneled requests to request time, * response size, and completion time of a network status request. Used to * measure download times of requests to derive average client * bandwidths. */ typedef struct dirreq_map_entry_t { HT_ENTRY(dirreq_map_entry_t) node; /** Unique identifier for this network status request; this is either the * chan->global_identifier of the dir channel (direct request) or a new * locally unique identifier of a circuit (tunneled request). This ID is * only unique among other direct or tunneled requests, respectively. */ uint64_t dirreq_id; unsigned int state:3; /**< State of this directory request. */ unsigned int type:1; /**< Is this a direct or a tunneled request? */ unsigned int completed:1; /**< Is this request complete? */ /** When did we receive the request and started sending the response? */ struct timeval request_time; size_t response_size; /**< What is the size of the response in bytes? */ struct timeval completion_time; /**< When did the request succeed? */ } dirreq_map_entry_t; /** Map of all directory requests asking for v2 or v3 network statuses in * the current geoip-stats interval. Values are * of type *<b>dirreq_map_entry_t</b>. */ static HT_HEAD(dirreqmap, dirreq_map_entry_t) dirreq_map = HT_INITIALIZER(); static int dirreq_map_ent_eq(const dirreq_map_entry_t *a, const dirreq_map_entry_t *b) { return a->dirreq_id == b->dirreq_id && a->type == b->type; } /* DOCDOC dirreq_map_ent_hash */ static unsigned dirreq_map_ent_hash(const dirreq_map_entry_t *entry) { unsigned u = (unsigned) entry->dirreq_id; u += entry->type << 20; return u; } HT_PROTOTYPE(dirreqmap, dirreq_map_entry_t, node, dirreq_map_ent_hash, dirreq_map_ent_eq) HT_GENERATE2(dirreqmap, dirreq_map_entry_t, node, dirreq_map_ent_hash, dirreq_map_ent_eq, 0.6, tor_reallocarray_, tor_free_) /** Helper: Put <b>entry</b> into map of directory requests using * <b>type</b> and <b>dirreq_id</b> as key parts. If there is * already an entry for that key, print out a BUG warning and return. */ static void dirreq_map_put_(dirreq_map_entry_t *entry, dirreq_type_t type, uint64_t dirreq_id) { dirreq_map_entry_t *old_ent; tor_assert(entry->type == type); tor_assert(entry->dirreq_id == dirreq_id); /* XXXX we could switch this to HT_INSERT some time, since it seems that * this bug doesn't happen. But since this function doesn't seem to be * critical-path, it's sane to leave it alone. */ old_ent = HT_REPLACE(dirreqmap, &dirreq_map, entry); if (old_ent && old_ent != entry) { log_warn(LD_BUG, "Error when putting directory request into local " "map. There was already an entry for the same identifier."); return; } } /** Helper: Look up and return an entry in the map of directory requests * using <b>type</b> and <b>dirreq_id</b> as key parts. If there * is no such entry, return NULL. */ static dirreq_map_entry_t * dirreq_map_get_(dirreq_type_t type, uint64_t dirreq_id) { dirreq_map_entry_t lookup; lookup.type = type; lookup.dirreq_id = dirreq_id; return HT_FIND(dirreqmap, &dirreq_map, &lookup); } /** Note that an either direct or tunneled (see <b>type</b>) directory * request for a v3 network status with unique ID <b>dirreq_id</b> of size * <b>response_size</b> has started. */ void geoip_start_dirreq(uint64_t dirreq_id, size_t response_size, dirreq_type_t type) { dirreq_map_entry_t *ent; if (!get_options()->DirReqStatistics) return; ent = tor_malloc_zero(sizeof(dirreq_map_entry_t)); ent->dirreq_id = dirreq_id; tor_gettimeofday(&ent->request_time); ent->response_size = response_size; ent->type = type; dirreq_map_put_(ent, type, dirreq_id); } /** Change the state of the either direct or tunneled (see <b>type</b>) * directory request with <b>dirreq_id</b> to <b>new_state</b> and * possibly mark it as completed. If no entry can be found for the given * key parts (e.g., if this is a directory request that we are not * measuring, or one that was started in the previous measurement period), * or if the state cannot be advanced to <b>new_state</b>, do nothing. */ void geoip_change_dirreq_state(uint64_t dirreq_id, dirreq_type_t type, dirreq_state_t new_state) { dirreq_map_entry_t *ent; if (!get_options()->DirReqStatistics) return; ent = dirreq_map_get_(type, dirreq_id); if (!ent) return; if (new_state == DIRREQ_IS_FOR_NETWORK_STATUS) return; if (new_state - 1 != ent->state) return; ent->state = new_state; if ((type == DIRREQ_DIRECT && new_state == DIRREQ_FLUSHING_DIR_CONN_FINISHED) || (type == DIRREQ_TUNNELED && new_state == DIRREQ_CHANNEL_BUFFER_FLUSHED)) { tor_gettimeofday(&ent->completion_time); ent->completed = 1; } } /** Return the bridge-ip-transports string that should be inserted in * our extra-info descriptor. Return NULL if the bridge-ip-transports * line should be empty. */ char * geoip_get_transport_history(void) { unsigned granularity = IP_GRANULARITY; /** String hash table (name of transport) -> (number of users). */ strmap_t *transport_counts = strmap_new(); /** Smartlist that contains copies of the names of the transports that have been used. */ smartlist_t *transports_used = smartlist_new(); /* Special string to signify that no transport was used for this connection. Pluggable transport names can't have symbols in their names, so this string will never collide with a real transport. */ static const char* no_transport_str = "<OR>"; clientmap_entry_t **ent; smartlist_t *string_chunks = smartlist_new(); char *the_string = NULL; /* If we haven't seen any clients yet, return NULL. */ if (HT_EMPTY(&client_history)) goto done; /** We do the following steps to form the transport history string: * a) Foreach client that uses a pluggable transport, we increase the * times that transport was used by one. If the client did not use * a transport, we increase the number of times someone connected * without obfuscation. * b) Foreach transport we observed, we write its transport history * string and push it to string_chunks. So, for example, if we've * seen 665 obfs2 clients, we write "obfs2=665". * c) We concatenate string_chunks to form the final string. */ log_debug(LD_GENERAL,"Starting iteration for transport history. %d clients.", HT_SIZE(&client_history)); /* Loop through all clients. */ HT_FOREACH(ent, clientmap, &client_history) { uintptr_t val; void *ptr; const char *transport_name = (*ent)->transport_name; if (!transport_name) transport_name = no_transport_str; /* Increase the count for this transport name. */ ptr = strmap_get(transport_counts, transport_name); val = (uintptr_t)ptr; val++; ptr = (void*)val; strmap_set(transport_counts, transport_name, ptr); /* If it's the first time we see this transport, note it. */ if (val == 1) smartlist_add_strdup(transports_used, transport_name); log_debug(LD_GENERAL, "Client from '%s' with transport '%s'. " "I've now seen %d clients.", safe_str_client(fmt_addr(&(*ent)->addr)), transport_name ? transport_name : "<no transport>", (int)val); } /* Sort the transport names (helps with unit testing). */ smartlist_sort_strings(transports_used); /* Loop through all seen transports. */ SMARTLIST_FOREACH_BEGIN(transports_used, const char *, transport_name) { void *transport_count_ptr = strmap_get(transport_counts, transport_name); uintptr_t transport_count = (uintptr_t) transport_count_ptr; log_debug(LD_GENERAL, "We got "U64_FORMAT" clients with transport '%s'.", U64_PRINTF_ARG((uint64_t)transport_count), transport_name); smartlist_add_asprintf(string_chunks, "%s="U64_FORMAT, transport_name, U64_PRINTF_ARG(round_uint64_to_next_multiple_of( (uint64_t)transport_count, granularity))); } SMARTLIST_FOREACH_END(transport_name); the_string = smartlist_join_strings(string_chunks, ",", 0, NULL); log_debug(LD_GENERAL, "Final bridge-ip-transports string: '%s'", the_string); done: strmap_free(transport_counts, NULL); SMARTLIST_FOREACH(transports_used, char *, s, tor_free(s)); smartlist_free(transports_used); SMARTLIST_FOREACH(string_chunks, char *, s, tor_free(s)); smartlist_free(string_chunks); return the_string; } /** Return a newly allocated comma-separated string containing statistics * on network status downloads. The string contains the number of completed * requests, timeouts, and still running requests as well as the download * times by deciles and quartiles. Return NULL if we have not observed * requests for long enough. */ static char * geoip_get_dirreq_history(dirreq_type_t type) { char *result = NULL; smartlist_t *dirreq_completed = NULL; uint32_t complete = 0, timeouts = 0, running = 0; int bufsize = 1024, written; dirreq_map_entry_t **ptr, **next; struct timeval now; tor_gettimeofday(&now); dirreq_completed = smartlist_new(); for (ptr = HT_START(dirreqmap, &dirreq_map); ptr; ptr = next) { dirreq_map_entry_t *ent = *ptr; if (ent->type != type) { next = HT_NEXT(dirreqmap, &dirreq_map, ptr); continue; } else { if (ent->completed) { smartlist_add(dirreq_completed, ent); complete++; next = HT_NEXT_RMV(dirreqmap, &dirreq_map, ptr); } else { if (tv_mdiff(&ent->request_time, &now) / 1000 > DIRREQ_TIMEOUT) timeouts++; else running++; next = HT_NEXT_RMV(dirreqmap, &dirreq_map, ptr); tor_free(ent); } } } #define DIR_REQ_GRANULARITY 4 complete = round_uint32_to_next_multiple_of(complete, DIR_REQ_GRANULARITY); timeouts = round_uint32_to_next_multiple_of(timeouts, DIR_REQ_GRANULARITY); running = round_uint32_to_next_multiple_of(running, DIR_REQ_GRANULARITY); result = tor_malloc_zero(bufsize); written = tor_snprintf(result, bufsize, "complete=%u,timeout=%u," "running=%u", complete, timeouts, running); if (written < 0) { tor_free(result); goto done; } #define MIN_DIR_REQ_RESPONSES 16 if (complete >= MIN_DIR_REQ_RESPONSES) { uint32_t *dltimes; /* We may have rounded 'completed' up. Here we want to use the * real value. */ complete = smartlist_len(dirreq_completed); dltimes = tor_calloc(complete, sizeof(uint32_t)); SMARTLIST_FOREACH_BEGIN(dirreq_completed, dirreq_map_entry_t *, ent) { uint32_t bytes_per_second; uint32_t time_diff = (uint32_t) tv_mdiff(&ent->request_time, &ent->completion_time); if (time_diff == 0) time_diff = 1; /* Avoid DIV/0; "instant" answers are impossible * by law of nature or something, but a millisecond * is a bit greater than "instantly" */ bytes_per_second = (uint32_t)(1000 * ent->response_size / time_diff); dltimes[ent_sl_idx] = bytes_per_second; } SMARTLIST_FOREACH_END(ent); median_uint32(dltimes, complete); /* sorts as a side effect. */ written = tor_snprintf(result + written, bufsize - written, ",min=%u,d1=%u,d2=%u,q1=%u,d3=%u,d4=%u,md=%u," "d6=%u,d7=%u,q3=%u,d8=%u,d9=%u,max=%u", dltimes[0], dltimes[1*complete/10-1], dltimes[2*complete/10-1], dltimes[1*complete/4-1], dltimes[3*complete/10-1], dltimes[4*complete/10-1], dltimes[5*complete/10-1], dltimes[6*complete/10-1], dltimes[7*complete/10-1], dltimes[3*complete/4-1], dltimes[8*complete/10-1], dltimes[9*complete/10-1], dltimes[complete-1]); if (written<0) tor_free(result); tor_free(dltimes); } done: SMARTLIST_FOREACH(dirreq_completed, dirreq_map_entry_t *, ent, tor_free(ent)); smartlist_free(dirreq_completed); return result; } /** Store a newly allocated comma-separated string in * *<a>country_str</a> containing entries for all the countries from * which we've seen enough clients connect as a bridge, directory * server, or entry guard. The entry format is cc=num where num is the * number of IPs we've seen connecting from that country, and cc is a * lowercased country code. *<a>country_str</a> is set to NULL if * we're not ready to export per country data yet. * * Store a newly allocated comma-separated string in <a>ipver_str</a> * containing entries for clients connecting over IPv4 and IPv6. The * format is family=num where num is the nubmer of IPs we've seen * connecting over that protocol family, and family is 'v4' or 'v6'. * * Return 0 on success and -1 if we're missing geoip data. */ int geoip_get_client_history(geoip_client_action_t action, char **country_str, char **ipver_str) { unsigned granularity = IP_GRANULARITY; smartlist_t *entries = NULL; int n_countries = geoip_get_n_countries(); int i; clientmap_entry_t **cm_ent; unsigned *counts = NULL; unsigned total = 0; unsigned ipv4_count = 0, ipv6_count = 0; if (!geoip_is_loaded(AF_INET) && !geoip_is_loaded(AF_INET6)) return -1; counts = tor_calloc(n_countries, sizeof(unsigned)); HT_FOREACH(cm_ent, clientmap, &client_history) { int country; if ((*cm_ent)->action != (int)action) continue; country = geoip_get_country_by_addr(&(*cm_ent)->addr); if (country < 0) country = 0; /** unresolved requests are stored at index 0. */ tor_assert(0 <= country && country < n_countries); ++counts[country]; ++total; switch (tor_addr_family(&(*cm_ent)->addr)) { case AF_INET: ipv4_count++; break; case AF_INET6: ipv6_count++; break; } } if (ipver_str) { smartlist_t *chunks = smartlist_new(); smartlist_add_asprintf(chunks, "v4=%u", round_to_next_multiple_of(ipv4_count, granularity)); smartlist_add_asprintf(chunks, "v6=%u", round_to_next_multiple_of(ipv6_count, granularity)); *ipver_str = smartlist_join_strings(chunks, ",", 0, NULL); SMARTLIST_FOREACH(chunks, char *, c, tor_free(c)); smartlist_free(chunks); } /* Don't record per country data if we haven't seen enough IPs. */ if (total < MIN_IPS_TO_NOTE_ANYTHING) { tor_free(counts); if (country_str) *country_str = NULL; return 0; } /* Make a list of c_hist_t */ entries = smartlist_new(); for (i = 0; i < n_countries; ++i) { unsigned c = counts[i]; const char *countrycode; c_hist_t *ent; /* Only report a country if it has a minimum number of IPs. */ if (c >= MIN_IPS_TO_NOTE_COUNTRY) { c = round_to_next_multiple_of(c, granularity); countrycode = geoip_get_country_name(i); ent = tor_malloc(sizeof(c_hist_t)); strlcpy(ent->country, countrycode, sizeof(ent->country)); ent->total = c; smartlist_add(entries, ent); } } /* Sort entries. Note that we must do this _AFTER_ rounding, or else * the sort order could leak info. */ smartlist_sort(entries, c_hist_compare_); if (country_str) { smartlist_t *chunks = smartlist_new(); SMARTLIST_FOREACH(entries, c_hist_t *, ch, { smartlist_add_asprintf(chunks, "%s=%u", ch->country, ch->total); }); *country_str = smartlist_join_strings(chunks, ",", 0, NULL); SMARTLIST_FOREACH(chunks, char *, c, tor_free(c)); smartlist_free(chunks); } SMARTLIST_FOREACH(entries, c_hist_t *, c, tor_free(c)); smartlist_free(entries); tor_free(counts); return 0; } /** Return a newly allocated string holding the per-country request history * for v3 network statuses in a format suitable for an extra-info document, * or NULL on failure. */ char * geoip_get_request_history(void) { smartlist_t *entries, *strings; char *result; unsigned granularity = IP_GRANULARITY; if (!geoip_countries) return NULL; entries = smartlist_new(); SMARTLIST_FOREACH_BEGIN(geoip_countries, geoip_country_t *, c) { uint32_t tot = 0; c_hist_t *ent; tot = c->n_v3_ns_requests; if (!tot) continue; ent = tor_malloc_zero(sizeof(c_hist_t)); strlcpy(ent->country, c->countrycode, sizeof(ent->country)); ent->total = round_to_next_multiple_of(tot, granularity); smartlist_add(entries, ent); } SMARTLIST_FOREACH_END(c); smartlist_sort(entries, c_hist_compare_); strings = smartlist_new(); SMARTLIST_FOREACH(entries, c_hist_t *, ent, { smartlist_add_asprintf(strings, "%s=%u", ent->country, ent->total); }); result = smartlist_join_strings(strings, ",", 0, NULL); SMARTLIST_FOREACH(strings, char *, cp, tor_free(cp)); SMARTLIST_FOREACH(entries, c_hist_t *, ent, tor_free(ent)); smartlist_free(strings); smartlist_free(entries); return result; } /** Start time of directory request stats or 0 if we're not collecting * directory request statistics. */ static time_t start_of_dirreq_stats_interval; /** Initialize directory request stats. */ void geoip_dirreq_stats_init(time_t now) { start_of_dirreq_stats_interval = now; } /** Reset counters for dirreq stats. */ void geoip_reset_dirreq_stats(time_t now) { SMARTLIST_FOREACH(geoip_countries, geoip_country_t *, c, { c->n_v3_ns_requests = 0; }); { clientmap_entry_t **ent, **next, *this; for (ent = HT_START(clientmap, &client_history); ent != NULL; ent = next) { if ((*ent)->action == GEOIP_CLIENT_NETWORKSTATUS) { this = *ent; next = HT_NEXT_RMV(clientmap, &client_history, ent); clientmap_entry_free(this); } else { next = HT_NEXT(clientmap, &client_history, ent); } } } memset(ns_v3_responses, 0, sizeof(ns_v3_responses)); { dirreq_map_entry_t **ent, **next, *this; for (ent = HT_START(dirreqmap, &dirreq_map); ent != NULL; ent = next) { this = *ent; next = HT_NEXT_RMV(dirreqmap, &dirreq_map, ent); tor_free(this); } } start_of_dirreq_stats_interval = now; } /** Stop collecting directory request stats in a way that we can re-start * doing so in geoip_dirreq_stats_init(). */ void geoip_dirreq_stats_term(void) { geoip_reset_dirreq_stats(0); } /** Return a newly allocated string containing the dirreq statistics * until <b>now</b>, or NULL if we're not collecting dirreq stats. Caller * must ensure start_of_dirreq_stats_interval is in the past. */ char * geoip_format_dirreq_stats(time_t now) { char t[ISO_TIME_LEN+1]; int i; char *v3_ips_string = NULL, *v3_reqs_string = NULL, *v3_direct_dl_string = NULL, *v3_tunneled_dl_string = NULL; char *result = NULL; if (!start_of_dirreq_stats_interval) return NULL; /* Not initialized. */ tor_assert(now >= start_of_dirreq_stats_interval); format_iso_time(t, now); geoip_get_client_history(GEOIP_CLIENT_NETWORKSTATUS, &v3_ips_string, NULL); v3_reqs_string = geoip_get_request_history(); #define RESPONSE_GRANULARITY 8 for (i = 0; i < GEOIP_NS_RESPONSE_NUM; i++) { ns_v3_responses[i] = round_uint32_to_next_multiple_of( ns_v3_responses[i], RESPONSE_GRANULARITY); } #undef RESPONSE_GRANULARITY v3_direct_dl_string = geoip_get_dirreq_history(DIRREQ_DIRECT); v3_tunneled_dl_string = geoip_get_dirreq_history(DIRREQ_TUNNELED); /* Put everything together into a single string. */ tor_asprintf(&result, "dirreq-stats-end %s (%d s)\n" "dirreq-v3-ips %s\n" "dirreq-v3-reqs %s\n" "dirreq-v3-resp ok=%u,not-enough-sigs=%u,unavailable=%u," "not-found=%u,not-modified=%u,busy=%u\n" "dirreq-v3-direct-dl %s\n" "dirreq-v3-tunneled-dl %s\n", t, (unsigned) (now - start_of_dirreq_stats_interval), v3_ips_string ? v3_ips_string : "", v3_reqs_string ? v3_reqs_string : "", ns_v3_responses[GEOIP_SUCCESS], ns_v3_responses[GEOIP_REJECT_NOT_ENOUGH_SIGS], ns_v3_responses[GEOIP_REJECT_UNAVAILABLE], ns_v3_responses[GEOIP_REJECT_NOT_FOUND], ns_v3_responses[GEOIP_REJECT_NOT_MODIFIED], ns_v3_responses[GEOIP_REJECT_BUSY], v3_direct_dl_string ? v3_direct_dl_string : "", v3_tunneled_dl_string ? v3_tunneled_dl_string : ""); /* Free partial strings. */ tor_free(v3_ips_string); tor_free(v3_reqs_string); tor_free(v3_direct_dl_string); tor_free(v3_tunneled_dl_string); return result; } /** If 24 hours have passed since the beginning of the current dirreq * stats period, write dirreq stats to $DATADIR/stats/dirreq-stats * (possibly overwriting an existing file) and reset counters. Return * when we would next want to write dirreq stats or 0 if we never want to * write. */ time_t geoip_dirreq_stats_write(time_t now) { char *str = NULL; if (!start_of_dirreq_stats_interval) return 0; /* Not initialized. */ if (start_of_dirreq_stats_interval + WRITE_STATS_INTERVAL > now) goto done; /* Not ready to write. */ /* Discard all items in the client history that are too old. */ geoip_remove_old_clients(start_of_dirreq_stats_interval); /* Generate history string .*/ str = geoip_format_dirreq_stats(now); if (! str) goto done; /* Write dirreq-stats string to disk. */ if (!check_or_create_data_subdir("stats")) { write_to_data_subdir("stats", "dirreq-stats", str, "dirreq statistics"); /* Reset measurement interval start. */ geoip_reset_dirreq_stats(now); } done: tor_free(str); return start_of_dirreq_stats_interval + WRITE_STATS_INTERVAL; } /** Start time of bridge stats or 0 if we're not collecting bridge * statistics. */ static time_t start_of_bridge_stats_interval; /** Initialize bridge stats. */ void geoip_bridge_stats_init(time_t now) { start_of_bridge_stats_interval = now; } /** Stop collecting bridge stats in a way that we can re-start doing so in * geoip_bridge_stats_init(). */ void geoip_bridge_stats_term(void) { client_history_clear(); start_of_bridge_stats_interval = 0; } /** Validate a bridge statistics string as it would be written to a * current extra-info descriptor. Return 1 if the string is valid and * recent enough, or 0 otherwise. */ static int validate_bridge_stats(const char *stats_str, time_t now) { char stats_end_str[ISO_TIME_LEN+1], stats_start_str[ISO_TIME_LEN+1], *eos; const char *BRIDGE_STATS_END = "bridge-stats-end "; const char *BRIDGE_IPS = "bridge-ips "; const char *BRIDGE_IPS_EMPTY_LINE = "bridge-ips\n"; const char *BRIDGE_TRANSPORTS = "bridge-ip-transports "; const char *BRIDGE_TRANSPORTS_EMPTY_LINE = "bridge-ip-transports\n"; const char *tmp; time_t stats_end_time; int seconds; tor_assert(stats_str); /* Parse timestamp and number of seconds from "bridge-stats-end YYYY-MM-DD HH:MM:SS (N s)" */ tmp = find_str_at_start_of_line(stats_str, BRIDGE_STATS_END); if (!tmp) return 0; tmp += strlen(BRIDGE_STATS_END); if (strlen(tmp) < ISO_TIME_LEN + 6) return 0; strlcpy(stats_end_str, tmp, sizeof(stats_end_str)); if (parse_iso_time(stats_end_str, &stats_end_time) < 0) return 0; if (stats_end_time < now - (25*60*60) || stats_end_time > now + (1*60*60)) return 0; seconds = (int)strtol(tmp + ISO_TIME_LEN + 2, &eos, 10); if (!eos || seconds < 23*60*60) return 0; format_iso_time(stats_start_str, stats_end_time - seconds); /* Parse: "bridge-ips CC=N,CC=N,..." */ tmp = find_str_at_start_of_line(stats_str, BRIDGE_IPS); if (!tmp) { /* Look if there is an empty "bridge-ips" line */ tmp = find_str_at_start_of_line(stats_str, BRIDGE_IPS_EMPTY_LINE); if (!tmp) return 0; } /* Parse: "bridge-ip-transports PT=N,PT=N,..." */ tmp = find_str_at_start_of_line(stats_str, BRIDGE_TRANSPORTS); if (!tmp) { /* Look if there is an empty "bridge-ip-transports" line */ tmp = find_str_at_start_of_line(stats_str, BRIDGE_TRANSPORTS_EMPTY_LINE); if (!tmp) return 0; } return 1; } /** Most recent bridge statistics formatted to be written to extra-info * descriptors. */ static char *bridge_stats_extrainfo = NULL; /** Return a newly allocated string holding our bridge usage stats by country * in a format suitable for inclusion in an extrainfo document. Return NULL on * failure. */ char * geoip_format_bridge_stats(time_t now) { char *out = NULL; char *country_data = NULL, *ipver_data = NULL, *transport_data = NULL; long duration = now - start_of_bridge_stats_interval; char written[ISO_TIME_LEN+1]; if (duration < 0) return NULL; if (!start_of_bridge_stats_interval) return NULL; /* Not initialized. */ format_iso_time(written, now); geoip_get_client_history(GEOIP_CLIENT_CONNECT, &country_data, &ipver_data); transport_data = geoip_get_transport_history(); tor_asprintf(&out, "bridge-stats-end %s (%ld s)\n" "bridge-ips %s\n" "bridge-ip-versions %s\n" "bridge-ip-transports %s\n", written, duration, country_data ? country_data : "", ipver_data ? ipver_data : "", transport_data ? transport_data : ""); tor_free(country_data); tor_free(ipver_data); tor_free(transport_data); return out; } /** Return a newly allocated string holding our bridge usage stats by country * in a format suitable for the answer to a controller request. Return NULL on * failure. */ static char * format_bridge_stats_controller(time_t now) { char *out = NULL, *country_data = NULL, *ipver_data = NULL; char started[ISO_TIME_LEN+1]; (void) now; format_iso_time(started, start_of_bridge_stats_interval); geoip_get_client_history(GEOIP_CLIENT_CONNECT, &country_data, &ipver_data); tor_asprintf(&out, "TimeStarted=\"%s\" CountrySummary=%s IPVersions=%s", started, country_data ? country_data : "", ipver_data ? ipver_data : ""); tor_free(country_data); tor_free(ipver_data); return out; } /** Return a newly allocated string holding our bridge usage stats by * country in a format suitable for inclusion in our heartbeat * message. Return NULL on failure. */ char * format_client_stats_heartbeat(time_t now) { const int n_hours = 6; char *out = NULL; int n_clients = 0; clientmap_entry_t **ent; unsigned cutoff = (unsigned)( (now-n_hours*3600)/60 ); if (!start_of_bridge_stats_interval) return NULL; /* Not initialized. */ /* count unique IPs */ HT_FOREACH(ent, clientmap, &client_history) { /* only count directly connecting clients */ if ((*ent)->action != GEOIP_CLIENT_CONNECT) continue; if ((*ent)->last_seen_in_minutes < cutoff) continue; n_clients++; } tor_asprintf(&out, "Heartbeat: " "In the last %d hours, I have seen %d unique clients.", n_hours, n_clients); return out; } /** Write bridge statistics to $DATADIR/stats/bridge-stats and return * when we should next try to write statistics. */ time_t geoip_bridge_stats_write(time_t now) { char *val = NULL; /* Check if 24 hours have passed since starting measurements. */ if (now < start_of_bridge_stats_interval + WRITE_STATS_INTERVAL) return start_of_bridge_stats_interval + WRITE_STATS_INTERVAL; /* Discard all items in the client history that are too old. */ geoip_remove_old_clients(start_of_bridge_stats_interval); /* Generate formatted string */ val = geoip_format_bridge_stats(now); if (val == NULL) goto done; /* Update the stored value. */ tor_free(bridge_stats_extrainfo); bridge_stats_extrainfo = val; start_of_bridge_stats_interval = now; /* Write it to disk. */ if (!check_or_create_data_subdir("stats")) { write_to_data_subdir("stats", "bridge-stats", bridge_stats_extrainfo, "bridge statistics"); /* Tell the controller, "hey, there are clients!" */ { char *controller_str = format_bridge_stats_controller(now); if (controller_str) control_event_clients_seen(controller_str); tor_free(controller_str); } } done: return start_of_bridge_stats_interval + WRITE_STATS_INTERVAL; } /** Try to load the most recent bridge statistics from disk, unless we * have finished a measurement interval lately, and check whether they * are still recent enough. */ static void load_bridge_stats(time_t now) { char *fname, *contents; if (bridge_stats_extrainfo) return; fname = get_datadir_fname2("stats", "bridge-stats"); contents = read_file_to_str(fname, RFTS_IGNORE_MISSING, NULL); if (contents && validate_bridge_stats(contents, now)) { bridge_stats_extrainfo = contents; } else { tor_free(contents); } tor_free(fname); } /** Return most recent bridge statistics for inclusion in extra-info * descriptors, or NULL if we don't have recent bridge statistics. */ const char * geoip_get_bridge_stats_extrainfo(time_t now) { load_bridge_stats(now); return bridge_stats_extrainfo; } /** Return a new string containing the recent bridge statistics to be returned * to controller clients, or NULL if we don't have any bridge statistics. */ char * geoip_get_bridge_stats_controller(time_t now) { return format_bridge_stats_controller(now); } /** Start time of entry stats or 0 if we're not collecting entry * statistics. */ static time_t start_of_entry_stats_interval; /** Initialize entry stats. */ void geoip_entry_stats_init(time_t now) { start_of_entry_stats_interval = now; } /** Reset counters for entry stats. */ void geoip_reset_entry_stats(time_t now) { client_history_clear(); start_of_entry_stats_interval = now; } /** Stop collecting entry stats in a way that we can re-start doing so in * geoip_entry_stats_init(). */ void geoip_entry_stats_term(void) { geoip_reset_entry_stats(0); } /** Return a newly allocated string containing the entry statistics * until <b>now</b>, or NULL if we're not collecting entry stats. Caller * must ensure start_of_entry_stats_interval lies in the past. */ char * geoip_format_entry_stats(time_t now) { char t[ISO_TIME_LEN+1]; char *data = NULL; char *result; if (!start_of_entry_stats_interval) return NULL; /* Not initialized. */ tor_assert(now >= start_of_entry_stats_interval); geoip_get_client_history(GEOIP_CLIENT_CONNECT, &data, NULL); format_iso_time(t, now); tor_asprintf(&result, "entry-stats-end %s (%u s)\n" "entry-ips %s\n", t, (unsigned) (now - start_of_entry_stats_interval), data ? data : ""); tor_free(data); return result; } /** If 24 hours have passed since the beginning of the current entry stats * period, write entry stats to $DATADIR/stats/entry-stats (possibly * overwriting an existing file) and reset counters. Return when we would * next want to write entry stats or 0 if we never want to write. */ time_t geoip_entry_stats_write(time_t now) { char *str = NULL; if (!start_of_entry_stats_interval) return 0; /* Not initialized. */ if (start_of_entry_stats_interval + WRITE_STATS_INTERVAL > now) goto done; /* Not ready to write. */ /* Discard all items in the client history that are too old. */ geoip_remove_old_clients(start_of_entry_stats_interval); /* Generate history string .*/ str = geoip_format_entry_stats(now); /* Write entry-stats string to disk. */ if (!check_or_create_data_subdir("stats")) { write_to_data_subdir("stats", "entry-stats", str, "entry statistics"); /* Reset measurement interval start. */ geoip_reset_entry_stats(now); } done: tor_free(str); return start_of_entry_stats_interval + WRITE_STATS_INTERVAL; } /** Helper used to implement GETINFO ip-to-country/... controller command. */ int getinfo_helper_geoip(control_connection_t *control_conn, const char *question, char **answer, const char **errmsg) { (void)control_conn; if (!strcmpstart(question, "ip-to-country/")) { int c; sa_family_t family; tor_addr_t addr; question += strlen("ip-to-country/"); family = tor_addr_parse(&addr, question); if (family != AF_INET && family != AF_INET6) { *errmsg = "Invalid address family"; return -1; } if (!geoip_is_loaded(family)) { *errmsg = "GeoIP data not loaded"; return -1; } if (family == AF_INET) c = geoip_get_country_by_ipv4(tor_addr_to_ipv4h(&addr)); else /* AF_INET6 */ c = geoip_get_country_by_ipv6(tor_addr_to_in6(&addr)); *answer = tor_strdup(geoip_get_country_name(c)); } return 0; } /** Release all storage held by the GeoIP databases and country list. */ STATIC void clear_geoip_db(void) { if (geoip_countries) { SMARTLIST_FOREACH(geoip_countries, geoip_country_t *, c, tor_free(c)); smartlist_free(geoip_countries); } strmap_free(country_idxplus1_by_lc_code, NULL); if (geoip_ipv4_entries) { SMARTLIST_FOREACH(geoip_ipv4_entries, geoip_ipv4_entry_t *, ent, tor_free(ent)); smartlist_free(geoip_ipv4_entries); } if (geoip_ipv6_entries) { SMARTLIST_FOREACH(geoip_ipv6_entries, geoip_ipv6_entry_t *, ent, tor_free(ent)); smartlist_free(geoip_ipv6_entries); } geoip_countries = NULL; country_idxplus1_by_lc_code = NULL; geoip_ipv4_entries = NULL; geoip_ipv6_entries = NULL; } /** Release all storage held in this file. */ void geoip_free_all(void) { { clientmap_entry_t **ent, **next, *this; for (ent = HT_START(clientmap, &client_history); ent != NULL; ent = next) { this = *ent; next = HT_NEXT_RMV(clientmap, &client_history, ent); clientmap_entry_free(this); } HT_CLEAR(clientmap, &client_history); } { dirreq_map_entry_t **ent, **next, *this; for (ent = HT_START(dirreqmap, &dirreq_map); ent != NULL; ent = next) { this = *ent; next = HT_NEXT_RMV(dirreqmap, &dirreq_map, ent); tor_free(this); } HT_CLEAR(dirreqmap, &dirreq_map); } clear_geoip_db(); tor_free(bridge_stats_extrainfo); }
BreakoutCoin/Breakout-Chain-Client
src/tor/or/geoip.c
C
mit
58,156
/* swdp-m0sub.c * * Copyright 2015 Brian Swetland <swetland@frotz.net> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <app.h> #include <debug.h> #include <string.h> #include <stdlib.h> #include <printf.h> #include <platform.h> #include <arch/arm.h> #include <kernel/thread.h> #include <platform/lpc43xx-gpio.h> #include <platform/lpc43xx-sgpio.h> #include <platform/lpc43xx-clocks.h> #include "rswdp.h" #define PIN_LED PIN(1,1) #define PIN_RESET PIN(2,5) #define PIN_RESET_TXEN PIN(2,6) #define PIN_SWDIO_TXEN PIN(1,5) // SGPIO15=6 #define PIN_SWDIO PIN(1,6) // SGPIO14=6 #define PIN_SWO PIN(1,14) // U1_RXD=1 #define PIN_SWCLK PIN(1,17) // SGPIO11=6 #define GPIO_LED GPIO(0,8) #define GPIO_RESET GPIO(5,5) #define GPIO_RESET_TXEN GPIO(5,6) #define GPIO_SWDIO_TXEN GPIO(1,8) #define GPIO_SWDIO GPIO(1,9) #define GPIO_SWCLK GPIO(0,12) static void gpio_init(void) { pin_config(PIN_LED, PIN_MODE(0) | PIN_PLAIN); pin_config(PIN_RESET, PIN_MODE(4) | PIN_PLAIN); pin_config(PIN_RESET_TXEN, PIN_MODE(4) | PIN_PLAIN); pin_config(PIN_SWDIO_TXEN, PIN_MODE(6) | PIN_PLAIN | PIN_FAST); pin_config(PIN_SWDIO, PIN_MODE(6) | PIN_PLAIN | PIN_INPUT | PIN_FAST); pin_config(PIN_SWCLK, PIN_MODE(6) | PIN_PLAIN | PIN_FAST); pin_config(PIN_SWO, PIN_MODE(1) | PIN_PLAIN | PIN_INPUT | PIN_FAST); gpio_set(GPIO_LED, 0); gpio_set(GPIO_RESET, 1); gpio_set(GPIO_RESET_TXEN, 0); gpio_config(GPIO_LED, GPIO_OUTPUT); gpio_config(GPIO_RESET, GPIO_OUTPUT); gpio_config(GPIO_RESET_TXEN, GPIO_OUTPUT); } /* returns 1 if the number of bits set in n is odd */ static unsigned parity(unsigned n) { n = (n & 0x55555555) + ((n & 0xaaaaaaaa) >> 1); n = (n & 0x33333333) + ((n & 0xcccccccc) >> 2); n = (n & 0x0f0f0f0f) + ((n & 0xf0f0f0f0) >> 4); n = (n & 0x00ff00ff) + ((n & 0xff00ff00) >> 8); n = (n & 0x0000ffff) + ((n & 0xffff0000) >> 16); return n & 1; } #include "fw-m0sub.h" #define M0SUB_ZEROMAP 0x40043308 #define M0SUB_TXEV 0x40043314 // write 0 to clear #define M4_TXEV 0x40043130 // write 0 to clear #define RESET_CTRL0 0x40053100 #define M0_SUB_RST (1 << 12) #define COMM_CMD 0x18004000 #define COMM_ARG1 0x18004004 #define COMM_ARG2 0x18004008 #define COMM_RESP 0x1800400C #define CMD_ERR 0 #define CMD_NOP 1 #define CMD_READ 2 #define CMD_WRITE 3 #define CMD_RESET 4 #define CMD_SETCLOCK 5 #define RSP_BUSY 0xFFFFFFFF void swd_init(void) { gpio_init(); writel(BASE_CLK_SEL(CLK_PLL1), BASE_PERIPH_CLK); spin(1000); // SGPIO15 SWDIO_TXEN writel(CFG_OUT_GPIO | CFG_OE_GPIO, SGPIO_OUT_CFG(15)); // SGPIO14 SWDIO writel(CFG_OUT_GPIO | CFG_OE_GPIO, SGPIO_OUT_CFG(14)); // SGPIO11 SWCLK writel(CFG_OUT_GPIO | CFG_OE_GPIO, SGPIO_OUT_CFG(11)); // all outputs enabled and high writel((1 << 11) | (1 << 14) | (1 << 15), SGPIO_OUT); writel((1 << 11) | (1 << 14) | (1 << 15), SGPIO_OEN); writel(0, M4_TXEV); writel(M0_SUB_RST, RESET_CTRL0); writel(0x18000000, M0SUB_ZEROMAP); writel(0xffffffff, 0x18004000); memcpy((void*) 0x18000000, zero_bin, sizeof(zero_bin)); DSB; writel(0, RESET_CTRL0); } int swd_write(unsigned hdr, unsigned data) { unsigned n; unsigned p = parity(data); writel(CMD_WRITE, COMM_CMD); writel((hdr << 8) | (p << 16), COMM_ARG1); writel(data, COMM_ARG2); writel(RSP_BUSY, COMM_RESP); DSB; asm("sev"); while ((n = readl(COMM_RESP)) == RSP_BUSY) ; //printf("wr s=%d\n", n); return n; } int swd_read(unsigned hdr, unsigned *val) { unsigned n, data, p; writel(CMD_READ, COMM_CMD); writel(hdr << 8, COMM_ARG1); writel(RSP_BUSY, COMM_RESP); DSB; asm("sev"); while ((n = readl(COMM_RESP)) == RSP_BUSY) ; if (n) { return n; } data = readl(COMM_ARG1); p = readl(COMM_ARG2); if (p != parity(data)) { return ERR_PARITY; } //printf("rd s=%d p=%d d=%08x\n", n, p, data); *val = data; return 0; } void swd_reset(void) { unsigned n; writel(CMD_RESET, COMM_CMD); writel(RSP_BUSY, COMM_RESP); DSB; asm("sev"); while ((n = readl(COMM_RESP)) == RSP_BUSY) ; } unsigned swd_set_clock(unsigned khz) { unsigned n; if (khz > 8000) { khz = 8000; } writel(CMD_SETCLOCK, COMM_CMD); writel(khz/1000, COMM_ARG1); writel(RSP_BUSY, COMM_RESP); DSB; asm("sev"); while ((n = readl(COMM_RESP)) == RSP_BUSY) ; // todo: accurate value return khz; } void swd_hw_reset(int assert) { if (assert) { gpio_set(GPIO_RESET, 0); gpio_set(GPIO_RESET_TXEN, 1); } else { gpio_set(GPIO_RESET, 1); gpio_set(GPIO_RESET_TXEN, 0); } }
nvll/lk
app/mdebug/swd-m0sub.c
C
mit
4,971
/* * Changes: * Jan 22, 2010: Created (Cristiano Giuffrida) */ #include "inc.h" /*===========================================================================* * do_up * *===========================================================================*/ PUBLIC int do_up(m_ptr) message *m_ptr; /* request message pointer */ { /* A request was made to start a new system service. */ struct rproc *rp; struct rprocpub *rpub; int r; struct rs_start rs_start; int noblock; /* Check if the call can be allowed. */ if((r = check_call_permission(m_ptr->m_source, RS_UP, NULL)) != OK) return r; /* Allocate a new system service slot. */ r = alloc_slot(&rp); if(r != OK) { printf("RS: do_up: unable to allocate a new slot: %d\n", r); return r; } rpub = rp->r_pub; /* Copy the request structure. */ r = copy_rs_start(m_ptr->m_source, m_ptr->RS_CMD_ADDR, &rs_start); if (r != OK) { return r; } noblock = (rs_start.rss_flags & RSS_NOBLOCK); /* Initialize the slot as requested. */ r = init_slot(rp, &rs_start, m_ptr->m_source); if(r != OK) { printf("RS: do_up: unable to init the new slot: %d\n", r); return r; } /* Check for duplicates */ if(lookup_slot_by_label(rpub->label)) { printf("RS: service with the same label '%s' already exists\n", rpub->label); return EBUSY; } if(rpub->dev_nr>0 && lookup_slot_by_dev_nr(rpub->dev_nr)) { printf("RS: service with the same device number %d already exists\n", rpub->dev_nr); return EBUSY; } /* All information was gathered. Now try to start the system service. */ r = start_service(rp); if(r != OK) { return r; } /* Unblock the caller immediately if requested. */ if(noblock) { return OK; } /* Late reply - send a reply when service completes initialization. */ rp->r_flags |= RS_LATEREPLY; rp->r_caller = m_ptr->m_source; rp->r_caller_request = RS_UP; return EDONTREPLY; } /*===========================================================================* * do_down * *===========================================================================*/ PUBLIC int do_down(message *m_ptr) { register struct rproc *rp; register struct rprocpub *rpub; int s; char label[RS_MAX_LABEL_LEN]; /* Copy label. */ s = copy_label(m_ptr->m_source, m_ptr->RS_CMD_ADDR, m_ptr->RS_CMD_LEN, label, sizeof(label)); if(s != OK) { return s; } /* Lookup slot by label. */ rp = lookup_slot_by_label(label); if(!rp) { if(rs_verbose) printf("RS: do_down: service '%s' not found\n", label); return(ESRCH); } rpub = rp->r_pub; /* Check if the call can be allowed. */ if((s = check_call_permission(m_ptr->m_source, RS_DOWN, rp)) != OK) return s; /* Stop service. */ if (rp->r_flags & RS_TERMINATED) { /* A recovery script is requesting us to bring down the service. * The service is already gone, simply perform cleanup. */ if(rs_verbose) printf("RS: recovery script performs service down...\n"); unpublish_service(rp); cleanup_service(rp); return(OK); } stop_service(rp,RS_EXITING); /* Late reply - send a reply when service dies. */ rp->r_flags |= RS_LATEREPLY; rp->r_caller = m_ptr->m_source; rp->r_caller_request = RS_DOWN; return EDONTREPLY; } /*===========================================================================* * do_restart * *===========================================================================*/ PUBLIC int do_restart(message *m_ptr) { struct rproc *rp; int s, r; char label[RS_MAX_LABEL_LEN]; char script[MAX_SCRIPT_LEN]; /* Copy label. */ s = copy_label(m_ptr->m_source, m_ptr->RS_CMD_ADDR, m_ptr->RS_CMD_LEN, label, sizeof(label)); if(s != OK) { return s; } /* Lookup slot by label. */ rp = lookup_slot_by_label(label); if(!rp) { if(rs_verbose) printf("RS: do_restart: service '%s' not found\n", label); return(ESRCH); } /* Check if the call can be allowed. */ if((r = check_call_permission(m_ptr->m_source, RS_RESTART, rp)) != OK) return r; /* We can only be asked to restart a service from a recovery script. */ if (! (rp->r_flags & RS_TERMINATED) ) { if(rs_verbose) printf("RS: %s is still running\n", srv_to_string(rp)); return EBUSY; } if(rs_verbose) printf("RS: recovery script performs service restart...\n"); /* Restart the service, but make sure we don't call the script again. */ strcpy(script, rp->r_script); rp->r_script[0] = '\0'; restart_service(rp); strcpy(rp->r_script, script); return OK; } /*===========================================================================* * do_refresh * *===========================================================================*/ PUBLIC int do_refresh(message *m_ptr) { register struct rproc *rp; register struct rprocpub *rpub; int s; char label[RS_MAX_LABEL_LEN]; /* Copy label. */ s = copy_label(m_ptr->m_source, m_ptr->RS_CMD_ADDR, m_ptr->RS_CMD_LEN, label, sizeof(label)); if(s != OK) { return s; } /* Lookup slot by label. */ rp = lookup_slot_by_label(label); if(!rp) { if(rs_verbose) printf("RS: do_refresh: service '%s' not found\n", label); return(ESRCH); } rpub = rp->r_pub; /* Check if the call can be allowed. */ if((s = check_call_permission(m_ptr->m_source, RS_REFRESH, rp)) != OK) return s; /* Refresh service. */ if(rs_verbose) printf("RS: %s refreshing\n", srv_to_string(rp)); stop_service(rp,RS_REFRESHING); return OK; } /*===========================================================================* * do_shutdown * *===========================================================================*/ PUBLIC int do_shutdown(message *m_ptr) { int slot_nr; struct rproc *rp; int r; /* Check if the call can be allowed. */ if (m_ptr != NULL) { if((r = check_call_permission(m_ptr->m_source, RS_SHUTDOWN, NULL)) != OK) return r; } if(rs_verbose) printf("RS: shutting down...\n"); /* Set flag to tell RS we are shutting down. */ shutting_down = TRUE; /* Don't restart dead services. */ for (slot_nr = 0; slot_nr < NR_SYS_PROCS; slot_nr++) { rp = &rproc[slot_nr]; if (rp->r_flags & RS_IN_USE) { rp->r_flags |= RS_EXITING; } } return(OK); } /*===========================================================================* * do_init_ready * *===========================================================================*/ PUBLIC int do_init_ready(message *m_ptr) { int who_p; struct rproc *rp; struct rprocpub *rpub; int result; int r; who_p = _ENDPOINT_P(m_ptr->m_source); rp = rproc_ptr[who_p]; rpub = rp->r_pub; result = m_ptr->RS_INIT_RESULT; /* Make sure the originating service was requested to initialize. */ if(! (rp->r_flags & RS_INITIALIZING) ) { if(rs_verbose) printf("RS: do_init_ready: got unexpected init ready msg from %d\n", m_ptr->m_source); return(EDONTREPLY); } /* Check if something went wrong and the service failed to init. * In that case, kill the service. */ if(result != OK) { if(rs_verbose) printf("RS: %s initialization error: %s\n", srv_to_string(rp), init_strerror(result)); crash_service(rp); /* simulate crash */ return(EDONTREPLY); } /* Mark the slot as no longer initializing. */ rp->r_flags &= ~RS_INITIALIZING; rp->r_check_tm = 0; getuptime(&rp->r_alive_tm); /* See if a late reply has to be sent. */ late_reply(rp, OK); if(rs_verbose) printf("RS: %s initialized\n", srv_to_string(rp)); /* If the service has completed initialization after a live * update, end the update now. */ if(rp->r_flags & RS_UPDATING) { printf("RS: update succeeded\n"); end_update(OK); } /* If the service has completed initialization after a crash * make the new instance active and cleanup the old replica. */ if(rp->r_prev_rp) { cleanup_service(rp->r_prev_rp); rp->r_prev_rp = NULL; if(rs_verbose) printf("RS: %s completed restart\n", srv_to_string(rp)); } /* If we must keep a replica of this system service, create it now. */ if(rpub->sys_flags & SF_USE_REPL) { if ((r = clone_service(rp)) != OK) { printf("RS: warning: unable to clone %s\n", srv_to_string(rp)); } } return(OK); } /*===========================================================================* * do_update * *===========================================================================*/ PUBLIC int do_update(message *m_ptr) { struct rproc *rp; struct rproc *new_rp; struct rprocpub *rpub; struct rs_start rs_start; int noblock; int s; char label[RS_MAX_LABEL_LEN]; int lu_state; int prepare_maxtime; /* Copy the request structure. */ s = copy_rs_start(m_ptr->m_source, m_ptr->RS_CMD_ADDR, &rs_start); if (s != OK) { return s; } noblock = (rs_start.rss_flags & RSS_NOBLOCK); /* Copy label. */ s = copy_label(m_ptr->m_source, rs_start.rss_label.l_addr, rs_start.rss_label.l_len, label, sizeof(label)); if(s != OK) { return s; } /* Lookup slot by label. */ rp = lookup_slot_by_label(label); if(!rp) { if(rs_verbose) printf("RS: do_update: service '%s' not found\n", label); return ESRCH; } rpub = rp->r_pub; /* Check if the call can be allowed. */ if((s = check_call_permission(m_ptr->m_source, RS_UPDATE, rp)) != OK) return s; /* Retrieve live update state. */ lu_state = m_ptr->RS_LU_STATE; if(lu_state == SEF_LU_STATE_NULL) { return(EINVAL); } /* Retrieve prepare max time. */ prepare_maxtime = m_ptr->RS_LU_PREPARE_MAXTIME; if(prepare_maxtime) { if(prepare_maxtime < 0 || prepare_maxtime > RS_MAX_PREPARE_MAXTIME) { return(EINVAL); } } else { prepare_maxtime = RS_DEFAULT_PREPARE_MAXTIME; } /* Make sure we are not already updating. */ if(rupdate.flags & RS_UPDATING) { if(rs_verbose) printf("RS: do_update: an update is already in progress\n"); return EBUSY; } /* Allocate a system service slot for the new version. */ s = alloc_slot(&new_rp); if(s != OK) { printf("RS: do_update: unable to allocate a new slot: %d\n", s); return s; } /* Initialize the slot as requested. */ s = init_slot(new_rp, &rs_start, m_ptr->m_source); if(s != OK) { printf("RS: do_update: unable to init the new slot: %d\n", s); return s; } /* Let the new version inherit defaults from the old one. */ inherit_service_defaults(rp, new_rp); /* Create new version of the service but don't let it run. */ s = create_service(new_rp); if(s != OK) { printf("RS: do_update: unable to create a new service: %d\n", s); return s; } /* Link old version to new version and mark both as updating. */ rp->r_new_rp = new_rp; new_rp->r_old_rp = rp; rp->r_flags |= RS_UPDATING; rp->r_new_rp->r_flags |= RS_UPDATING; rupdate.flags |= RS_UPDATING; getuptime(&rupdate.prepare_tm); rupdate.prepare_maxtime = prepare_maxtime; rupdate.rp = rp; if(rs_verbose) printf("RS: %s updating\n", srv_to_string(rp)); /* Request to update. */ m_ptr->m_type = RS_LU_PREPARE; asynsend3(rpub->endpoint, m_ptr, AMF_NOREPLY); /* Unblock the caller immediately if requested. */ if(noblock) { return OK; } /* Late reply - send a reply when the new version completes initialization. */ rp->r_flags |= RS_LATEREPLY; rp->r_caller = m_ptr->m_source; rp->r_caller_request = RS_UPDATE; return EDONTREPLY; } /*===========================================================================* * do_upd_ready * *===========================================================================*/ PUBLIC int do_upd_ready(message *m_ptr) { struct rproc *rp, *old_rp, *new_rp; int who_p; int result; int r; who_p = _ENDPOINT_P(m_ptr->m_source); rp = rproc_ptr[who_p]; result = m_ptr->RS_LU_RESULT; /* Make sure the originating service was requested to prepare for update. */ if(rp != rupdate.rp) { if(rs_verbose) printf("RS: do_upd_ready: got unexpected update ready msg from %d\n", m_ptr->m_source); return(EINVAL); } /* Check if something went wrong and the service failed to prepare * for the update. In that case, end the update process. The old version will * be replied to and continue executing. */ if(result != OK) { end_update(result); printf("RS: update failed: %s\n", lu_strerror(result)); return OK; } /* Perform the update. */ old_rp = rp; new_rp = rp->r_new_rp; r = update_service(&old_rp, &new_rp); if(r != OK) { end_update(r); printf("RS: update failed: error %d\n", r); return r; } /* Let the new version run. */ r = run_service(new_rp, SEF_INIT_LU); if(r != OK) { update_service(&new_rp, &old_rp); /* rollback, can't fail. */ end_update(r); printf("RS: update failed: error %d\n", r); return r; } return(EDONTREPLY); } /*===========================================================================* * do_period * *===========================================================================*/ PUBLIC void do_period(m_ptr) message *m_ptr; { register struct rproc *rp; register struct rprocpub *rpub; clock_t now = m_ptr->NOTIFY_TIMESTAMP; int s; long period; /* If an update is in progress, check its status. */ if(rupdate.flags & RS_UPDATING) { update_period(m_ptr); } /* Search system services table. Only check slots that are in use and not * updating. */ for (rp=BEG_RPROC_ADDR; rp<END_RPROC_ADDR; rp++) { rpub = rp->r_pub; if ((rp->r_flags & RS_IN_USE) && !(rp->r_flags & RS_UPDATING)) { /* Compute period. */ period = rpub->period; if(rp->r_flags & RS_INITIALIZING) { period = RS_INIT_T; } /* If the service is to be revived (because it repeatedly exited, * and was not directly restarted), the binary backoff field is * greater than zero. */ if (rp->r_backoff > 0) { rp->r_backoff -= 1; if (rp->r_backoff == 0) { restart_service(rp); } } /* If the service was signaled with a SIGTERM and fails to respond, * kill the system service with a SIGKILL signal. */ else if (rp->r_stop_tm > 0 && now - rp->r_stop_tm > 2*RS_DELTA_T && rp->r_pid > 0) { crash_service(rp); /* simulate crash */ rp->r_stop_tm = 0; } /* There seems to be no special conditions. If the service has a * period assigned check its status. */ else if (period > 0) { /* Check if an answer to a status request is still pending. If * the service didn't respond within time, kill it to simulate * a crash. The failure will be detected and the service will * be restarted automatically. */ if (rp->r_alive_tm < rp->r_check_tm) { if (now - rp->r_alive_tm > 2*period && rp->r_pid > 0 && !(rp->r_flags & RS_NOPINGREPLY)) { if(rs_verbose) printf("RS: %s reported late\n", srv_to_string(rp)); rp->r_flags |= RS_NOPINGREPLY; crash_service(rp); /* simulate crash */ } } /* No answer pending. Check if a period expired since the last * check and, if so request the system service's status. */ else if (now - rp->r_check_tm > rpub->period) { notify(rpub->endpoint); /* request status */ rp->r_check_tm = now; /* mark time */ } } } } /* Reschedule a synchronous alarm for the next period. */ if (OK != (s=sys_setalarm(RS_DELTA_T, 0))) panic("couldn't set alarm: %d", s); } /*===========================================================================* * do_sigchld * *===========================================================================*/ PUBLIC void do_sigchld() { /* PM informed us that there are dead children to cleanup. Go get them. */ pid_t pid; int status; struct rproc *rp; struct rproc **rps; struct rprocpub *rpub; int i, nr_rps; if(rs_verbose) printf("RS: got SIGCHLD signal, cleaning up dead children\n"); while ( (pid = waitpid(-1, &status, WNOHANG)) != 0 ) { rp = lookup_slot_by_pid(pid); if(rp != NULL) { rpub = rp->r_pub; if(rs_verbose) printf("RS: %s exited via another signal manager\n", srv_to_string(rp)); /* The slot is still there. This means RS is not the signal * manager assigned to the process. Ignore the event but * free slots for all the service instances and send a late * reply if necessary. */ get_service_instances(rp, &rps, &nr_rps); for(i=0;i<nr_rps;i++) { if(rupdate.flags & RS_UPDATING) { rupdate.flags &= ~RS_UPDATING; } free_slot(rps[i]); } } } } /*===========================================================================* * do_getsysinfo * *===========================================================================*/ PUBLIC int do_getsysinfo(m_ptr) message *m_ptr; { vir_bytes src_addr, dst_addr; int dst_proc; size_t len; int s; /* Check if the call can be allowed. */ if((s = check_call_permission(m_ptr->m_source, 0, NULL)) != OK) return s; switch(m_ptr->m1_i1) { case SI_PROC_TAB: src_addr = (vir_bytes) rproc; len = sizeof(struct rproc) * NR_SYS_PROCS; break; case SI_PROCPUB_TAB: src_addr = (vir_bytes) rprocpub; len = sizeof(struct rprocpub) * NR_SYS_PROCS; break; default: return(EINVAL); } dst_proc = m_ptr->m_source; dst_addr = (vir_bytes) m_ptr->m1_p1; if (OK != (s=sys_datacopy(SELF, src_addr, dst_proc, dst_addr, len))) return(s); return(OK); } /*===========================================================================* * do_lookup * *===========================================================================*/ PUBLIC int do_lookup(m_ptr) message *m_ptr; { static char namebuf[100]; int len, r; struct rproc *rrp; struct rprocpub *rrpub; len = m_ptr->RS_NAME_LEN; if(len < 2 || len >= sizeof(namebuf)) { printf("RS: len too weird (%d)\n", len); return EINVAL; } if((r=sys_vircopy(m_ptr->m_source, D, (vir_bytes) m_ptr->RS_NAME, SELF, D, (vir_bytes) namebuf, len)) != OK) { printf("RS: name copy failed\n"); return r; } namebuf[len] = '\0'; rrp = lookup_slot_by_label(namebuf); if(!rrp) { return ESRCH; } rrpub = rrp->r_pub; m_ptr->RS_ENDPOINT = rrpub->endpoint; return OK; }
ducis/operating-system-labs
src.clean/servers/rs/request.c
C
mit
19,836
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2013, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #ifdef HAVE_LIMITS_H #include <limits.h> #endif #ifdef HAVE_NETINET_IN_H #include <netinet/in.h> #endif #ifdef HAVE_NETDB_H #include <netdb.h> #endif #ifdef HAVE_ARPA_INET_H #include <arpa/inet.h> #endif #ifdef __VMS #include <in.h> #include <inet.h> #endif #ifdef HAVE_PROCESS_H #include <process.h> #endif #if (defined(NETWARE) && defined(__NOVELL_LIBC__)) #undef in_addr_t #define in_addr_t unsigned long #endif /*********************************************************************** * Only for ares-enabled builds * And only for functions that fulfill the asynch resolver backend API * as defined in asyn.h, nothing else belongs in this file! **********************************************************************/ #ifdef CURLRES_ARES #include "urldata.h" #include "sendf.h" #include "hostip.h" #include "hash.h" #include "share.h" #include "strerror.h" #include "url.h" #include "multiif.h" #include "inet_pton.h" #include "connect.h" #include "select.h" #include "progress.h" #define _MPRINTF_REPLACE /* use our functions only */ #include <curl/mprintf.h> # if defined(CURL_STATICLIB) && !defined(CARES_STATICLIB) && \ (defined(WIN32) || defined(_WIN32) || defined(__SYMBIAN32__)) # define CARES_STATICLIB # endif # include <ares.h> # include <ares_version.h> /* really old c-ares didn't include this by itself */ #if ARES_VERSION >= 0x010500 /* c-ares 1.5.0 or later, the callback proto is modified */ #define HAVE_CARES_CALLBACK_TIMEOUTS 1 #endif #include "curl_memory.h" /* The last #include file should be: */ #include "memdebug.h" struct ResolverResults { int num_pending; /* number of ares_gethostbyname() requests */ Curl_addrinfo *temp_ai; /* intermediary result while fetching c-ares parts */ int last_status; }; /* * Curl_resolver_global_init() - the generic low-level asynchronous name * resolve API. Called from curl_global_init() to initialize global resolver * environment. Initializes ares library. */ int Curl_resolver_global_init(void) { #ifdef CARES_HAVE_ARES_LIBRARY_INIT if(ares_library_init(ARES_LIB_INIT_ALL)) { return CURLE_FAILED_INIT; } #endif return CURLE_OK; } /* * Curl_resolver_global_cleanup() * * Called from curl_global_cleanup() to destroy global resolver environment. * Deinitializes ares library. */ void Curl_resolver_global_cleanup(void) { #ifdef CARES_HAVE_ARES_LIBRARY_CLEANUP ares_library_cleanup(); #endif } /* * Curl_resolver_init() * * Called from curl_easy_init() -> Curl_open() to initialize resolver * URL-state specific environment ('resolver' member of the UrlState * structure). Fills the passed pointer by the initialized ares_channel. */ CURLcode Curl_resolver_init(void **resolver) { int status = ares_init((ares_channel*)resolver); if(status != ARES_SUCCESS) { if(status == ARES_ENOMEM) return CURLE_OUT_OF_MEMORY; else return CURLE_FAILED_INIT; } return CURLE_OK; /* make sure that all other returns from this function should destroy the ares channel before returning error! */ } /* * Curl_resolver_cleanup() * * Called from curl_easy_cleanup() -> Curl_close() to cleanup resolver * URL-state specific environment ('resolver' member of the UrlState * structure). Destroys the ares channel. */ void Curl_resolver_cleanup(void *resolver) { ares_destroy((ares_channel)resolver); } /* * Curl_resolver_duphandle() * * Called from curl_easy_duphandle() to duplicate resolver URL-state specific * environment ('resolver' member of the UrlState structure). Duplicates the * 'from' ares channel and passes the resulting channel to the 'to' pointer. */ int Curl_resolver_duphandle(void **to, void *from) { /* Clone the ares channel for the new handle */ if(ARES_SUCCESS != ares_dup((ares_channel*)to,(ares_channel)from)) return CURLE_FAILED_INIT; return CURLE_OK; } static void destroy_async_data (struct Curl_async *async); /* * Cancel all possibly still on-going resolves for this connection. */ void Curl_resolver_cancel(struct connectdata *conn) { if(conn && conn->data && conn->data->state.resolver) ares_cancel((ares_channel)conn->data->state.resolver); destroy_async_data(&conn->async); } /* * destroy_async_data() cleans up async resolver data. */ static void destroy_async_data (struct Curl_async *async) { if(async->hostname) free(async->hostname); if(async->os_specific) { struct ResolverResults *res = (struct ResolverResults *)async->os_specific; if(res) { if(res->temp_ai) { Curl_freeaddrinfo(res->temp_ai); res->temp_ai = NULL; } free(res); } async->os_specific = NULL; } async->hostname = NULL; } /* * Curl_resolver_getsock() is called when someone from the outside world * (using curl_multi_fdset()) wants to get our fd_set setup and we're talking * with ares. The caller must make sure that this function is only called when * we have a working ares channel. * * Returns: sockets-in-use-bitmap */ int Curl_resolver_getsock(struct connectdata *conn, curl_socket_t *socks, int numsocks) { struct timeval maxtime; struct timeval timebuf; struct timeval *timeout; long milli; int max = ares_getsock((ares_channel)conn->data->state.resolver, (ares_socket_t *)socks, numsocks); maxtime.tv_sec = CURL_TIMEOUT_RESOLVE; maxtime.tv_usec = 0; timeout = ares_timeout((ares_channel)conn->data->state.resolver, &maxtime, &timebuf); milli = (timeout->tv_sec * 1000) + (timeout->tv_usec/1000); if(milli == 0) milli += 10; Curl_expire(conn->data, milli); return max; } /* * waitperform() * * 1) Ask ares what sockets it currently plays with, then * 2) wait for the timeout period to check for action on ares' sockets. * 3) tell ares to act on all the sockets marked as "with action" * * return number of sockets it worked on */ static int waitperform(struct connectdata *conn, int timeout_ms) { struct SessionHandle *data = conn->data; int nfds; int bitmask; ares_socket_t socks[ARES_GETSOCK_MAXNUM]; struct pollfd pfd[ARES_GETSOCK_MAXNUM]; int i; int num = 0; bitmask = ares_getsock((ares_channel)data->state.resolver, socks, ARES_GETSOCK_MAXNUM); for(i=0; i < ARES_GETSOCK_MAXNUM; i++) { pfd[i].events = 0; pfd[i].revents = 0; if(ARES_GETSOCK_READABLE(bitmask, i)) { pfd[i].fd = socks[i]; pfd[i].events |= POLLRDNORM|POLLIN; } if(ARES_GETSOCK_WRITABLE(bitmask, i)) { pfd[i].fd = socks[i]; pfd[i].events |= POLLWRNORM|POLLOUT; } if(pfd[i].events != 0) num++; else break; } if(num) nfds = Curl_poll(pfd, num, timeout_ms); else nfds = 0; if(!nfds) /* Call ares_process() unconditonally here, even if we simply timed out above, as otherwise the ares name resolve won't timeout! */ ares_process_fd((ares_channel)data->state.resolver, ARES_SOCKET_BAD, ARES_SOCKET_BAD); else { /* move through the descriptors and ask for processing on them */ for(i=0; i < num; i++) ares_process_fd((ares_channel)data->state.resolver, pfd[i].revents & (POLLRDNORM|POLLIN)? pfd[i].fd:ARES_SOCKET_BAD, pfd[i].revents & (POLLWRNORM|POLLOUT)? pfd[i].fd:ARES_SOCKET_BAD); } return nfds; } /* * Curl_resolver_is_resolved() is called repeatedly to check if a previous * name resolve request has completed. It should also make sure to time-out if * the operation seems to take too long. * * Returns normal CURLcode errors. */ CURLcode Curl_resolver_is_resolved(struct connectdata *conn, struct Curl_dns_entry **dns) { struct SessionHandle *data = conn->data; struct ResolverResults *res = (struct ResolverResults *) conn->async.os_specific; CURLcode rc = CURLE_OK; *dns = NULL; waitperform(conn, 0); if(res && !res->num_pending) { (void)Curl_addrinfo_callback(conn, res->last_status, res->temp_ai); /* temp_ai ownership is moved to the connection, so we need not free-up them */ res->temp_ai = NULL; if(!conn->async.dns) { failf(data, "Could not resolve: %s (%s)", conn->async.hostname, ares_strerror(conn->async.status)); rc = conn->bits.proxy?CURLE_COULDNT_RESOLVE_PROXY: CURLE_COULDNT_RESOLVE_HOST; } else *dns = conn->async.dns; destroy_async_data(&conn->async); } return rc; } /* * Curl_resolver_wait_resolv() * * waits for a resolve to finish. This function should be avoided since using * this risk getting the multi interface to "hang". * * If 'entry' is non-NULL, make it point to the resolved dns entry * * Returns CURLE_COULDNT_RESOLVE_HOST if the host was not resolved, and * CURLE_OPERATION_TIMEDOUT if a time-out occurred. */ CURLcode Curl_resolver_wait_resolv(struct connectdata *conn, struct Curl_dns_entry **entry) { CURLcode rc=CURLE_OK; struct SessionHandle *data = conn->data; long timeout; struct timeval now = Curl_tvnow(); struct Curl_dns_entry *temp_entry; timeout = Curl_timeleft(data, &now, TRUE); if(!timeout) timeout = CURL_TIMEOUT_RESOLVE * 1000; /* default name resolve timeout */ /* Wait for the name resolve query to complete. */ for(;;) { struct timeval *tvp, tv, store; long timediff; int itimeout; int timeout_ms; itimeout = (timeout > (long)INT_MAX) ? INT_MAX : (int)timeout; store.tv_sec = itimeout/1000; store.tv_usec = (itimeout%1000)*1000; tvp = ares_timeout((ares_channel)data->state.resolver, &store, &tv); /* use the timeout period ares returned to us above if less than one second is left, otherwise just use 1000ms to make sure the progress callback gets called frequent enough */ if(!tvp->tv_sec) timeout_ms = (int)(tvp->tv_usec/1000); else timeout_ms = 1000; waitperform(conn, timeout_ms); Curl_resolver_is_resolved(conn,&temp_entry); if(conn->async.done) break; if(Curl_pgrsUpdate(conn)) { rc = CURLE_ABORTED_BY_CALLBACK; timeout = -1; /* trigger the cancel below */ } else { struct timeval now2 = Curl_tvnow(); timediff = Curl_tvdiff(now2, now); /* spent time */ timeout -= timediff?timediff:1; /* always deduct at least 1 */ now = now2; /* for next loop */ } if(timeout < 0) { /* our timeout, so we cancel the ares operation */ ares_cancel((ares_channel)data->state.resolver); break; } } /* Operation complete, if the lookup was successful we now have the entry in the cache. */ if(entry) *entry = conn->async.dns; if(rc) /* close the connection, since we can't return failure here without cleaning up this connection properly. TODO: remove this action from here, it is not a name resolver decision. */ conn->bits.close = TRUE; return rc; } /* Connects results to the list */ static void compound_results(struct ResolverResults *res, Curl_addrinfo *ai) { Curl_addrinfo *ai_tail; if(!ai) return; ai_tail = ai; while(ai_tail->ai_next) ai_tail = ai_tail->ai_next; /* Add the new results to the list of old results. */ ai_tail->ai_next = res->temp_ai; res->temp_ai = ai; } /* * ares_query_completed_cb() is the callback that ares will call when * the host query initiated by ares_gethostbyname() from Curl_getaddrinfo(), * when using ares, is completed either successfully or with failure. */ static void query_completed_cb(void *arg, /* (struct connectdata *) */ int status, #ifdef HAVE_CARES_CALLBACK_TIMEOUTS int timeouts, #endif struct hostent *hostent) { struct connectdata *conn = (struct connectdata *)arg; struct ResolverResults *res; #ifdef HAVE_CARES_CALLBACK_TIMEOUTS (void)timeouts; /* ignored */ #endif if(ARES_EDESTRUCTION == status) /* when this ares handle is getting destroyed, the 'arg' pointer may not be valid so only defer it when we know the 'status' says its fine! */ return; res = (struct ResolverResults *)conn->async.os_specific; res->num_pending--; if(CURL_ASYNC_SUCCESS == status) { Curl_addrinfo *ai = Curl_he2ai(hostent, conn->async.port); if(ai) { compound_results(res, ai); } } /* A successful result overwrites any previous error */ if(res->last_status != ARES_SUCCESS) res->last_status = status; } /* * Curl_resolver_getaddrinfo() - when using ares * * Returns name information about the given hostname and port number. If * successful, the 'hostent' is returned and the forth argument will point to * memory we need to free after use. That memory *MUST* be freed with * Curl_freeaddrinfo(), nothing else. */ Curl_addrinfo *Curl_resolver_getaddrinfo(struct connectdata *conn, const char *hostname, int port, int *waitp) { char *bufp; struct SessionHandle *data = conn->data; struct in_addr in; int family = PF_INET; #ifdef ENABLE_IPV6 /* CURLRES_IPV6 */ struct in6_addr in6; #endif /* CURLRES_IPV6 */ *waitp = 0; /* default to synchronous response */ /* First check if this is an IPv4 address string */ if(Curl_inet_pton(AF_INET, hostname, &in) > 0) { /* This is a dotted IP address 123.123.123.123-style */ return Curl_ip2addr(AF_INET, &in, hostname, port); } #ifdef ENABLE_IPV6 /* CURLRES_IPV6 */ /* Otherwise, check if this is an IPv6 address string */ if(Curl_inet_pton (AF_INET6, hostname, &in6) > 0) /* This must be an IPv6 address literal. */ return Curl_ip2addr(AF_INET6, &in6, hostname, port); switch(conn->ip_version) { default: #if ARES_VERSION >= 0x010601 family = PF_UNSPEC; /* supported by c-ares since 1.6.1, so for older c-ares versions this just falls through and defaults to PF_INET */ break; #endif case CURL_IPRESOLVE_V4: family = PF_INET; break; case CURL_IPRESOLVE_V6: family = PF_INET6; break; } #endif /* CURLRES_IPV6 */ bufp = strdup(hostname); if(bufp) { struct ResolverResults *res = NULL; Curl_safefree(conn->async.hostname); conn->async.hostname = bufp; conn->async.port = port; conn->async.done = FALSE; /* not done */ conn->async.status = 0; /* clear */ conn->async.dns = NULL; /* clear */ res = calloc(sizeof(struct ResolverResults),1); if(!res) { Curl_safefree(conn->async.hostname); conn->async.hostname = NULL; return NULL; } conn->async.os_specific = res; /* initial status - failed */ res->last_status = ARES_ENOTFOUND; #ifdef ENABLE_IPV6 /* CURLRES_IPV6 */ if(family == PF_UNSPEC) { if(Curl_ipv6works()) { res->num_pending = 2; /* areschannel is already setup in the Curl_open() function */ ares_gethostbyname((ares_channel)data->state.resolver, hostname, PF_INET, query_completed_cb, conn); ares_gethostbyname((ares_channel)data->state.resolver, hostname, PF_INET6, query_completed_cb, conn); } else { res->num_pending = 1; /* areschannel is already setup in the Curl_open() function */ ares_gethostbyname((ares_channel)data->state.resolver, hostname, PF_INET, query_completed_cb, conn); } } else #endif /* CURLRES_IPV6 */ { res->num_pending = 1; /* areschannel is already setup in the Curl_open() function */ ares_gethostbyname((ares_channel)data->state.resolver, hostname, family, query_completed_cb, conn); } *waitp = 1; /* expect asynchronous response */ } return NULL; /* no struct yet */ } CURLcode Curl_set_dns_servers(struct SessionHandle *data, char *servers) { CURLcode result = CURLE_NOT_BUILT_IN; int ares_result; /* If server is NULL or empty, this would purge all DNS servers * from ares library, which will cause any and all queries to fail. * So, just return OK if none are configured and don't actually make * any changes to c-ares. This lets c-ares use it's defaults, which * it gets from the OS (for instance from /etc/resolv.conf on Linux). */ if(!(servers && servers[0])) return CURLE_OK; #if (ARES_VERSION >= 0x010704) ares_result = ares_set_servers_csv(data->state.resolver, servers); switch(ares_result) { case ARES_SUCCESS: result = CURLE_OK; break; case ARES_ENOMEM: result = CURLE_OUT_OF_MEMORY; break; case ARES_ENOTINITIALIZED: case ARES_ENODATA: case ARES_EBADSTR: default: result = CURLE_BAD_FUNCTION_ARGUMENT; break; } #else /* too old c-ares version! */ (void)data; (void)(ares_result); #endif return result; } CURLcode Curl_set_dns_interface(struct SessionHandle *data, const char *interf) { #if (ARES_VERSION >= 0x010704) if(!interf) interf = ""; ares_set_local_dev((ares_channel)data->state.resolver, interf); return CURLE_OK; #else /* c-ares version too old! */ (void)data; (void)interf; return CURLE_NOT_BUILT_IN; #endif } CURLcode Curl_set_dns_local_ip4(struct SessionHandle *data, const char *local_ip4) { #if (ARES_VERSION >= 0x010704) uint32_t a4; if((!local_ip4) || (local_ip4[0] == 0)) { a4 = 0; /* disabled: do not bind to a specific address */ } else { if(Curl_inet_pton(AF_INET, local_ip4, &a4) != 1) { return CURLE_BAD_FUNCTION_ARGUMENT; } } ares_set_local_ip4((ares_channel)data->state.resolver, ntohl(a4)); return CURLE_OK; #else /* c-ares version too old! */ (void)data; (void)local_ip4; return CURLE_NOT_BUILT_IN; #endif } CURLcode Curl_set_dns_local_ip6(struct SessionHandle *data, const char *local_ip6) { #if (ARES_VERSION >= 0x010704) unsigned char a6[INET6_ADDRSTRLEN]; if((!local_ip6) || (local_ip6[0] == 0)) { /* disabled: do not bind to a specific address */ memset(a6, 0, sizeof(a6)); } else { if(Curl_inet_pton(AF_INET6, local_ip6, a6) != 1) { return CURLE_BAD_FUNCTION_ARGUMENT; } } ares_set_local_ip6((ares_channel)data->state.resolver, a6); return CURLE_OK; #else /* c-ares version too old! */ (void)data; (void)local_ip6; return CURLE_NOT_BUILT_IN; #endif } #endif /* CURLRES_ARES */
sidhujag/devcoin-wallet
src/curl/lib/asyn-ares.c
C
mit
19,853
/* * (c) copyright 1987 by the Vrije Universiteit, Amsterdam, The Netherlands. * See the copyright notice in the ACK home directory, in the file "Copyright". */ /* $Header$ */ #include <ctype.h> #include <stdlib.h> /* We do not use strtol here for backwards compatibility in behaviour on overflow. */ long atol(register const char *nptr) { long total = 0; int minus = 0; while (isspace(*nptr)) nptr++; if (*nptr == '+') nptr++; else if (*nptr == '-') { minus = 1; nptr++; } while (isdigit(*nptr)) { total *= 10; total += (*nptr++ - '0'); } return minus ? -total : total; }
ducis/operating-system-labs
src.clean/lib/libc/ansi/atol.c
C
mit
629
/* adddma.c */ #include <lib.h> #define adddma _adddma #include <unistd.h> #include <stdarg.h> int adddma(proc_e, start, size) endpoint_t proc_e; phys_bytes start; phys_bytes size; { message m; m.m2_i1= proc_e; m.m2_l1= start; m.m2_l2= size; return _syscall(MM, ADDDMA, &m); }
ducis/operating-system-labs
src.clean/lib/libc/other/_adddma.c
C
mit
314
/* * Syscall interface to knfsd. * * Copyright (C) 1995, 1996 Olaf Kirch <okir@monad.swb.de> */ #include <linux/slab.h> #include <linux/namei.h> #include <linux/ctype.h> #include <linux/sunrpc/svcsock.h> #include <linux/lockd/lockd.h> #include <linux/sunrpc/addr.h> #include <linux/sunrpc/gss_api.h> #include <linux/sunrpc/gss_krb5_enctypes.h> #include <linux/sunrpc/rpc_pipe_fs.h> #include <linux/module.h> #include "idmap.h" #include "nfsd.h" #include "cache.h" #include "state.h" #include "netns.h" /* * We have a single directory with several nodes in it. */ enum { NFSD_Root = 1, NFSD_List, NFSD_Export_features, NFSD_Fh, NFSD_FO_UnlockIP, NFSD_FO_UnlockFS, NFSD_Threads, NFSD_Pool_Threads, NFSD_Pool_Stats, NFSD_Reply_Cache_Stats, NFSD_Versions, NFSD_Ports, NFSD_MaxBlkSize, NFSD_SupportedEnctypes, /* * The below MUST come last. Otherwise we leave a hole in nfsd_files[] * with !CONFIG_NFSD_V4 and simple_fill_super() goes oops */ #ifdef CONFIG_NFSD_V4 NFSD_Leasetime, NFSD_Gracetime, NFSD_RecoveryDir, #endif }; /* * write() for these nodes. */ static ssize_t write_filehandle(struct file *file, char *buf, size_t size); static ssize_t write_unlock_ip(struct file *file, char *buf, size_t size); static ssize_t write_unlock_fs(struct file *file, char *buf, size_t size); static ssize_t write_threads(struct file *file, char *buf, size_t size); static ssize_t write_pool_threads(struct file *file, char *buf, size_t size); static ssize_t write_versions(struct file *file, char *buf, size_t size); static ssize_t write_ports(struct file *file, char *buf, size_t size); static ssize_t write_maxblksize(struct file *file, char *buf, size_t size); #ifdef CONFIG_NFSD_V4 static ssize_t write_leasetime(struct file *file, char *buf, size_t size); static ssize_t write_gracetime(struct file *file, char *buf, size_t size); static ssize_t write_recoverydir(struct file *file, char *buf, size_t size); #endif static ssize_t (*write_op[])(struct file *, char *, size_t) = { [NFSD_Fh] = write_filehandle, [NFSD_FO_UnlockIP] = write_unlock_ip, [NFSD_FO_UnlockFS] = write_unlock_fs, [NFSD_Threads] = write_threads, [NFSD_Pool_Threads] = write_pool_threads, [NFSD_Versions] = write_versions, [NFSD_Ports] = write_ports, [NFSD_MaxBlkSize] = write_maxblksize, #ifdef CONFIG_NFSD_V4 [NFSD_Leasetime] = write_leasetime, [NFSD_Gracetime] = write_gracetime, [NFSD_RecoveryDir] = write_recoverydir, #endif }; static ssize_t nfsctl_transaction_write(struct file *file, const char __user *buf, size_t size, loff_t *pos) { ino_t ino = file_inode(file)->i_ino; char *data; ssize_t rv; if (ino >= ARRAY_SIZE(write_op) || !write_op[ino]) return -EINVAL; data = simple_transaction_get(file, buf, size); if (IS_ERR(data)) return PTR_ERR(data); rv = write_op[ino](file, data, size); if (rv >= 0) { simple_transaction_set(file, rv); rv = size; } return rv; } static ssize_t nfsctl_transaction_read(struct file *file, char __user *buf, size_t size, loff_t *pos) { if (! file->private_data) { /* An attempt to read a transaction file without writing * causes a 0-byte write so that the file can return * state information */ ssize_t rv = nfsctl_transaction_write(file, buf, 0, pos); if (rv < 0) return rv; } return simple_transaction_read(file, buf, size, pos); } static const struct file_operations transaction_ops = { .write = nfsctl_transaction_write, .read = nfsctl_transaction_read, .release = simple_transaction_release, .llseek = default_llseek, }; static int exports_net_open(struct net *net, struct file *file) { int err; struct seq_file *seq; struct nfsd_net *nn = net_generic(net, nfsd_net_id); err = seq_open(file, &nfs_exports_op); if (err) return err; seq = file->private_data; seq->private = nn->svc_export_cache; return 0; } static int exports_proc_open(struct inode *inode, struct file *file) { return exports_net_open(current->nsproxy->net_ns, file); } static const struct file_operations exports_proc_operations = { .open = exports_proc_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release, .owner = THIS_MODULE, }; static int exports_nfsd_open(struct inode *inode, struct file *file) { return exports_net_open(inode->i_sb->s_fs_info, file); } static const struct file_operations exports_nfsd_operations = { .open = exports_nfsd_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release, .owner = THIS_MODULE, }; static int export_features_show(struct seq_file *m, void *v) { seq_printf(m, "0x%x 0x%x\n", NFSEXP_ALLFLAGS, NFSEXP_SECINFO_FLAGS); return 0; } static int export_features_open(struct inode *inode, struct file *file) { return single_open(file, export_features_show, NULL); } static const struct file_operations export_features_operations = { .open = export_features_open, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; #if defined(CONFIG_SUNRPC_GSS) || defined(CONFIG_SUNRPC_GSS_MODULE) static int supported_enctypes_show(struct seq_file *m, void *v) { seq_printf(m, KRB5_SUPPORTED_ENCTYPES); return 0; } static int supported_enctypes_open(struct inode *inode, struct file *file) { return single_open(file, supported_enctypes_show, NULL); } static const struct file_operations supported_enctypes_ops = { .open = supported_enctypes_open, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; #endif /* CONFIG_SUNRPC_GSS or CONFIG_SUNRPC_GSS_MODULE */ static const struct file_operations pool_stats_operations = { .open = nfsd_pool_stats_open, .read = seq_read, .llseek = seq_lseek, .release = nfsd_pool_stats_release, .owner = THIS_MODULE, }; static struct file_operations reply_cache_stats_operations = { .open = nfsd_reply_cache_stats_open, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; /*----------------------------------------------------------------------------*/ /* * payload - write methods */ /** * write_unlock_ip - Release all locks used by a client * * Experimental. * * Input: * buf: '\n'-terminated C string containing a * presentation format IP address * size: length of C string in @buf * Output: * On success: returns zero if all specified locks were released; * returns one if one or more locks were not released * On error: return code is negative errno value */ static ssize_t write_unlock_ip(struct file *file, char *buf, size_t size) { struct sockaddr_storage address; struct sockaddr *sap = (struct sockaddr *)&address; size_t salen = sizeof(address); char *fo_path; struct net *net = file->f_dentry->d_sb->s_fs_info; /* sanity check */ if (size == 0) return -EINVAL; if (buf[size-1] != '\n') return -EINVAL; fo_path = buf; if (qword_get(&buf, fo_path, size) < 0) return -EINVAL; if (rpc_pton(net, fo_path, size, sap, salen) == 0) return -EINVAL; return nlmsvc_unlock_all_by_ip(sap); } /** * write_unlock_fs - Release all locks on a local file system * * Experimental. * * Input: * buf: '\n'-terminated C string containing the * absolute pathname of a local file system * size: length of C string in @buf * Output: * On success: returns zero if all specified locks were released; * returns one if one or more locks were not released * On error: return code is negative errno value */ static ssize_t write_unlock_fs(struct file *file, char *buf, size_t size) { struct path path; char *fo_path; int error; /* sanity check */ if (size == 0) return -EINVAL; if (buf[size-1] != '\n') return -EINVAL; fo_path = buf; if (qword_get(&buf, fo_path, size) < 0) return -EINVAL; error = kern_path(fo_path, 0, &path); if (error) return error; /* * XXX: Needs better sanity checking. Otherwise we could end up * releasing locks on the wrong file system. * * For example: * 1. Does the path refer to a directory? * 2. Is that directory a mount point, or * 3. Is that directory the root of an exported file system? */ error = nlmsvc_unlock_all_by_sb(path.dentry->d_sb); path_put(&path); return error; } /** * write_filehandle - Get a variable-length NFS file handle by path * * On input, the buffer contains a '\n'-terminated C string comprised of * three alphanumeric words separated by whitespace. The string may * contain escape sequences. * * Input: * buf: * domain: client domain name * path: export pathname * maxsize: numeric maximum size of * @buf * size: length of C string in @buf * Output: * On success: passed-in buffer filled with '\n'-terminated C * string containing a ASCII hex text version * of the NFS file handle; * return code is the size in bytes of the string * On error: return code is negative errno value */ static ssize_t write_filehandle(struct file *file, char *buf, size_t size) { char *dname, *path; int uninitialized_var(maxsize); char *mesg = buf; int len; struct auth_domain *dom; struct knfsd_fh fh; struct net *net = file->f_dentry->d_sb->s_fs_info; if (size == 0) return -EINVAL; if (buf[size-1] != '\n') return -EINVAL; buf[size-1] = 0; dname = mesg; len = qword_get(&mesg, dname, size); if (len <= 0) return -EINVAL; path = dname+len+1; len = qword_get(&mesg, path, size); if (len <= 0) return -EINVAL; len = get_int(&mesg, &maxsize); if (len) return len; if (maxsize < NFS_FHSIZE) return -EINVAL; if (maxsize > NFS3_FHSIZE) maxsize = NFS3_FHSIZE; if (qword_get(&mesg, mesg, size)>0) return -EINVAL; /* we have all the words, they are in buf.. */ dom = unix_domain_find(dname); if (!dom) return -ENOMEM; len = exp_rootfh(net, dom, path, &fh, maxsize); auth_domain_put(dom); if (len) return len; mesg = buf; len = SIMPLE_TRANSACTION_LIMIT; qword_addhex(&mesg, &len, (char*)&fh.fh_base, fh.fh_size); mesg[-1] = '\n'; return mesg - buf; } /** * write_threads - Start NFSD, or report the current number of running threads * * Input: * buf: ignored * size: zero * Output: * On success: passed-in buffer filled with '\n'-terminated C * string numeric value representing the number of * running NFSD threads; * return code is the size in bytes of the string * On error: return code is zero * * OR * * Input: * buf: C string containing an unsigned * integer value representing the * number of NFSD threads to start * size: non-zero length of C string in @buf * Output: * On success: NFS service is started; * passed-in buffer filled with '\n'-terminated C * string numeric value representing the number of * running NFSD threads; * return code is the size in bytes of the string * On error: return code is zero or a negative errno value */ static ssize_t write_threads(struct file *file, char *buf, size_t size) { char *mesg = buf; int rv; struct net *net = file->f_dentry->d_sb->s_fs_info; if (size > 0) { int newthreads; rv = get_int(&mesg, &newthreads); if (rv) return rv; if (newthreads < 0) return -EINVAL; rv = nfsd_svc(newthreads, net); if (rv < 0) return rv; } else rv = nfsd_nrthreads(net); return scnprintf(buf, SIMPLE_TRANSACTION_LIMIT, "%d\n", rv); } /** * write_pool_threads - Set or report the current number of threads per pool * * Input: * buf: ignored * size: zero * * OR * * Input: * buf: C string containing whitespace- * separated unsigned integer values * representing the number of NFSD * threads to start in each pool * size: non-zero length of C string in @buf * Output: * On success: passed-in buffer filled with '\n'-terminated C * string containing integer values representing the * number of NFSD threads in each pool; * return code is the size in bytes of the string * On error: return code is zero or a negative errno value */ static ssize_t write_pool_threads(struct file *file, char *buf, size_t size) { /* if size > 0, look for an array of number of threads per node * and apply them then write out number of threads per node as reply */ char *mesg = buf; int i; int rv; int len; int npools; int *nthreads; struct net *net = file->f_dentry->d_sb->s_fs_info; mutex_lock(&nfsd_mutex); npools = nfsd_nrpools(net); if (npools == 0) { /* * NFS is shut down. The admin can start it by * writing to the threads file but NOT the pool_threads * file, sorry. Report zero threads. */ mutex_unlock(&nfsd_mutex); strcpy(buf, "0\n"); return strlen(buf); } nthreads = kcalloc(npools, sizeof(int), GFP_KERNEL); rv = -ENOMEM; if (nthreads == NULL) goto out_free; if (size > 0) { for (i = 0; i < npools; i++) { rv = get_int(&mesg, &nthreads[i]); if (rv == -ENOENT) break; /* fewer numbers than pools */ if (rv) goto out_free; /* syntax error */ rv = -EINVAL; if (nthreads[i] < 0) goto out_free; } rv = nfsd_set_nrthreads(i, nthreads, net); if (rv) goto out_free; } rv = nfsd_get_nrthreads(npools, nthreads, net); if (rv) goto out_free; mesg = buf; size = SIMPLE_TRANSACTION_LIMIT; for (i = 0; i < npools && size > 0; i++) { snprintf(mesg, size, "%d%c", nthreads[i], (i == npools-1 ? '\n' : ' ')); len = strlen(mesg); size -= len; mesg += len; } rv = mesg - buf; out_free: kfree(nthreads); mutex_unlock(&nfsd_mutex); return rv; } static ssize_t __write_versions(struct file *file, char *buf, size_t size) { char *mesg = buf; char *vers, *minorp, sign; int len, num, remaining; unsigned minor; ssize_t tlen = 0; char *sep; struct net *net = file->f_dentry->d_sb->s_fs_info; struct nfsd_net *nn = net_generic(net, nfsd_net_id); if (size>0) { if (nn->nfsd_serv) /* Cannot change versions without updating * nn->nfsd_serv->sv_xdrsize, and reallocing * rq_argp and rq_resp */ return -EBUSY; if (buf[size-1] != '\n') return -EINVAL; buf[size-1] = 0; vers = mesg; len = qword_get(&mesg, vers, size); if (len <= 0) return -EINVAL; do { sign = *vers; if (sign == '+' || sign == '-') num = simple_strtol((vers+1), &minorp, 0); else num = simple_strtol(vers, &minorp, 0); if (*minorp == '.') { if (num != 4) return -EINVAL; minor = simple_strtoul(minorp+1, NULL, 0); if (minor == 0) return -EINVAL; if (nfsd_minorversion(minor, sign == '-' ? NFSD_CLEAR : NFSD_SET) < 0) return -EINVAL; goto next; } switch(num) { case 2: case 3: case 4: nfsd_vers(num, sign == '-' ? NFSD_CLEAR : NFSD_SET); break; default: return -EINVAL; } next: vers += len + 1; } while ((len = qword_get(&mesg, vers, size)) > 0); /* If all get turned off, turn them back on, as * having no versions is BAD */ nfsd_reset_versions(); } /* Now write current state into reply buffer */ len = 0; sep = ""; remaining = SIMPLE_TRANSACTION_LIMIT; for (num=2 ; num <= 4 ; num++) if (nfsd_vers(num, NFSD_AVAIL)) { len = snprintf(buf, remaining, "%s%c%d", sep, nfsd_vers(num, NFSD_TEST)?'+':'-', num); sep = " "; if (len > remaining) break; remaining -= len; buf += len; tlen += len; } if (nfsd_vers(4, NFSD_AVAIL)) for (minor = 1; minor <= NFSD_SUPPORTED_MINOR_VERSION; minor++) { len = snprintf(buf, remaining, " %c4.%u", (nfsd_vers(4, NFSD_TEST) && nfsd_minorversion(minor, NFSD_TEST)) ? '+' : '-', minor); if (len > remaining) break; remaining -= len; buf += len; tlen += len; } len = snprintf(buf, remaining, "\n"); if (len > remaining) return -EINVAL; return tlen + len; } /** * write_versions - Set or report the available NFS protocol versions * * Input: * buf: ignored * size: zero * Output: * On success: passed-in buffer filled with '\n'-terminated C * string containing positive or negative integer * values representing the current status of each * protocol version; * return code is the size in bytes of the string * On error: return code is zero or a negative errno value * * OR * * Input: * buf: C string containing whitespace- * separated positive or negative * integer values representing NFS * protocol versions to enable ("+n") * or disable ("-n") * size: non-zero length of C string in @buf * Output: * On success: status of zero or more protocol versions has * been updated; passed-in buffer filled with * '\n'-terminated C string containing positive * or negative integer values representing the * current status of each protocol version; * return code is the size in bytes of the string * On error: return code is zero or a negative errno value */ static ssize_t write_versions(struct file *file, char *buf, size_t size) { ssize_t rv; mutex_lock(&nfsd_mutex); rv = __write_versions(file, buf, size); mutex_unlock(&nfsd_mutex); return rv; } /* * Zero-length write. Return a list of NFSD's current listener * transports. */ static ssize_t __write_ports_names(char *buf, struct net *net) { struct nfsd_net *nn = net_generic(net, nfsd_net_id); if (nn->nfsd_serv == NULL) return 0; return svc_xprt_names(nn->nfsd_serv, buf, SIMPLE_TRANSACTION_LIMIT); } /* * A single 'fd' number was written, in which case it must be for * a socket of a supported family/protocol, and we use it as an * nfsd listener. */ static ssize_t __write_ports_addfd(char *buf, struct net *net) { char *mesg = buf; int fd, err; struct nfsd_net *nn = net_generic(net, nfsd_net_id); err = get_int(&mesg, &fd); if (err != 0 || fd < 0) return -EINVAL; err = nfsd_create_serv(net); if (err != 0) return err; err = svc_addsock(nn->nfsd_serv, fd, buf, SIMPLE_TRANSACTION_LIMIT); if (err < 0) { nfsd_destroy(net); return err; } /* Decrease the count, but don't shut down the service */ nn->nfsd_serv->sv_nrthreads--; return err; } /* * A transport listener is added by writing it's transport name and * a port number. */ static ssize_t __write_ports_addxprt(char *buf, struct net *net) { char transport[16]; struct svc_xprt *xprt; int port, err; struct nfsd_net *nn = net_generic(net, nfsd_net_id); if (sscanf(buf, "%15s %5u", transport, &port) != 2) return -EINVAL; if (port < 1 || port > USHRT_MAX) return -EINVAL; err = nfsd_create_serv(net); if (err != 0) return err; err = svc_create_xprt(nn->nfsd_serv, transport, net, PF_INET, port, SVC_SOCK_ANONYMOUS); if (err < 0) goto out_err; err = svc_create_xprt(nn->nfsd_serv, transport, net, PF_INET6, port, SVC_SOCK_ANONYMOUS); if (err < 0 && err != -EAFNOSUPPORT) goto out_close; /* Decrease the count, but don't shut down the service */ nn->nfsd_serv->sv_nrthreads--; return 0; out_close: xprt = svc_find_xprt(nn->nfsd_serv, transport, net, PF_INET, port); if (xprt != NULL) { svc_close_xprt(xprt); svc_xprt_put(xprt); } out_err: nfsd_destroy(net); return err; } static ssize_t __write_ports(struct file *file, char *buf, size_t size, struct net *net) { if (size == 0) return __write_ports_names(buf, net); if (isdigit(buf[0])) return __write_ports_addfd(buf, net); if (isalpha(buf[0])) return __write_ports_addxprt(buf, net); return -EINVAL; } /** * write_ports - Pass a socket file descriptor or transport name to listen on * * Input: * buf: ignored * size: zero * Output: * On success: passed-in buffer filled with a '\n'-terminated C * string containing a whitespace-separated list of * named NFSD listeners; * return code is the size in bytes of the string * On error: return code is zero or a negative errno value * * OR * * Input: * buf: C string containing an unsigned * integer value representing a bound * but unconnected socket that is to be * used as an NFSD listener; listen(3) * must be called for a SOCK_STREAM * socket, otherwise it is ignored * size: non-zero length of C string in @buf * Output: * On success: NFS service is started; * passed-in buffer filled with a '\n'-terminated C * string containing a unique alphanumeric name of * the listener; * return code is the size in bytes of the string * On error: return code is a negative errno value * * OR * * Input: * buf: C string containing a transport * name and an unsigned integer value * representing the port to listen on, * separated by whitespace * size: non-zero length of C string in @buf * Output: * On success: returns zero; NFS service is started * On error: return code is a negative errno value */ static ssize_t write_ports(struct file *file, char *buf, size_t size) { ssize_t rv; struct net *net = file->f_dentry->d_sb->s_fs_info; mutex_lock(&nfsd_mutex); rv = __write_ports(file, buf, size, net); mutex_unlock(&nfsd_mutex); return rv; } int nfsd_max_blksize; /** * write_maxblksize - Set or report the current NFS blksize * * Input: * buf: ignored * size: zero * * OR * * Input: * buf: C string containing an unsigned * integer value representing the new * NFS blksize * size: non-zero length of C string in @buf * Output: * On success: passed-in buffer filled with '\n'-terminated C string * containing numeric value of the current NFS blksize * setting; * return code is the size in bytes of the string * On error: return code is zero or a negative errno value */ static ssize_t write_maxblksize(struct file *file, char *buf, size_t size) { char *mesg = buf; struct net *net = file->f_dentry->d_sb->s_fs_info; struct nfsd_net *nn = net_generic(net, nfsd_net_id); if (size > 0) { int bsize; int rv = get_int(&mesg, &bsize); if (rv) return rv; /* force bsize into allowed range and * required alignment. */ if (bsize < 1024) bsize = 1024; if (bsize > NFSSVC_MAXBLKSIZE) bsize = NFSSVC_MAXBLKSIZE; bsize &= ~(1024-1); mutex_lock(&nfsd_mutex); if (nn->nfsd_serv) { mutex_unlock(&nfsd_mutex); return -EBUSY; } nfsd_max_blksize = bsize; mutex_unlock(&nfsd_mutex); } return scnprintf(buf, SIMPLE_TRANSACTION_LIMIT, "%d\n", nfsd_max_blksize); } #ifdef CONFIG_NFSD_V4 static ssize_t __nfsd4_write_time(struct file *file, char *buf, size_t size, time_t *time, struct nfsd_net *nn) { char *mesg = buf; int rv, i; if (size > 0) { if (nn->nfsd_serv) return -EBUSY; rv = get_int(&mesg, &i); if (rv) return rv; /* * Some sanity checking. We don't have a reason for * these particular numbers, but problems with the * extremes are: * - Too short: the briefest network outage may * cause clients to lose all their locks. Also, * the frequent polling may be wasteful. * - Too long: do you really want reboot recovery * to take more than an hour? Or to make other * clients wait an hour before being able to * revoke a dead client's locks? */ if (i < 10 || i > 3600) return -EINVAL; *time = i; } return scnprintf(buf, SIMPLE_TRANSACTION_LIMIT, "%ld\n", *time); } static ssize_t nfsd4_write_time(struct file *file, char *buf, size_t size, time_t *time, struct nfsd_net *nn) { ssize_t rv; mutex_lock(&nfsd_mutex); rv = __nfsd4_write_time(file, buf, size, time, nn); mutex_unlock(&nfsd_mutex); return rv; } /** * write_leasetime - Set or report the current NFSv4 lease time * * Input: * buf: ignored * size: zero * * OR * * Input: * buf: C string containing an unsigned * integer value representing the new * NFSv4 lease expiry time * size: non-zero length of C string in @buf * Output: * On success: passed-in buffer filled with '\n'-terminated C * string containing unsigned integer value of the * current lease expiry time; * return code is the size in bytes of the string * On error: return code is zero or a negative errno value */ static ssize_t write_leasetime(struct file *file, char *buf, size_t size) { struct net *net = file->f_dentry->d_sb->s_fs_info; struct nfsd_net *nn = net_generic(net, nfsd_net_id); return nfsd4_write_time(file, buf, size, &nn->nfsd4_lease, nn); } /** * write_gracetime - Set or report current NFSv4 grace period time * * As above, but sets the time of the NFSv4 grace period. * * Note this should never be set to less than the *previous* * lease-period time, but we don't try to enforce this. (In the common * case (a new boot), we don't know what the previous lease time was * anyway.) */ static ssize_t write_gracetime(struct file *file, char *buf, size_t size) { struct net *net = file->f_dentry->d_sb->s_fs_info; struct nfsd_net *nn = net_generic(net, nfsd_net_id); return nfsd4_write_time(file, buf, size, &nn->nfsd4_grace, nn); } static ssize_t __write_recoverydir(struct file *file, char *buf, size_t size, struct nfsd_net *nn) { char *mesg = buf; char *recdir; int len, status; if (size > 0) { if (nn->nfsd_serv) return -EBUSY; if (size > PATH_MAX || buf[size-1] != '\n') return -EINVAL; buf[size-1] = 0; recdir = mesg; len = qword_get(&mesg, recdir, size); if (len <= 0) return -EINVAL; status = nfs4_reset_recoverydir(recdir); if (status) return status; } return scnprintf(buf, SIMPLE_TRANSACTION_LIMIT, "%s\n", nfs4_recoverydir()); } /** * write_recoverydir - Set or report the pathname of the recovery directory * * Input: * buf: ignored * size: zero * * OR * * Input: * buf: C string containing the pathname * of the directory on a local file * system containing permanent NFSv4 * recovery data * size: non-zero length of C string in @buf * Output: * On success: passed-in buffer filled with '\n'-terminated C string * containing the current recovery pathname setting; * return code is the size in bytes of the string * On error: return code is zero or a negative errno value */ static ssize_t write_recoverydir(struct file *file, char *buf, size_t size) { ssize_t rv; struct net *net = file->f_dentry->d_sb->s_fs_info; struct nfsd_net *nn = net_generic(net, nfsd_net_id); mutex_lock(&nfsd_mutex); rv = __write_recoverydir(file, buf, size, nn); mutex_unlock(&nfsd_mutex); return rv; } #endif /*----------------------------------------------------------------------------*/ /* * populating the filesystem. */ static int nfsd_fill_super(struct super_block * sb, void * data, int silent) { static struct tree_descr nfsd_files[] = { [NFSD_List] = {"exports", &exports_nfsd_operations, S_IRUGO}, [NFSD_Export_features] = {"export_features", &export_features_operations, S_IRUGO}, [NFSD_FO_UnlockIP] = {"unlock_ip", &transaction_ops, S_IWUSR|S_IRUSR}, [NFSD_FO_UnlockFS] = {"unlock_filesystem", &transaction_ops, S_IWUSR|S_IRUSR}, [NFSD_Fh] = {"filehandle", &transaction_ops, S_IWUSR|S_IRUSR}, [NFSD_Threads] = {"threads", &transaction_ops, S_IWUSR|S_IRUSR}, [NFSD_Pool_Threads] = {"pool_threads", &transaction_ops, S_IWUSR|S_IRUSR}, [NFSD_Pool_Stats] = {"pool_stats", &pool_stats_operations, S_IRUGO}, [NFSD_Reply_Cache_Stats] = {"reply_cache_stats", &reply_cache_stats_operations, S_IRUGO}, [NFSD_Versions] = {"versions", &transaction_ops, S_IWUSR|S_IRUSR}, [NFSD_Ports] = {"portlist", &transaction_ops, S_IWUSR|S_IRUGO}, [NFSD_MaxBlkSize] = {"max_block_size", &transaction_ops, S_IWUSR|S_IRUGO}, #if defined(CONFIG_SUNRPC_GSS) || defined(CONFIG_SUNRPC_GSS_MODULE) [NFSD_SupportedEnctypes] = {"supported_krb5_enctypes", &supported_enctypes_ops, S_IRUGO}, #endif /* CONFIG_SUNRPC_GSS or CONFIG_SUNRPC_GSS_MODULE */ #ifdef CONFIG_NFSD_V4 [NFSD_Leasetime] = {"nfsv4leasetime", &transaction_ops, S_IWUSR|S_IRUSR}, [NFSD_Gracetime] = {"nfsv4gracetime", &transaction_ops, S_IWUSR|S_IRUSR}, [NFSD_RecoveryDir] = {"nfsv4recoverydir", &transaction_ops, S_IWUSR|S_IRUSR}, #endif /* last one */ {""} }; struct net *net = sb->s_ns; int ret; ret = simple_fill_super(sb, 0x6e667364, nfsd_files); if (ret) return ret; sb->s_fs_info = get_net(net); return 0; } static struct dentry *nfsd_mount(struct file_system_type *fs_type, int flags, const char *dev_name, void *data) { return mount_ns(fs_type, flags, NULL, current->nsproxy->net_ns, nfsd_fill_super); } static void nfsd_umount(struct super_block *sb) { struct net *net = sb->s_fs_info; kill_litter_super(sb); put_net(net); } static struct file_system_type nfsd_fs_type = { .owner = THIS_MODULE, .name = "nfsd", .mount = nfsd_mount, .kill_sb = nfsd_umount, .fs_flags = FS_VIRTUALIZED, }; MODULE_ALIAS_FS("nfsd"); #ifdef CONFIG_PROC_FS static int create_proc_exports_entry(void) { struct proc_dir_entry *entry; entry = proc_mkdir("fs/nfs", NULL); if (!entry) return -ENOMEM; entry = proc_create("exports", 0, entry, &exports_proc_operations); if (!entry) { remove_proc_entry("fs/nfs", NULL); return -ENOMEM; } return 0; } #else /* CONFIG_PROC_FS */ static int create_proc_exports_entry(void) { return 0; } #endif int nfsd_net_id; static __net_init int nfsd_init_net(struct net *net) { int retval; struct nfsd_net *nn = net_generic(net, nfsd_net_id); retval = nfsd_export_init(net); if (retval) goto out_export_error; retval = nfsd_idmap_init(net); if (retval) goto out_idmap_error; nn->nfsd4_lease = 90; /* default lease time */ nn->nfsd4_grace = 90; return 0; out_idmap_error: nfsd_export_shutdown(net); out_export_error: return retval; } static __net_exit void nfsd_exit_net(struct net *net) { nfsd_idmap_shutdown(net); nfsd_export_shutdown(net); } static struct pernet_operations nfsd_net_ops = { .init = nfsd_init_net, .exit = nfsd_exit_net, .id = &nfsd_net_id, .size = sizeof(struct nfsd_net), }; static int __init init_nfsd(void) { int retval; printk(KERN_INFO "Installing knfsd (copyright (C) 1996 okir@monad.swb.de).\n"); retval = register_cld_notifier(); if (retval) return retval; retval = register_pernet_subsys(&nfsd_net_ops); if (retval < 0) goto out_unregister_notifier; retval = nfsd4_init_slabs(); if (retval) goto out_unregister_pernet; nfs4_state_init(); retval = nfsd_fault_inject_init(); /* nfsd fault injection controls */ if (retval) goto out_free_slabs; nfsd_stat_init(); /* Statistics */ retval = nfsd_reply_cache_init(); if (retval) goto out_free_stat; nfsd_lockd_init(); /* lockd->nfsd callbacks */ retval = create_proc_exports_entry(); if (retval) goto out_free_lockd; retval = register_filesystem(&nfsd_fs_type); if (retval) goto out_free_all; return 0; out_free_all: remove_proc_entry("fs/nfs/exports", NULL); remove_proc_entry("fs/nfs", NULL); out_free_lockd: nfsd_lockd_shutdown(); nfsd_reply_cache_shutdown(); out_free_stat: nfsd_stat_shutdown(); nfsd_fault_inject_cleanup(); out_free_slabs: nfsd4_free_slabs(); out_unregister_pernet: unregister_pernet_subsys(&nfsd_net_ops); out_unregister_notifier: unregister_cld_notifier(); return retval; } static void __exit exit_nfsd(void) { nfsd_reply_cache_shutdown(); remove_proc_entry("fs/nfs/exports", NULL); remove_proc_entry("fs/nfs", NULL); nfsd_stat_shutdown(); nfsd_lockd_shutdown(); nfsd4_free_slabs(); nfsd_fault_inject_cleanup(); unregister_filesystem(&nfsd_fs_type); unregister_pernet_subsys(&nfsd_net_ops); unregister_cld_notifier(); } MODULE_AUTHOR("Olaf Kirch <okir@monad.swb.de>"); MODULE_LICENSE("GPL"); module_init(init_nfsd) module_exit(exit_nfsd)
zoobab/vzkernel
fs/nfsd/nfsctl.c
C
gpl-2.0
31,358
/* * Copyright (C) 2012 Spreadtrum Communications Inc. * * This software is licensed under the terms of the GNU General Public * License version 2, as published by the Free Software Foundation, and * may be copied, distributed, and modified under those terms. * * This program 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. */ #include <linux/kernel.h> #include <linux/init.h> #include <linux/platform_device.h> #include <asm/io.h> #include <asm/setup.h> #include <asm/mach/time.h> #include <asm/mach/arch.h> #include <asm/mach-types.h> #include <asm/hardware/gic.h> #include <asm/hardware/cache-l2x0.h> #include <asm/localtimer.h> #include <mach/hardware.h> #include <linux/i2c.h> #include <linux/i2c/ft5306_ts.h> #include <linux/i2c/lis3dh.h> #include <linux/i2c/ltr_558als.h> #include <linux/akm8975.h> #include <linux/spi/spi.h> #include <mach/board.h> #include <mach/serial_sprd.h> #include <mach/adi.h> #include <mach/adc.h> #include "../devices.h" #include <linux/gpio.h> #include <linux/mpu.h> #include <linux/akm8975.h> #include <linux/irq.h> #include <mach/sci.h> #include <mach/hardware.h> #include <mach/regs_glb.h> #include <mach/regs_ahb.h> #include <mach/pinmap.h> /* IRQ's for the multi sensor board */ #define MPUIRQ_GPIO 212 extern void __init sc8825_reserve(void); extern void __init sci_map_io(void); extern void __init sc8825_init_irq(void); extern void __init sc8825_timer_init(void); extern int __init sc8825_regulator_init(void); extern int __init sci_clock_init(void); #ifdef CONFIG_ANDROID_RAM_CONSOLE extern int __init sprd_ramconsole_init(void); #endif static struct platform_device rfkill_device; static struct platform_device kb_backlight_device; static struct platform_device *devices[] __initdata = { &sprd_serial_device0, &sprd_serial_device1, &sprd_serial_device2, &sprd_device_rtc, &sprd_nand_device, &sprd_lcd_device0, &sprd_backlight_device, &sprd_i2c_device0, &sprd_i2c_device1, &sprd_i2c_device2, &sprd_i2c_device3, &sprd_spi0_device, &sprd_spi1_device, &sprd_spi2_device, &sprd_keypad_device, &sprd_audio_platform_pcm_device, &sprd_audio_cpu_dai_vaudio_device, &sprd_audio_cpu_dai_vbc_device, &sprd_audio_codec_sprd_codec_device, &sprd_audio_cpu_dai_i2s_device, &sprd_audio_cpu_dai_i2s_device1, &sprd_audio_codec_null_codec_device, &sprd_battery_device, #ifdef CONFIG_ANDROID_PMEM &sprd_pmem_device, &sprd_pmem_adsp_device, #endif #ifdef CONFIG_ION &sprd_ion_dev, #endif &sprd_emmc_device, &sprd_sdio0_device, &sprd_sdio1_device, &sprd_sdio2_device, &sprd_vsp_device, &sprd_dcam_device, &sprd_scale_device, &sprd_rotation_device, &sprd_sensor_device, &sprd_isp_device, &sprd_ahb_bm0_device, &sprd_ahb_bm1_device, &sprd_ahb_bm2_device, &sprd_ahb_bm3_device, &sprd_ahb_bm4_device, &sprd_axi_bm0_device, &sprd_axi_bm1_device, &sprd_axi_bm2_device, #ifdef CONFIG_SIPC &sprd_cproc_td_device, &sprd_spipe_td_device, &sprd_slog_td_device, &sprd_stty_td_device, #endif &kb_backlight_device, &rfkill_device, }; /* RFKILL */ static struct resource rfkill_resources[] = { { .name = "bt_reset", .start = GPIO_BT_RESET, .end = GPIO_BT_RESET, .flags = IORESOURCE_IO, }, }; static struct platform_device rfkill_device = { .name = "rfkill", .id = -1, .num_resources = ARRAY_SIZE(rfkill_resources), .resource = rfkill_resources, }; /* keypad backlight */ static struct platform_device kb_backlight_device = { .name = "keyboard-backlight", .id = -1, }; static struct sys_timer sc8825_timer = { .init = sc8825_timer_init, }; static int calibration_mode = false; static int __init calibration_start(char *str) { if(str) pr_info("modem calibartion:%s\n", str); calibration_mode = true; return 1; } __setup("calibration=", calibration_start); int in_calibration(void) { return (calibration_mode == true); } EXPORT_SYMBOL(in_calibration); static void __init sprd_add_otg_device(void) { /* * if in calibrtaion mode, we do nothing, modem will handle everything */ if (calibration_mode) return; platform_device_register(&sprd_otg_device); } static struct serial_data plat_data0 = { .wakeup_type = BT_RTS_HIGH_WHEN_SLEEP, .clk = 48000000, }; static struct serial_data plat_data1 = { .wakeup_type = BT_RTS_HIGH_WHEN_SLEEP, .clk = 26000000, }; static struct serial_data plat_data2 = { .wakeup_type = BT_RTS_HIGH_WHEN_SLEEP, .clk = 26000000, }; static struct ft5x0x_ts_platform_data ft5x0x_ts_info = { .irq_gpio_number = GPIO_TOUCH_IRQ, .reset_gpio_number = GPIO_TOUCH_RESET, .vdd_name = "vdd28", }; static struct ltr558_pls_platform_data ltr558_pls_info = { .irq_gpio_number = GPIO_PLSENSOR_IRQ, }; static struct lis3dh_acc_platform_data lis3dh_plat_data = { .poll_interval = 10, .min_interval = 10, .g_range = LIS3DH_ACC_G_2G, .axis_map_x = 1, .axis_map_y = 0, .axis_map_z = 2, .negate_x = 0, .negate_y = 0, .negate_z = 1 }; struct akm8975_platform_data akm8975_platform_d = { .mag_low_x = -20480, .mag_high_x = 20479, .mag_low_y = -20480, .mag_high_y = 20479, .mag_low_z = -20480, .mag_high_z = 20479, }; static struct mpu_platform_data mpu9150_platform_data = { .int_config = 0x00, .level_shifter = 0, .orientation = { -1, 0, 0, 0, -1, 0, 0, 0, +1 }, .sec_slave_type = SECONDARY_SLAVE_TYPE_COMPASS, .sec_slave_id = COMPASS_ID_AK8963, .secondary_i2c_addr = 0x0C, .secondary_orientation = { 0, -1, 0, 1, 0, 0, 0, 0, 1 }, .key = {0xec, 0x06, 0x17, 0xdf, 0x77, 0xfc, 0xe6, 0xac, 0x7b, 0x6f, 0x12, 0x8a, 0x1d, 0x63, 0x67, 0x37}, }; static struct i2c_board_info i2c2_boardinfo[] = { { I2C_BOARD_INFO(LIS3DH_ACC_I2C_NAME, LIS3DH_ACC_I2C_ADDR), .platform_data = &lis3dh_plat_data, }, { I2C_BOARD_INFO("mpu9150", 0x68), .irq = MPUIRQ_GPIO, .platform_data = &mpu9150_platform_data, }, { I2C_BOARD_INFO(LTR558_I2C_NAME, LTR558_I2C_ADDR), .platform_data = &ltr558_pls_info, }, { I2C_BOARD_INFO("BEKEN_FM", 0x70), }, /* { I2C_BOARD_INFO(AKM8975_I2C_NAME, AKM8975_I2C_ADDR), .platform_data = &akm8975_platform_d, },*/ }; static struct i2c_board_info i2c1_boardinfo[] = { {I2C_BOARD_INFO("sensor_main",0x3C),}, {I2C_BOARD_INFO("sensor_sub",0x21),}, }; static struct i2c_board_info i2c0_boardinfo[] = { { I2C_BOARD_INFO(FT5206_TS_DEVICE, FT5206_TS_ADDR), .platform_data = &ft5x0x_ts_info, }, }; static int sc8810_add_i2c_devices(void) { i2c_register_board_info(2, i2c2_boardinfo, ARRAY_SIZE(i2c2_boardinfo)); i2c_register_board_info(1, i2c1_boardinfo, ARRAY_SIZE(i2c1_boardinfo)); i2c_register_board_info(0, i2c0_boardinfo, ARRAY_SIZE(i2c0_boardinfo)); return 0; } struct platform_device audio_pa_amplifier_device = { .name = "speaker-pa", .id = -1, }; static int audio_pa_amplifier_l(u32 cmd, void *data) { int ret = 0; if (cmd < 0) { /* get speaker amplifier status : enabled or disabled */ ret = 0; } else { /* set speaker amplifier */ } return ret; } const char * sc8825_regulator_map[] = { /*supply source, consumer0, consumer1, ..., NULL */ "vdd28", "iic_vdd", "ctp_vdd", NULL, "vddsd0", "tflash_vcc", NULL, "vddsim0", "nfc_vcc", NULL, "vddsim1", "sim_vcc", NULL, NULL, }; int __init sc8825_regulator_init(void) { static struct platform_device sc8825_regulator_device = { .name = "sprd-regulator", .id = -1, .dev = {.platform_data = sc8825_regulator_map}, }; return platform_device_register(&sc8825_regulator_device); } int __init sc8825_clock_init_early(void) { /* FIXME: Force disable all unused clocks */ sci_glb_clr(REG_AHB_AHB_CTL0, BIT_AXIBUSMON2_EB | BIT_AXIBUSMON1_EB | BIT_AXIBUSMON0_EB | // BIT_EMC_EB | // BIT_AHB_ARCH_EB | // BIT_SPINLOCK_EB | BIT_SDIO2_EB | BIT_EMMC_EB | // BIT_DISPC_EB | BIT_G3D_EB | BIT_SDIO1_EB | BIT_DRM_EB | BIT_BUSMON4_EB | BIT_BUSMON3_EB | BIT_BUSMON2_EB | BIT_ROT_EB | BIT_VSP_EB | BIT_ISP_EB | BIT_BUSMON1_EB | BIT_DCAM_MIPI_EB | BIT_CCIR_EB | BIT_NFC_EB | BIT_BUSMON0_EB | // BIT_DMA_EB | // BIT_USBD_EB | BIT_SDIO0_EB | // BIT_LCDC_EB | BIT_CCIR_IN_EB | BIT_DCAM_EB | 0); sci_glb_clr(REG_AHB_AHB_CTL2, // BIT_DISPMTX_CLK_EN | BIT_MMMTX_CLK_EN | // BIT_DISPC_CORE_CLK_EN| // BIT_LCDC_CORE_CLK_EN| BIT_ISP_CORE_CLK_EN | BIT_VSP_CORE_CLK_EN | BIT_DCAM_CORE_CLK_EN| 0); sci_glb_clr(REG_AHB_AHB_CTL3, // BIT_CLK_ULPI_EN | // BIT_CLK_USB_REF_EN | 0); sci_glb_clr(REG_GLB_GEN0, BIT_IC3_EB | BIT_IC2_EB | BIT_IC1_EB | // BIT_RTC_TMR_EB | // BIT_RTC_SYST0_EB | BIT_RTC_KPD_EB | BIT_IIS1_EB | // BIT_RTC_EIC_EB | BIT_UART2_EB | // BIT_UART1_EB | BIT_UART0_EB | // BIT_SYST0_EB | BIT_SPI1_EB | BIT_SPI0_EB | // BIT_SIM1_EB | // BIT_EPT_EB | BIT_CCIR_MCLK_EN | // BIT_PINREG_EB | BIT_IIS0_EB | // BIT_MCU_DSP_RST | // BIT_EIC_EB | BIT_KPD_EB | BIT_EFUSE_EB | // BIT_ADI_EB | // BIT_GPIO_EB | BIT_I2C0_EB | // BIT_SIM0_EB | // BIT_TMR_EB | BIT_SPI2_EB | BIT_UART3_EB | 0); sci_glb_clr(REG_AHB_CA5_CFG, // BIT_CA5_CLK_DBG_EN | 0); sci_glb_clr(REG_GLB_GEN1, BIT_AUDIF_AUTO_EN | BIT_VBC_EN | BIT_AUD_TOP_EB | BIT_AUD_IF_EB | BIT_CLK_AUX1_EN | BIT_CLK_AUX0_EN | 0); sci_glb_clr(REG_GLB_CLK_EN, BIT_PWM3_EB | //BIT_PWM2_EB | BIT_PWM1_EB | // BIT_PWM0_EB | 0); sci_glb_clr(REG_GLB_PCTRL, // BIT_MCU_MPLL_EN | // BIT_MCU_TDPLL_EN | // BIT_MCU_DPLL_EN | BIT_MCU_GPLL_EN); /* clk_gpu */ sci_glb_set(REG_GLB_TD_PLL_CTL, // BIT_TDPLL_DIV2OUT_FORCE_PD | /* clk_384m */ // BIT_TDPLL_DIV3OUT_FORCE_PD | /* clk_256m */ // BIT_TDPLL_DIV4OUT_FORCE_PD | /* clk_192m */ // BIT_TDPLL_DIV5OUT_FORCE_PD | /* clk_153p6m */ 0); printk("sc8825 clock module early init ok\n"); return 0; } static void __init sc8825_init_machine(void) { #ifdef CONFIG_ANDROID_RAM_CONSOLE sprd_ramconsole_init(); #endif sci_adc_init((void __iomem *)ADC_BASE); sc8825_regulator_init(); sprd_add_otg_device(); platform_device_add_data(&sprd_serial_device0,(const void*)&plat_data0,sizeof(plat_data0)); platform_device_add_data(&sprd_serial_device1,(const void*)&plat_data1,sizeof(plat_data1)); platform_device_add_data(&sprd_serial_device2,(const void*)&plat_data2,sizeof(plat_data2)); platform_add_devices(devices, ARRAY_SIZE(devices)); sc8810_add_i2c_devices(); } extern void sc8825_enable_timer_early(void); static void __init sc8825_init_early(void) { /* earlier init request than irq and timer */ sc8825_clock_init_early(); sc8825_enable_timer_early(); sci_adi_init(); } /* * Setup the memory banks. */ static void __init sc8825_fixup(struct machine_desc *desc, struct tag *tags, char **cmdline, struct meminfo *mi) { } MACHINE_START(SC8825OPENPHONE, "sc8825") .reserve = sc8825_reserve, .map_io = sci_map_io, .fixup = sc8825_fixup, .init_early = sc8825_init_early, .init_irq = sc8825_init_irq, .timer = &sc8825_timer, .init_machine = sc8825_init_machine, MACHINE_END
voltagex/kernel-sprdb2g_gonk4.0_6821
arch/arm/mach-sc8825/board_sp6825gb/board.c
C
gpl-2.0
11,412
/* * Secure Digital Host Controller Interface ACPI driver. * * Copyright (c) 2012, Intel Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope 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 * this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #include <linux/init.h> #include <linux/export.h> #include <linux/module.h> #include <linux/device.h> #include <linux/platform_device.h> #include <linux/ioport.h> #include <linux/io.h> #include <linux/dma-mapping.h> #include <linux/compiler.h> #include <linux/stddef.h> #include <linux/bitops.h> #include <linux/types.h> #include <linux/err.h> #include <linux/gpio/consumer.h> #include <linux/interrupt.h> #include <linux/acpi.h> #include <linux/pm.h> #include <linux/pm_runtime.h> #include <linux/delay.h> #include <linux/mmc/host.h> #include <linux/mmc/pm.h> #include <linux/mmc/sdhci.h> #include "sdhci.h" enum { SDHCI_ACPI_SD_CD = BIT(0), SDHCI_ACPI_RUNTIME_PM = BIT(1), }; struct sdhci_acpi_chip { const struct sdhci_ops *ops; unsigned int quirks; unsigned int quirks2; unsigned long caps; unsigned int caps2; mmc_pm_flag_t pm_caps; }; struct sdhci_acpi_slot { const struct sdhci_acpi_chip *chip; unsigned int quirks; unsigned int quirks2; unsigned long caps; unsigned int caps2; mmc_pm_flag_t pm_caps; unsigned int flags; }; struct sdhci_acpi_host { struct sdhci_host *host; const struct sdhci_acpi_slot *slot; struct platform_device *pdev; bool use_runtime_pm; }; static inline bool sdhci_acpi_flag(struct sdhci_acpi_host *c, unsigned int flag) { return c->slot && (c->slot->flags & flag); } static int sdhci_acpi_enable_dma(struct sdhci_host *host) { return 0; } static void sdhci_acpi_int_hw_reset(struct sdhci_host *host) { u8 reg; reg = sdhci_readb(host, SDHCI_POWER_CONTROL); reg |= 0x10; sdhci_writeb(host, reg, SDHCI_POWER_CONTROL); /* For eMMC, minimum is 1us but give it 9us for good measure */ udelay(9); reg &= ~0x10; sdhci_writeb(host, reg, SDHCI_POWER_CONTROL); /* For eMMC, minimum is 200us but give it 300us for good measure */ usleep_range(300, 1000); } static const struct sdhci_ops sdhci_acpi_ops_dflt = { .enable_dma = sdhci_acpi_enable_dma, }; static const struct sdhci_ops sdhci_acpi_ops_int = { .enable_dma = sdhci_acpi_enable_dma, .hw_reset = sdhci_acpi_int_hw_reset, }; static const struct sdhci_acpi_chip sdhci_acpi_chip_int = { .ops = &sdhci_acpi_ops_int, }; static const struct sdhci_acpi_slot sdhci_acpi_slot_int_emmc = { .chip = &sdhci_acpi_chip_int, .caps = MMC_CAP_8_BIT_DATA | MMC_CAP_NONREMOVABLE | MMC_CAP_HW_RESET, .caps2 = MMC_CAP2_HC_ERASE_SZ, .flags = SDHCI_ACPI_RUNTIME_PM, }; static const struct sdhci_acpi_slot sdhci_acpi_slot_int_sdio = { .quirks2 = SDHCI_QUIRK2_HOST_OFF_CARD_ON, .caps = MMC_CAP_NONREMOVABLE | MMC_CAP_POWER_OFF_CARD, .flags = SDHCI_ACPI_RUNTIME_PM, .pm_caps = MMC_PM_KEEP_POWER, }; static const struct sdhci_acpi_slot sdhci_acpi_slot_int_sd = { .flags = SDHCI_ACPI_SD_CD | SDHCI_ACPI_RUNTIME_PM, .quirks2 = SDHCI_QUIRK2_CARD_ON_NEEDS_BUS_ON, }; struct sdhci_acpi_uid_slot { const char *hid; const char *uid; const struct sdhci_acpi_slot *slot; }; static const struct sdhci_acpi_uid_slot sdhci_acpi_uids[] = { { "80860F14" , "1" , &sdhci_acpi_slot_int_emmc }, { "80860F14" , "3" , &sdhci_acpi_slot_int_sd }, { "INT33BB" , "2" , &sdhci_acpi_slot_int_sdio }, { "INT33C6" , NULL, &sdhci_acpi_slot_int_sdio }, { "PNP0D40" }, { }, }; static const struct acpi_device_id sdhci_acpi_ids[] = { { "80860F14" }, { "INT33BB" }, { "INT33C6" }, { "PNP0D40" }, { }, }; MODULE_DEVICE_TABLE(acpi, sdhci_acpi_ids); static const struct sdhci_acpi_slot *sdhci_acpi_get_slot_by_ids(const char *hid, const char *uid) { const struct sdhci_acpi_uid_slot *u; for (u = sdhci_acpi_uids; u->hid; u++) { if (strcmp(u->hid, hid)) continue; if (!u->uid) return u->slot; if (uid && !strcmp(u->uid, uid)) return u->slot; } return NULL; } static const struct sdhci_acpi_slot *sdhci_acpi_get_slot(acpi_handle handle, const char *hid) { const struct sdhci_acpi_slot *slot; struct acpi_device_info *info; const char *uid = NULL; acpi_status status; status = acpi_get_object_info(handle, &info); if (!ACPI_FAILURE(status) && (info->valid & ACPI_VALID_UID)) uid = info->unique_id.string; slot = sdhci_acpi_get_slot_by_ids(hid, uid); kfree(info); return slot; } #ifdef CONFIG_PM_RUNTIME static irqreturn_t sdhci_acpi_sd_cd(int irq, void *dev_id) { mmc_detect_change(dev_id, msecs_to_jiffies(200)); return IRQ_HANDLED; } static int sdhci_acpi_add_own_cd(struct device *dev, struct mmc_host *mmc) { struct gpio_desc *desc; unsigned long flags; int err, irq; desc = devm_gpiod_get_index(dev, "sd_cd", 0); if (IS_ERR(desc)) { err = PTR_ERR(desc); goto out; } err = gpiod_direction_input(desc); if (err) goto out_free; irq = gpiod_to_irq(desc); if (irq < 0) { err = irq; goto out_free; } flags = IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING; err = devm_request_irq(dev, irq, sdhci_acpi_sd_cd, flags, "sd_cd", mmc); if (err) goto out_free; return 0; out_free: devm_gpiod_put(dev, desc); out: dev_warn(dev, "failed to setup card detect wake up\n"); return err; } #else static int sdhci_acpi_add_own_cd(struct device *dev, struct mmc_host *mmc) { return 0; } #endif static int sdhci_acpi_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; acpi_handle handle = ACPI_HANDLE(dev); struct acpi_device *device; struct sdhci_acpi_host *c; struct sdhci_host *host; struct resource *iomem; resource_size_t len; const char *hid; int err; if (acpi_bus_get_device(handle, &device)) return -ENODEV; if (acpi_bus_get_status(device) || !device->status.present) return -ENODEV; hid = acpi_device_hid(device); iomem = platform_get_resource(pdev, IORESOURCE_MEM, 0); if (!iomem) return -ENOMEM; len = resource_size(iomem); if (len < 0x100) dev_err(dev, "Invalid iomem size!\n"); if (!devm_request_mem_region(dev, iomem->start, len, dev_name(dev))) return -ENOMEM; host = sdhci_alloc_host(dev, sizeof(struct sdhci_acpi_host)); if (IS_ERR(host)) return PTR_ERR(host); c = sdhci_priv(host); c->host = host; c->slot = sdhci_acpi_get_slot(handle, hid); c->pdev = pdev; c->use_runtime_pm = sdhci_acpi_flag(c, SDHCI_ACPI_RUNTIME_PM); platform_set_drvdata(pdev, c); host->hw_name = "ACPI"; host->ops = &sdhci_acpi_ops_dflt; host->irq = platform_get_irq(pdev, 0); host->ioaddr = devm_ioremap_nocache(dev, iomem->start, resource_size(iomem)); if (host->ioaddr == NULL) { err = -ENOMEM; goto err_free; } if (!dev->dma_mask) { u64 dma_mask; if (sdhci_readl(host, SDHCI_CAPABILITIES) & SDHCI_CAN_64BIT) { /* 64-bit DMA is not supported at present */ dma_mask = DMA_BIT_MASK(32); } else { dma_mask = DMA_BIT_MASK(32); } err = dma_coerce_mask_and_coherent(dev, dma_mask); if (err) goto err_free; } if (c->slot) { if (c->slot->chip) { host->ops = c->slot->chip->ops; host->quirks |= c->slot->chip->quirks; host->quirks2 |= c->slot->chip->quirks2; host->mmc->caps |= c->slot->chip->caps; host->mmc->caps2 |= c->slot->chip->caps2; host->mmc->pm_caps |= c->slot->chip->pm_caps; } host->quirks |= c->slot->quirks; host->quirks2 |= c->slot->quirks2; host->mmc->caps |= c->slot->caps; host->mmc->caps2 |= c->slot->caps2; host->mmc->pm_caps |= c->slot->pm_caps; } host->mmc->caps2 |= MMC_CAP2_NO_PRESCAN_POWERUP; err = sdhci_add_host(host); if (err) goto err_free; if (sdhci_acpi_flag(c, SDHCI_ACPI_SD_CD)) { if (sdhci_acpi_add_own_cd(dev, host->mmc)) c->use_runtime_pm = false; } if (c->use_runtime_pm) { pm_runtime_set_active(dev); pm_suspend_ignore_children(dev, 1); pm_runtime_set_autosuspend_delay(dev, 50); pm_runtime_use_autosuspend(dev); pm_runtime_enable(dev); } return 0; err_free: sdhci_free_host(c->host); return err; } static int sdhci_acpi_remove(struct platform_device *pdev) { struct sdhci_acpi_host *c = platform_get_drvdata(pdev); struct device *dev = &pdev->dev; int dead; if (c->use_runtime_pm) { pm_runtime_get_sync(dev); pm_runtime_disable(dev); pm_runtime_put_noidle(dev); } dead = (sdhci_readl(c->host, SDHCI_INT_STATUS) == ~0); sdhci_remove_host(c->host, dead); sdhci_free_host(c->host); return 0; } #ifdef CONFIG_PM_SLEEP static int sdhci_acpi_suspend(struct device *dev) { struct sdhci_acpi_host *c = dev_get_drvdata(dev); return sdhci_suspend_host(c->host); } static int sdhci_acpi_resume(struct device *dev) { struct sdhci_acpi_host *c = dev_get_drvdata(dev); return sdhci_resume_host(c->host); } #else #define sdhci_acpi_suspend NULL #define sdhci_acpi_resume NULL #endif #ifdef CONFIG_PM_RUNTIME static int sdhci_acpi_runtime_suspend(struct device *dev) { struct sdhci_acpi_host *c = dev_get_drvdata(dev); return sdhci_runtime_suspend_host(c->host); } static int sdhci_acpi_runtime_resume(struct device *dev) { struct sdhci_acpi_host *c = dev_get_drvdata(dev); return sdhci_runtime_resume_host(c->host); } static int sdhci_acpi_runtime_idle(struct device *dev) { return 0; } #else #define sdhci_acpi_runtime_suspend NULL #define sdhci_acpi_runtime_resume NULL #define sdhci_acpi_runtime_idle NULL #endif static const struct dev_pm_ops sdhci_acpi_pm_ops = { .suspend = sdhci_acpi_suspend, .resume = sdhci_acpi_resume, .runtime_suspend = sdhci_acpi_runtime_suspend, .runtime_resume = sdhci_acpi_runtime_resume, .runtime_idle = sdhci_acpi_runtime_idle, }; static struct platform_driver sdhci_acpi_driver = { .driver = { .name = "sdhci-acpi", .owner = THIS_MODULE, .acpi_match_table = sdhci_acpi_ids, .pm = &sdhci_acpi_pm_ops, }, .probe = sdhci_acpi_probe, .remove = sdhci_acpi_remove, }; module_platform_driver(sdhci_acpi_driver); MODULE_DESCRIPTION("Secure Digital Host Controller Interface ACPI driver"); MODULE_AUTHOR("Adrian Hunter"); MODULE_LICENSE("GPL v2");
wgoossens/linux-nios2
drivers/mmc/host/sdhci-acpi.c
C
gpl-2.0
10,570
// SPDX-License-Identifier: GPL-2.0-or-later /* * * BlueZ - Bluetooth protocol stack for Linux * * Copyright (C) 2013 Intel Corporation. All rights reserved. * * */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <stdbool.h> #include <glib.h> #include "lib/bluetooth.h" #include "lib/sco.h" #include "lib/mgmt.h" #include "monitor/bt.h" #include "emulator/bthost.h" #include "emulator/hciemu.h" #include "src/shared/tester.h" #include "src/shared/mgmt.h" struct test_data { const void *test_data; struct mgmt *mgmt; uint16_t mgmt_index; struct hciemu *hciemu; enum hciemu_type hciemu_type; unsigned int io_id; bool disable_esco; bool enable_codecs; }; struct sco_client_data { int expect_err; const uint8_t *send_data; uint16_t data_len; }; static void print_debug(const char *str, void *user_data) { const char *prefix = user_data; tester_print("%s%s", prefix, str); } static void read_info_callback(uint8_t status, uint16_t length, const void *param, void *user_data) { struct test_data *data = tester_get_data(); const struct mgmt_rp_read_info *rp = param; char addr[18]; uint16_t manufacturer; uint32_t supported_settings, current_settings; tester_print("Read Info callback"); tester_print(" Status: 0x%02x", status); if (status || !param) { tester_pre_setup_failed(); return; } ba2str(&rp->bdaddr, addr); manufacturer = btohs(rp->manufacturer); supported_settings = btohl(rp->supported_settings); current_settings = btohl(rp->current_settings); tester_print(" Address: %s", addr); tester_print(" Version: 0x%02x", rp->version); tester_print(" Manufacturer: 0x%04x", manufacturer); tester_print(" Supported settings: 0x%08x", supported_settings); tester_print(" Current settings: 0x%08x", current_settings); tester_print(" Class: 0x%02x%02x%02x", rp->dev_class[2], rp->dev_class[1], rp->dev_class[0]); tester_print(" Name: %s", rp->name); tester_print(" Short name: %s", rp->short_name); if (strcmp(hciemu_get_address(data->hciemu), addr)) { tester_pre_setup_failed(); return; } tester_pre_setup_complete(); } static void index_added_callback(uint16_t index, uint16_t length, const void *param, void *user_data) { struct test_data *data = tester_get_data(); tester_print("Index Added callback"); tester_print(" Index: 0x%04x", index); data->mgmt_index = index; mgmt_send(data->mgmt, MGMT_OP_READ_INFO, data->mgmt_index, 0, NULL, read_info_callback, NULL, NULL); } static void index_removed_callback(uint16_t index, uint16_t length, const void *param, void *user_data) { struct test_data *data = tester_get_data(); tester_print("Index Removed callback"); tester_print(" Index: 0x%04x", index); if (index != data->mgmt_index) return; mgmt_unregister_index(data->mgmt, data->mgmt_index); mgmt_unref(data->mgmt); data->mgmt = NULL; tester_post_teardown_complete(); } static void enable_codec_callback(uint8_t status, uint16_t length, const void *param, void *user_data) { if (status != MGMT_STATUS_SUCCESS) { tester_warn("Failed to enable codecs"); tester_setup_failed(); return; } tester_print("Enabled codecs"); } static void read_index_list_callback(uint8_t status, uint16_t length, const void *param, void *user_data) { struct test_data *data = tester_get_data(); tester_print("Read Index List callback"); tester_print(" Status: 0x%02x", status); if (status || !param) { tester_pre_setup_failed(); return; } mgmt_register(data->mgmt, MGMT_EV_INDEX_ADDED, MGMT_INDEX_NONE, index_added_callback, NULL, NULL); mgmt_register(data->mgmt, MGMT_EV_INDEX_REMOVED, MGMT_INDEX_NONE, index_removed_callback, NULL, NULL); data->hciemu = hciemu_new(HCIEMU_TYPE_BREDRLE); if (!data->hciemu) { tester_warn("Failed to setup HCI emulation"); tester_pre_setup_failed(); return; } if (tester_use_debug()) hciemu_set_debug(data->hciemu, print_debug, "hciemu: ", NULL); tester_print("New hciemu instance created"); if (data->disable_esco) { uint8_t *features; tester_print("Disabling eSCO packet type support"); features = hciemu_get_features(data->hciemu); if (features) features[3] &= ~0x80; } } static void test_pre_setup(const void *test_data) { struct test_data *data = tester_get_data(); data->mgmt = mgmt_new_default(); if (!data->mgmt) { tester_warn("Failed to setup management interface"); tester_pre_setup_failed(); return; } if (tester_use_debug()) mgmt_set_debug(data->mgmt, print_debug, "mgmt: ", NULL); mgmt_send(data->mgmt, MGMT_OP_READ_INDEX_LIST, MGMT_INDEX_NONE, 0, NULL, read_index_list_callback, NULL, NULL); } static void test_post_teardown(const void *test_data) { struct test_data *data = tester_get_data(); hciemu_unref(data->hciemu); data->hciemu = NULL; } static void test_data_free(void *test_data) { struct test_data *data = test_data; if (data->io_id > 0) g_source_remove(data->io_id); free(data); } #define test_sco_full(name, data, setup, func, _disable_esco, _enable_codecs) \ do { \ struct test_data *user; \ user = malloc(sizeof(struct test_data)); \ if (!user) \ break; \ user->hciemu_type = HCIEMU_TYPE_BREDRLE; \ user->io_id = 0; \ user->test_data = data; \ user->disable_esco = _disable_esco; \ user->enable_codecs = _enable_codecs; \ tester_add_full(name, data, \ test_pre_setup, setup, func, NULL, \ test_post_teardown, 2, user, test_data_free); \ } while (0) #define test_sco(name, data, setup, func) \ test_sco_full(name, data, setup, func, false, false) #define test_sco_11(name, data, setup, func) \ test_sco_full(name, data, setup, func, true, false) #define test_offload_sco(name, data, setup, func) \ test_sco_full(name, data, setup, func, false, true) static const struct sco_client_data connect_success = { .expect_err = 0 }; static const struct sco_client_data connect_failure = { .expect_err = EOPNOTSUPP }; const uint8_t data[] = {0, 1, 2, 3, 4, 5, 6, 7, 8}; static const struct sco_client_data connect_send_success = { .expect_err = 0, .data_len = sizeof(data), .send_data = data }; static void client_connectable_complete(uint16_t opcode, uint8_t status, const void *param, uint8_t len, void *user_data) { if (opcode != BT_HCI_CMD_WRITE_SCAN_ENABLE) return; tester_print("Client set connectable status 0x%02x", status); if (status) tester_setup_failed(); else tester_setup_complete(); } static void setup_powered_callback(uint8_t status, uint16_t length, const void *param, void *user_data) { struct test_data *data = tester_get_data(); struct bthost *bthost; if (status != MGMT_STATUS_SUCCESS) { tester_setup_failed(); return; } tester_print("Controller powered on"); bthost = hciemu_client_get_host(data->hciemu); bthost_set_cmd_complete_cb(bthost, client_connectable_complete, data); bthost_write_scan_enable(bthost, 0x03); } static void setup_powered(const void *test_data) { struct test_data *data = tester_get_data(); unsigned char param[] = { 0x01 }; tester_print("Powering on controller"); mgmt_send(data->mgmt, MGMT_OP_SET_CONNECTABLE, data->mgmt_index, sizeof(param), param, NULL, NULL, NULL); mgmt_send(data->mgmt, MGMT_OP_SET_SSP, data->mgmt_index, sizeof(param), param, NULL, NULL, NULL); mgmt_send(data->mgmt, MGMT_OP_SET_LE, data->mgmt_index, sizeof(param), param, NULL, NULL, NULL); if (data->enable_codecs) { /* a6695ace-ee7f-4fb9-881a-5fac66c629af */ static const uint8_t uuid[16] = { 0xaf, 0x29, 0xc6, 0x66, 0xac, 0x5f, 0x1a, 0x88, 0xb9, 0x4f, 0x7f, 0xee, 0xce, 0x5a, 0x69, 0xa6, }; struct mgmt_cp_set_exp_feature cp; memset(&cp, 0, sizeof(cp)); memcpy(cp.uuid, uuid, 16); cp.action = 1; tester_print("Enabling codecs"); mgmt_send(data->mgmt, MGMT_OP_SET_EXP_FEATURE, data->mgmt_index, sizeof(cp), &cp, enable_codec_callback, NULL, NULL); } mgmt_send(data->mgmt, MGMT_OP_SET_POWERED, data->mgmt_index, sizeof(param), param, setup_powered_callback, NULL, NULL); } static void test_framework(const void *test_data) { tester_test_passed(); } static void test_socket(const void *test_data) { int sk; sk = socket(PF_BLUETOOTH, SOCK_SEQPACKET, BTPROTO_SCO); if (sk < 0) { tester_warn("Can't create socket: %s (%d)", strerror(errno), errno); tester_test_failed(); return; } close(sk); tester_test_passed(); } static void test_codecs_getsockopt(const void *test_data) { int sk, err; socklen_t len; char buffer[255]; sk = socket(PF_BLUETOOTH, SOCK_SEQPACKET, BTPROTO_SCO); if (sk < 0) { tester_warn("Can't create socket: %s (%d)", strerror(errno), errno); tester_test_failed(); return; } len = sizeof(buffer); memset(buffer, 0, len); err = getsockopt(sk, SOL_BLUETOOTH, BT_CODEC, buffer, &len); if (err < 0) { tester_warn("Can't get socket option : %s (%d)", strerror(errno), errno); tester_test_failed(); goto end; } tester_test_passed(); end: close(sk); } static void test_codecs_setsockopt(const void *test_data) { int sk, err; char buffer[255]; struct bt_codecs *codecs; sk = socket(PF_BLUETOOTH, SOCK_SEQPACKET, BTPROTO_SCO); if (sk < 0) { tester_warn("Can't create socket: %s (%d)", strerror(errno), errno); tester_test_failed(); return; } memset(buffer, 0, sizeof(buffer)); codecs = (void *)buffer; codecs->codecs[0].id = 0x05; codecs->num_codecs = 1; codecs->codecs[0].data_path_id = 1; codecs->codecs[0].num_caps = 0x00; err = setsockopt(sk, SOL_BLUETOOTH, BT_CODEC, codecs, sizeof(buffer)); if (err < 0) { tester_warn("Can't set socket option : %s (%d)", strerror(errno), errno); tester_test_failed(); goto end; } tester_test_passed(); end: close(sk); } static void test_getsockopt(const void *test_data) { int sk, err; socklen_t len; struct bt_voice voice; sk = socket(PF_BLUETOOTH, SOCK_SEQPACKET, BTPROTO_SCO); if (sk < 0) { tester_warn("Can't create socket: %s (%d)", strerror(errno), errno); tester_test_failed(); return; } len = sizeof(voice); memset(&voice, 0, len); err = getsockopt(sk, SOL_BLUETOOTH, BT_VOICE, &voice, &len); if (err < 0) { tester_warn("Can't get socket option : %s (%d)", strerror(errno), errno); tester_test_failed(); goto end; } if (voice.setting != BT_VOICE_CVSD_16BIT) { tester_warn("Invalid voice setting"); tester_test_failed(); goto end; } tester_test_passed(); end: close(sk); } static void test_setsockopt(const void *test_data) { int sk, err; socklen_t len; struct bt_voice voice; sk = socket(PF_BLUETOOTH, SOCK_SEQPACKET, BTPROTO_SCO); if (sk < 0) { tester_warn("Can't create socket: %s (%d)", strerror(errno), errno); tester_test_failed(); goto end; } len = sizeof(voice); memset(&voice, 0, len); err = getsockopt(sk, SOL_BLUETOOTH, BT_VOICE, &voice, &len); if (err < 0) { tester_warn("Can't get socket option : %s (%d)", strerror(errno), errno); tester_test_failed(); goto end; } if (voice.setting != BT_VOICE_CVSD_16BIT) { tester_warn("Invalid voice setting"); tester_test_failed(); goto end; } memset(&voice, 0, sizeof(voice)); voice.setting = BT_VOICE_TRANSPARENT; err = setsockopt(sk, SOL_BLUETOOTH, BT_VOICE, &voice, sizeof(voice)); if (err < 0) { tester_warn("Can't set socket option : %s (%d)", strerror(errno), errno); tester_test_failed(); goto end; } len = sizeof(voice); memset(&voice, 0, len); err = getsockopt(sk, SOL_BLUETOOTH, BT_VOICE, &voice, &len); if (err < 0) { tester_warn("Can't get socket option : %s (%d)", strerror(errno), errno); tester_test_failed(); goto end; } if (voice.setting != BT_VOICE_TRANSPARENT) { tester_warn("Invalid voice setting"); tester_test_failed(); goto end; } tester_test_passed(); end: close(sk); } static int create_sco_sock(struct test_data *data) { const uint8_t *central_bdaddr; struct sockaddr_sco addr; int sk, err; sk = socket(PF_BLUETOOTH, SOCK_SEQPACKET | SOCK_NONBLOCK, BTPROTO_SCO); if (sk < 0) { err = -errno; tester_warn("Can't create socket: %s (%d)", strerror(errno), errno); return err; } central_bdaddr = hciemu_get_central_bdaddr(data->hciemu); if (!central_bdaddr) { tester_warn("No central bdaddr"); return -ENODEV; } memset(&addr, 0, sizeof(addr)); addr.sco_family = AF_BLUETOOTH; bacpy(&addr.sco_bdaddr, (void *) central_bdaddr); if (bind(sk, (struct sockaddr *) &addr, sizeof(addr)) < 0) { err = -errno; tester_warn("Can't bind socket: %s (%d)", strerror(errno), errno); close(sk); return err; } return sk; } static int connect_sco_sock(struct test_data *data, int sk) { const uint8_t *client_bdaddr; struct sockaddr_sco addr; int err; client_bdaddr = hciemu_get_client_bdaddr(data->hciemu); if (!client_bdaddr) { tester_warn("No client bdaddr"); return -ENODEV; } memset(&addr, 0, sizeof(addr)); addr.sco_family = AF_BLUETOOTH; bacpy(&addr.sco_bdaddr, (void *) client_bdaddr); err = connect(sk, (struct sockaddr *) &addr, sizeof(addr)); if (err < 0 && !(errno == EAGAIN || errno == EINPROGRESS)) { err = -errno; tester_warn("Can't connect socket: %s (%d)", strerror(errno), errno); return err; } return 0; } static gboolean sco_connect_cb(GIOChannel *io, GIOCondition cond, gpointer user_data) { struct test_data *data = tester_get_data(); const struct sco_client_data *scodata = data->test_data; int err, sk_err, sk; socklen_t len = sizeof(sk_err); data->io_id = 0; sk = g_io_channel_unix_get_fd(io); if (getsockopt(sk, SOL_SOCKET, SO_ERROR, &sk_err, &len) < 0) err = -errno; else err = -sk_err; if (err < 0) tester_warn("Connect failed: %s (%d)", strerror(-err), -err); else tester_print("Successfully connected"); if (scodata->send_data) { ssize_t ret; tester_print("Writing %u bytes of data", scodata->data_len); ret = write(sk, scodata->send_data, scodata->data_len); if (scodata->data_len != ret) { tester_warn("Failed to write %u bytes: %zu %s (%d)", scodata->data_len, ret, strerror(errno), errno); err = -errno; } } if (-err != scodata->expect_err) tester_test_failed(); else tester_test_passed(); return FALSE; } static void test_connect(const void *test_data) { struct test_data *data = tester_get_data(); GIOChannel *io; int sk; sk = create_sco_sock(data); if (sk < 0) { tester_test_failed(); return; } if (connect_sco_sock(data, sk) < 0) { close(sk); tester_test_failed(); return; } io = g_io_channel_unix_new(sk); g_io_channel_set_close_on_unref(io, TRUE); data->io_id = g_io_add_watch(io, G_IO_OUT, sco_connect_cb, NULL); g_io_channel_unref(io); tester_print("Connect in progress"); } static void test_connect_transp(const void *test_data) { struct test_data *data = tester_get_data(); const struct sco_client_data *scodata = data->test_data; int sk, err; struct bt_voice voice; sk = create_sco_sock(data); if (sk < 0) { tester_test_failed(); return; } memset(&voice, 0, sizeof(voice)); voice.setting = BT_VOICE_TRANSPARENT; err = setsockopt(sk, SOL_BLUETOOTH, BT_VOICE, &voice, sizeof(voice)); if (err < 0) { tester_warn("Can't set socket option : %s (%d)", strerror(errno), errno); tester_test_failed(); goto end; } err = connect_sco_sock(data, sk); tester_warn("Connect returned %s (%d), expected %s (%d)", strerror(-err), -err, strerror(scodata->expect_err), scodata->expect_err); if (-err != scodata->expect_err) tester_test_failed(); else tester_test_passed(); end: close(sk); } static void test_connect_offload_msbc(const void *test_data) { struct test_data *data = tester_get_data(); const struct sco_client_data *scodata = data->test_data; int sk, err; int len; char buffer[255]; struct bt_codecs *codecs; sk = create_sco_sock(data); if (sk < 0) { tester_test_failed(); return; } len = sizeof(buffer); memset(buffer, 0, len); codecs = (void *)buffer; codecs->codecs[0].id = 0x05; codecs->num_codecs = 1; codecs->codecs[0].data_path_id = 1; codecs->codecs[0].num_caps = 0x00; err = setsockopt(sk, SOL_BLUETOOTH, BT_CODEC, codecs, sizeof(buffer)); if (err < 0) { tester_warn("Can't set socket option : %s (%d)", strerror(errno), errno); tester_test_failed(); goto end; } err = connect_sco_sock(data, sk); tester_warn("Connect returned %s (%d), expected %s (%d)", strerror(-err), -err, strerror(scodata->expect_err), scodata->expect_err); if (-err != scodata->expect_err) tester_test_failed(); else tester_test_passed(); end: close(sk); } int main(int argc, char *argv[]) { tester_init(&argc, &argv); test_sco("Basic Framework - Success", NULL, setup_powered, test_framework); test_sco("Basic SCO Socket - Success", NULL, setup_powered, test_socket); test_sco("Basic SCO Get Socket Option - Success", NULL, setup_powered, test_getsockopt); test_sco("Basic SCO Set Socket Option - Success", NULL, setup_powered, test_setsockopt); test_sco("eSCO CVSD - Success", &connect_success, setup_powered, test_connect); test_sco("eSCO mSBC - Success", &connect_success, setup_powered, test_connect_transp); test_sco_11("SCO CVSD 1.1 - Success", &connect_success, setup_powered, test_connect); test_sco_11("SCO mSBC 1.1 - Failure", &connect_failure, setup_powered, test_connect_transp); test_sco("SCO CVSD Send - Success", &connect_send_success, setup_powered, test_connect); test_offload_sco("Basic SCO Get Socket Option - Offload - Success", NULL, setup_powered, test_codecs_getsockopt); test_offload_sco("Basic SCO Set Socket Option - Offload - Success", NULL, setup_powered, test_codecs_setsockopt); test_offload_sco("eSCO mSBC - Offload - Success", &connect_success, setup_powered, test_connect_offload_msbc); return tester_run(); }
cktakahasi/bluez
tools/sco-tester.c
C
gpl-2.0
18,002
/* * Soft: Keepalived is a failover program for the LVS project * <www.linuxvirtualserver.org>. It monitor & manipulate * a loadbalanced server pool using multi-layer checks. * * Part: NETLINK kernel command channel. * * Author: Alexandre Cassen, <acassen@linux-vs.org> * * This program 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. * * 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. * * Copyright (C) 2001-2012 Alexandre Cassen, <acassen@gmail.com> */ /* global include */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <syslog.h> #include <fcntl.h> #include <net/if_arp.h> #include <sys/socket.h> #include <netinet/in.h> #include <string.h> #include <errno.h> #include <time.h> #include <sys/uio.h> /* local include */ #include "check_api.h" #include "vrrp_netlink.h" #include "vrrp_if.h" #include "logger.h" #include "memory.h" #include "scheduler.h" #include "utils.h" /* Global vars */ nl_handle_t nl_kernel; /* Kernel reflection channel */ nl_handle_t nl_cmd; /* Command channel */ /* Create a socket to netlink interface_t */ int netlink_socket(nl_handle_t *nl, unsigned long groups) { socklen_t addr_len; int ret; memset(nl, 0, sizeof (*nl)); nl->fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE); if (nl->fd < 0) { log_message(LOG_INFO, "Netlink: Cannot open netlink socket : (%s)", strerror(errno)); return -1; } ret = fcntl(nl->fd, F_SETFL, O_NONBLOCK); if (ret < 0) { log_message(LOG_INFO, "Netlink: Cannot set netlink socket flags : (%s)", strerror(errno)); close(nl->fd); return -1; } memset(&nl->snl, 0, sizeof (nl->snl)); nl->snl.nl_family = AF_NETLINK; nl->snl.nl_groups = groups; ret = bind(nl->fd, (struct sockaddr *) &nl->snl, sizeof (nl->snl)); if (ret < 0) { log_message(LOG_INFO, "Netlink: Cannot bind netlink socket : (%s)", strerror(errno)); close(nl->fd); return -1; } addr_len = sizeof (nl->snl); ret = getsockname(nl->fd, (struct sockaddr *) &nl->snl, &addr_len); if (ret < 0 || addr_len != sizeof (nl->snl)) { log_message(LOG_INFO, "Netlink: Cannot getsockname : (%s)", strerror(errno)); close(nl->fd); return -1; } if (nl->snl.nl_family != AF_NETLINK) { log_message(LOG_INFO, "Netlink: Wrong address family %d", nl->snl.nl_family); close(nl->fd); return -1; } nl->seq = time(NULL); /* Set default rcvbuf size */ if_setsockopt_rcvbuf(&nl->fd, IF_DEFAULT_BUFSIZE); if (nl->fd < 0) return -1; return ret; } /* Close a netlink socket */ int netlink_close(nl_handle_t *nl) { /* First of all release pending thread */ thread_cancel(nl->thread); close(nl->fd); return 0; } /* Set netlink socket channel as blocking */ int netlink_set_block(nl_handle_t *nl, int *flags) { if ((*flags = fcntl(nl->fd, F_GETFL, 0)) < 0) { log_message(LOG_INFO, "Netlink: Cannot F_GETFL socket : (%s)", strerror(errno)); return -1; } *flags &= ~O_NONBLOCK; if (fcntl(nl->fd, F_SETFL, *flags) < 0) { log_message(LOG_INFO, "Netlink: Cannot F_SETFL socket : (%s)", strerror(errno)); return -1; } return 0; } /* Set netlink socket channel as non-blocking */ int netlink_set_nonblock(nl_handle_t *nl, int *flags) { *flags |= O_NONBLOCK; if (fcntl(nl->fd, F_SETFL, *flags) < 0) { log_message(LOG_INFO, "Netlink: Cannot F_SETFL socket : (%s)", strerror(errno)); return -1; } return 0; } /* iproute2 utility function */ int addattr32(struct nlmsghdr *n, int maxlen, int type, uint32_t data) { int len = RTA_LENGTH(4); struct rtattr *rta; if (NLMSG_ALIGN(n->nlmsg_len) + len > maxlen) return -1; rta = (struct rtattr*)(((char*)n) + NLMSG_ALIGN(n->nlmsg_len)); rta->rta_type = type; rta->rta_len = len; memcpy(RTA_DATA(rta), &data, 4); n->nlmsg_len = NLMSG_ALIGN(n->nlmsg_len) + len; return 0; } int addattr_l(struct nlmsghdr *n, int maxlen, int type, void *data, int alen) { int len = RTA_LENGTH(alen); struct rtattr *rta; if (NLMSG_ALIGN(n->nlmsg_len) + len > maxlen) return -1; rta = (struct rtattr *) (((char *) n) + NLMSG_ALIGN(n->nlmsg_len)); rta->rta_type = type; rta->rta_len = len; memcpy(RTA_DATA(rta), data, alen); n->nlmsg_len = NLMSG_ALIGN(n->nlmsg_len) + len; return 0; } int rta_addattr_l(struct rtattr *rta, int maxlen, int type, const void *data, int alen) { struct rtattr *subrta; int len = RTA_LENGTH(alen); if (RTA_ALIGN(rta->rta_len) + RTA_ALIGN(len) > maxlen) { return -1; } subrta = (struct rtattr*)(((char*)rta) + RTA_ALIGN(rta->rta_len)); subrta->rta_type = type; subrta->rta_len = len; memcpy(RTA_DATA(subrta), data, alen); rta->rta_len = NLMSG_ALIGN(rta->rta_len) + RTA_ALIGN(len); return 0; } static void parse_rtattr(struct rtattr **tb, int max, struct rtattr *rta, int len) { while (RTA_OK(rta, len)) { if (rta->rta_type <= max) tb[rta->rta_type] = rta; rta = RTA_NEXT(rta, len); } } char * netlink_scope_n2a(int scope) { if (scope == 0) return "global"; if (scope == 255) return "nowhere"; if (scope == 254) return "host"; if (scope == 253) return "link"; if (scope == 200) return "site"; return "unknown"; } int netlink_scope_a2n(char *scope) { if (!strcmp(scope, "global")) return 0; if (!strcmp(scope, "nowhere")) return 255; if (!strcmp(scope, "host")) return 254; if (!strcmp(scope, "link")) return 253; if (!strcmp(scope, "site")) return 200; return -1; } /* * Reflect base interface flags on VMAC interface. * VMAC interfaces should never update it own flags, only be reflected * by the base interface flags. */ static void vmac_reflect_flags(struct ifinfomsg *ifi) { interface_t *ifp; /* find the VMAC interface (if any) */ ifp = if_get_by_vmac_base_ifindex(ifi->ifi_index); /* if found, reflect base interface flags on VMAC interface */ if (ifp) { ifp->flags = ifi->ifi_flags; } } /* Our netlink parser */ static int netlink_parse_info(int (*filter) (struct sockaddr_nl *, struct nlmsghdr *), nl_handle_t *nl, struct nlmsghdr *n) { int status; int ret = 0; int error; while (1) { char buf[4096]; struct iovec iov = { buf, sizeof buf }; struct sockaddr_nl snl; struct msghdr msg = { (void *) &snl, sizeof snl, &iov, 1, NULL, 0, 0 }; struct nlmsghdr *h; status = recvmsg(nl->fd, &msg, 0); if (status < 0) { if (errno == EINTR) continue; if (errno == EWOULDBLOCK || errno == EAGAIN) break; log_message(LOG_INFO, "Netlink: Received message overrun (%m)"); continue; } if (status == 0) { log_message(LOG_INFO, "Netlink: EOF"); return -1; } if (msg.msg_namelen != sizeof snl) { log_message(LOG_INFO, "Netlink: Sender address length error: length %d", msg.msg_namelen); return -1; } for (h = (struct nlmsghdr *) buf; NLMSG_OK(h, status); h = NLMSG_NEXT(h, status)) { /* Finish of reading. */ if (h->nlmsg_type == NLMSG_DONE) return ret; /* Error handling. */ if (h->nlmsg_type == NLMSG_ERROR) { struct nlmsgerr *err = (struct nlmsgerr *) NLMSG_DATA(h); /* * If error == 0 then this is a netlink ACK. * return if not related to multipart message. */ if (err->error == 0) { if (!(h->nlmsg_flags & NLM_F_MULTI)) return 0; continue; } if (h->nlmsg_len < NLMSG_LENGTH(sizeof (struct nlmsgerr))) { log_message(LOG_INFO, "Netlink: error: message truncated"); return -1; } if (n && (err->error == -EEXIST) && ((n->nlmsg_type == RTM_NEWROUTE) || (n->nlmsg_type == RTM_NEWADDR))) return 0; log_message(LOG_INFO, "Netlink: error: %s, type=(%u), seq=%u, pid=%d", strerror(-err->error), err->msg.nlmsg_type, err->msg.nlmsg_seq, err->msg.nlmsg_pid); return -1; } /* Skip unsolicited messages from cmd channel */ if (nl != &nl_cmd && h->nlmsg_pid == nl_cmd.snl.nl_pid) continue; error = (*filter) (&snl, h); if (error < 0) { log_message(LOG_INFO, "Netlink: filter function error"); ret = error; } } /* After error care. */ if (msg.msg_flags & MSG_TRUNC) { log_message(LOG_INFO, "Netlink: error: message truncated"); continue; } if (status) { log_message(LOG_INFO, "Netlink: error: data remnant size %d", status); return -1; } } return ret; } /* Out talk filter */ static int netlink_talk_filter(struct sockaddr_nl *snl, struct nlmsghdr *h) { log_message(LOG_INFO, "Netlink: ignoring message type 0x%04x", h->nlmsg_type); return 0; } /* send message to netlink kernel socket, then receive response */ int netlink_talk(nl_handle_t *nl, struct nlmsghdr *n) { int status; int ret, flags; struct sockaddr_nl snl; struct iovec iov = { (void *) n, n->nlmsg_len }; struct msghdr msg = { (void *) &snl, sizeof snl, &iov, 1, NULL, 0, 0 }; memset(&snl, 0, sizeof snl); snl.nl_family = AF_NETLINK; n->nlmsg_seq = ++nl->seq; /* Request Netlink acknowledgement */ n->nlmsg_flags |= NLM_F_ACK; /* Send message to netlink interface. */ status = sendmsg(nl->fd, &msg, 0); if (status < 0) { log_message(LOG_INFO, "Netlink: sendmsg() error: %s", strerror(errno)); return -1; } /* Set blocking flag */ ret = netlink_set_block(nl, &flags); if (ret < 0) log_message(LOG_INFO, "Netlink: Warning, couldn't set " "blocking flag to netlink socket..."); status = netlink_parse_info(netlink_talk_filter, nl, n); /* Restore previous flags */ if (ret == 0) netlink_set_nonblock(nl, &flags); return status; } /* Fetch a specific type information from netlink kernel */ static int netlink_request(nl_handle_t *nl, int family, int type) { int status; struct sockaddr_nl snl; struct { struct nlmsghdr nlh; struct rtgenmsg g; } req; /* Cleanup the room */ memset(&snl, 0, sizeof (snl)); snl.nl_family = AF_NETLINK; req.nlh.nlmsg_len = sizeof (req); req.nlh.nlmsg_type = type; req.nlh.nlmsg_flags = NLM_F_ROOT | NLM_F_MATCH | NLM_F_REQUEST; req.nlh.nlmsg_pid = 0; req.nlh.nlmsg_seq = ++nl->seq; req.g.rtgen_family = family; status = sendto(nl->fd, (void *) &req, sizeof (req) , 0, (struct sockaddr *) &snl, sizeof (snl)); if (status < 0) { log_message(LOG_INFO, "Netlink: sendto() failed: %s", strerror(errno)); return -1; } return 0; } /* Netlink interface link lookup filter */ static int netlink_if_link_filter(struct sockaddr_nl *snl, struct nlmsghdr *h) { struct ifinfomsg *ifi; struct rtattr *tb[IFLA_MAX + 1]; interface_t *ifp; int i, len; char *name; ifi = NLMSG_DATA(h); if (h->nlmsg_type != RTM_NEWLINK) return 0; len = h->nlmsg_len - NLMSG_LENGTH(sizeof (struct ifinfomsg)); if (len < 0) return -1; /* Interface name lookup */ memset(tb, 0, sizeof (tb)); parse_rtattr(tb, IFLA_MAX, IFLA_RTA(ifi), len); if (tb[IFLA_IFNAME] == NULL) return -1; name = (char *) RTA_DATA(tb[IFLA_IFNAME]); /* Return if loopback */ if (ifi->ifi_type == ARPHRD_LOOPBACK) return 0; /* Skip it if already exist */ ifp = if_get_by_ifname(name); if (ifp) { if (!ifp->vmac) { vmac_reflect_flags(ifi); ifp->flags = ifi->ifi_flags; } return 0; } /* Fill the interface structure */ ifp = (interface_t *) MALLOC(sizeof(interface_t)); memcpy(ifp->ifname, name, strlen(name)); ifp->ifindex = ifi->ifi_index; ifp->mtu = *(int *) RTA_DATA(tb[IFLA_MTU]); ifp->hw_type = ifi->ifi_type; if (!ifp->vmac) { vmac_reflect_flags(ifi); ifp->flags = ifi->ifi_flags; ifp->base_ifindex = ifi->ifi_index; } if (tb[IFLA_ADDRESS]) { int hw_addr_len = RTA_PAYLOAD(tb[IFLA_ADDRESS]); if (hw_addr_len > IF_HWADDR_MAX) log_message(LOG_ERR, "MAC address for %s is too large: %d", name, hw_addr_len); else { ifp->hw_addr_len = hw_addr_len; memcpy(ifp->hw_addr, RTA_DATA(tb[IFLA_ADDRESS]), hw_addr_len); for (i = 0; i < hw_addr_len; i++) if (ifp->hw_addr[i] != 0) break; if (i == hw_addr_len) ifp->hw_addr_len = 0; else ifp->hw_addr_len = hw_addr_len; } } /* Queue this new interface_t */ if_add_queue(ifp); return 0; } /* * Netlink interface address lookup filter * We need to handle multiple primary address and * multiple secondary address to the same interface. */ static int netlink_if_address_filter(struct sockaddr_nl *snl, struct nlmsghdr *h) { struct ifaddrmsg *ifa; struct rtattr *tb[IFA_MAX + 1]; interface_t *ifp; int len; void *addr; ifa = NLMSG_DATA(h); /* Only IPV4 are valid us */ if (ifa->ifa_family != AF_INET && ifa->ifa_family != AF_INET6) return 0; if (h->nlmsg_type != RTM_NEWADDR && h->nlmsg_type != RTM_DELADDR) return 0; len = h->nlmsg_len - NLMSG_LENGTH(sizeof (struct ifaddrmsg)); if (len < 0) return -1; memset(tb, 0, sizeof (tb)); parse_rtattr(tb, IFA_MAX, IFA_RTA(ifa), len); /* Fetch interface_t */ ifp = if_get_by_ifindex(ifa->ifa_index); if (!ifp) return 0; if (tb[IFA_LOCAL] == NULL) tb[IFA_LOCAL] = tb[IFA_ADDRESS]; if (tb[IFA_ADDRESS] == NULL) tb[IFA_ADDRESS] = tb[IFA_LOCAL]; /* local interface address */ addr = (tb[IFA_LOCAL] ? RTA_DATA(tb[IFA_LOCAL]) : NULL); if (addr == NULL) return -1; /* If no address is set on interface then set the first time */ if (ifa->ifa_family == AF_INET) { if (!ifp->sin_addr.s_addr) ifp->sin_addr = *(struct in_addr *) addr; } else { if (!ifp->sin6_addr.s6_addr16[0] && ifa->ifa_scope == RT_SCOPE_LINK) ifp->sin6_addr = *(struct in6_addr *) addr; } #ifdef _WITH_LVS_ /* Refresh checkers state */ update_checker_activity(ifa->ifa_family, addr, (h->nlmsg_type == RTM_NEWADDR) ? 1 : 0); #endif return 0; } /* Interfaces lookup bootstrap function */ int netlink_interface_lookup(void) { nl_handle_t nlh; int status = 0; int ret, flags; if (netlink_socket(&nlh, 0) < 0) return -1; /* Set blocking flag */ ret = netlink_set_block(&nlh, &flags); if (ret < 0) log_message(LOG_INFO, "Netlink: Warning, couldn't set " "blocking flag to netlink socket..."); /* Interface lookup */ if (netlink_request(&nlh, AF_PACKET, RTM_GETLINK) < 0) { status = -1; goto end_int; } status = netlink_parse_info(netlink_if_link_filter, &nlh, NULL); end_int: netlink_close(&nlh); return status; } /* Adresses lookup bootstrap function */ static int netlink_address_lookup(void) { nl_handle_t nlh; int status = 0; int ret, flags; if (netlink_socket(&nlh, 0) < 0) return -1; /* Set blocking flag */ ret = netlink_set_block(&nlh, &flags); if (ret < 0) log_message(LOG_INFO, "Netlink: Warning, couldn't set " "blocking flag to netlink socket..."); /* IPv4 Address lookup */ if (netlink_request(&nlh, AF_INET, RTM_GETADDR) < 0) { status = -1; goto end_addr; } status = netlink_parse_info(netlink_if_address_filter, &nlh, NULL); /* IPv6 Address lookup */ if (netlink_request(&nlh, AF_INET6, RTM_GETADDR) < 0) { status = -1; goto end_addr; } status = netlink_parse_info(netlink_if_address_filter, &nlh, NULL); end_addr: netlink_close(&nlh); return status; } /* Netlink flag Link update */ static int netlink_reflect_filter(struct sockaddr_nl *snl, struct nlmsghdr *h) { struct ifinfomsg *ifi; struct rtattr *tb[IFLA_MAX + 1]; interface_t *ifp; int len; ifi = NLMSG_DATA(h); if (!(h->nlmsg_type == RTM_NEWLINK || h->nlmsg_type == RTM_DELLINK)) return 0; len = h->nlmsg_len - NLMSG_LENGTH(sizeof (struct ifinfomsg)); if (len < 0) return -1; /* Interface name lookup */ memset(tb, 0, sizeof (tb)); parse_rtattr(tb, IFLA_MAX, IFLA_RTA(ifi), len); if (tb[IFLA_IFNAME] == NULL) return -1; /* ignore loopback device */ if (ifi->ifi_type == ARPHRD_LOOPBACK) return 0; /* find the interface_t */ ifp = if_get_by_ifindex(ifi->ifi_index); if (!ifp) return -1; /* * Update flags. * VMAC interfaces should never update it own flags, only be reflected * by the base interface flags. */ if (!ifp->vmac) { vmac_reflect_flags(ifi); ifp->flags = ifi->ifi_flags; } return 0; } /* Netlink kernel message reflection */ static int netlink_broadcast_filter(struct sockaddr_nl *snl, struct nlmsghdr *h) { switch (h->nlmsg_type) { case RTM_NEWLINK: case RTM_DELLINK: return netlink_reflect_filter(snl, h); break; case RTM_NEWADDR: case RTM_DELADDR: return netlink_if_address_filter(snl, h); break; default: log_message(LOG_INFO, "Kernel is reflecting an unknown netlink nlmsg_type: %d", h->nlmsg_type); break; } return 0; } int kernel_netlink(thread_t * thread) { nl_handle_t *nl = THREAD_ARG(thread); if (thread->type != THREAD_READ_TIMEOUT) netlink_parse_info(netlink_broadcast_filter, nl, NULL); nl->thread = thread_add_read(master, kernel_netlink, nl, nl->fd, NETLINK_TIMER); return 0; } void kernel_netlink_init(void) { unsigned long groups; /* Start with a netlink address lookup */ netlink_address_lookup(); /* * Prepare netlink kernel broadcast channel * subscribtion. We subscribe to LINK and ADDR * netlink broadcast messages. */ groups = RTMGRP_LINK | RTMGRP_IPV4_IFADDR | RTMGRP_IPV6_IFADDR; netlink_socket(&nl_kernel, groups); if (nl_kernel.fd > 0) { log_message(LOG_INFO, "Registering Kernel netlink reflector"); nl_kernel.thread = thread_add_read(master, kernel_netlink, &nl_kernel, nl_kernel.fd, NETLINK_TIMER); } else log_message(LOG_INFO, "Error while registering Kernel netlink reflector channel"); /* Prepare netlink command channel. */ netlink_socket(&nl_cmd, 0); if (nl_cmd.fd > 0) log_message(LOG_INFO, "Registering Kernel netlink command channel"); else log_message(LOG_INFO, "Error while registering Kernel netlink cmd channel"); } void kernel_netlink_close(void) { netlink_close(&nl_kernel); netlink_close(&nl_cmd); }
xmllovemm/keepalived_modify
keepalived/vrrp/vrrp_netlink.c
C
gpl-2.0
18,234
/* * Note: this file originally auto-generated by mib2c using * : mib2c.int_watch.conf 13957 2005-12-20 15:33:08Z tanders $ */ #include <net-snmp/net-snmp-config.h> #include <net-snmp/net-snmp-includes.h> #include <net-snmp/agent/net-snmp-agent-includes.h> #include "statPPTP.h" #include "triton.h" /* * The variables we want to tie the relevant OIDs to. * The agent will handle all GET and (if applicable) SET requests * to these variables automatically, changing the values as needed. */ void pptp_get_stat(unsigned int **, unsigned int **); static unsigned int *stat_starting; static unsigned int *stat_active; /* * Our initialization routine, called automatically by the agent * (Note that the function name must match init_FILENAME()) */ void init_statPPTP(void) { netsnmp_handler_registration *reg; netsnmp_watcher_info *winfo; static oid statPPTPStarting_oid[] = { 1,3,6,1,4,1,8072,100,1,3,1 }; static oid statPPTPActive_oid[] = { 1,3,6,1,4,1,8072,100,1,3,2 }; /* * a debugging statement. Run the agent with -DstatPPTP to see * the output of this debugging statement. */ DEBUGMSGTL(("statPPTP", "Initializing the statPPTP module\n")); if (!triton_module_loaded("pptp")) return; pptp_get_stat(&stat_starting, &stat_active); /* * Register scalar watchers for each of the MIB objects. * The ASN type and RO/RW status are taken from the MIB definition, * but can be adjusted if needed. * * In most circumstances, the scalar watcher will handle all * of the necessary processing. But the NULL parameter in the * netsnmp_create_handler_registration() call can be used to * supply a user-provided handler if necessary. * * This approach can also be used to handle Counter64, string- * and OID-based watched scalars (although variable-sized writeable * objects will need some more specialised initialisation). */ DEBUGMSGTL(("statPPTP", "Initializing statPPTPStarting scalar integer. Default value = %d\n", 0)); reg = netsnmp_create_handler_registration( "statPPTPStarting", NULL, statPPTPStarting_oid, OID_LENGTH(statPPTPStarting_oid), HANDLER_CAN_RONLY); winfo = netsnmp_create_watcher_info( stat_starting, sizeof(*stat_starting), ASN_INTEGER, WATCHER_FIXED_SIZE); if (netsnmp_register_watched_scalar( reg, winfo ) < 0 ) { snmp_log( LOG_ERR, "Failed to register watched statPPTPStarting" ); } DEBUGMSGTL(("statPPTP", "Initializing statPPTPActive scalar integer. Default value = %d\n", 0)); reg = netsnmp_create_handler_registration( "statPPTPActive", NULL, statPPTPActive_oid, OID_LENGTH(statPPTPActive_oid), HANDLER_CAN_RONLY); winfo = netsnmp_create_watcher_info( stat_active, sizeof(*stat_active), ASN_INTEGER, WATCHER_FIXED_SIZE); if (netsnmp_register_watched_scalar( reg, winfo ) < 0 ) { snmp_log( LOG_ERR, "Failed to register watched statPPTPActive" ); } DEBUGMSGTL(("statPPTP", "Done initalizing statPPTP module\n")); }
musman2012/commented-accel
accel-pppd/extra/net-snmp/statPPTP.c
C
gpl-2.0
3,252
/* * Copyright (C) 2011-2012 Freescale Semiconductor, Inc. All Rights Reserved. */ /* * Modifyed by: Edison Fernández <edison.fernandez@ridgerun.com> * Added support to use it with Nitrogen6x * * 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. * This program 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 this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * */ #include <linux/module.h> #include <linux/init.h> #include <linux/slab.h> #include <linux/ctype.h> #include <linux/types.h> #include <linux/delay.h> #include <linux/device.h> #include <linux/clk.h> #include <linux/i2c.h> #include <linux/mfd/syscon.h> #include <linux/mfd/syscon/imx6q-iomuxc-gpr.h> #include <linux/of_gpio.h> #include <linux/regulator/consumer.h> #include <linux/fsl_devices.h> #include <linux/mutex.h> #include <linux/mipi_csi2.h> #include <linux/pwm.h> #include <media/v4l2-chip-ident.h> #include <media/v4l2-int-device.h> #include <sound/core.h> #include <sound/pcm.h> #include <sound/soc.h> #include <sound/jack.h> #include <sound/soc-dapm.h> #include <asm/mach-types.h> //#include <mach/audmux.h> #include <linux/slab.h> #include "mxc_v4l2_capture.h" #define CODEC_CLOCK 16500000 /* SSI clock sources */ #define IMX_SSP_SYS_CLK 0 #define TC358743_VOLTAGE_ANALOG 2800000 #define TC358743_VOLTAGE_DIGITAL_CORE 1500000 #define TC358743_VOLTAGE_DIGITAL_IO 1800000 #define MIN_FPS 30 #define MAX_FPS 60 #define DEFAULT_FPS 60 #define TC358743_XCLK_MIN 27000000 #define TC358743_XCLK_MAX 42000000 #define TC358743_CHIP_ID_HIGH_BYTE 0x0 #define TC358743_CHIP_ID_LOW_BYTE 0x0 #define TC3587430_HDMI_DETECT 0x0f //0x10 #define TC_VOLTAGE_ANALOG 2800000 #define TC_VOLTAGE_DIGITAL_CORE 1500000 #define TC_VOLTAGE_DIGITAL_IO 1800000 enum tc358743_mode { tc358743_mode_INIT, /*only for sensor init*/ tc358743_mode_INIT1, /*only for sensor init*/ tc358743_mode_480P_720_480, tc358743_mode_720P_60_1280_720, tc358743_mode_480P_640_480, tc358743_mode_1080P_1920_1080, tc358743_mode_INIT2, /*only for sensor init*/ tc358743_mode_INIT3, /*only for sensor init*/ tc358743_mode_INIT4, /*only for sensor init*/ tc358743_mode_INIT5, /*only for sensor init*/ tc358743_mode_INIT6, /*only for sensor init*/ tc358743_mode_720P_1280_720, tc358743_mode_MAX , }; enum tc358743_frame_rate { tc358743_60_fps, tc358743_30_fps, tc358743_max_fps }; struct reg_value { u16 u16RegAddr; u32 u32Val; u32 u32Mask; u8 u8Length; u32 u32Delay_ms; }; struct tc358743_mode_info { enum tc358743_mode mode; u32 width; u32 height; u32 vformat; u32 fps; u32 lanes; u32 freq; struct reg_value *init_data_ptr; u32 init_data_size; __u32 flags; }; static struct delayed_work det_work; static struct sensor_data tc358743_data; static int pwn_gpio, rst_gpio; static struct regulator *io_regulator; static struct regulator *core_regulator; static struct regulator *analog_regulator; static struct regulator *gpo_regulator; static u16 hpd_active = 1; #define DET_WORK_TIMEOUT_DEFAULT 100 #define DET_WORK_TIMEOUT_DEFERRED 2000 #define MAX_BOUNCE 5 static DEFINE_MUTEX(access_lock); static int det_work_disable = 0; static int det_work_timeout = DET_WORK_TIMEOUT_DEFAULT; static u32 hdmi_mode = 0, lock = 0, bounce = 0, fps = 0, audio = 2; static int tc358743_init_mode(enum tc358743_frame_rate frame_rate, enum tc358743_mode mode); static int tc358743_toggle_hpd(int active); static void tc_standby(s32 enable) { if (gpio_is_valid(pwn_gpio)) gpio_set_value(pwn_gpio, enable ? 1 : 0); pr_debug("tc_standby: powerdown=%x, power_gp=0x%x\n", enable, pwn_gpio); msleep(2); } static void tc_reset(void) { /* camera reset */ gpio_set_value(rst_gpio, 1); /* camera power dowmn */ if (gpio_is_valid(pwn_gpio)) { gpio_set_value(pwn_gpio, 1); msleep(5); gpio_set_value(pwn_gpio, 0); } msleep(5); gpio_set_value(rst_gpio, 0); msleep(1); gpio_set_value(rst_gpio, 1); msleep(20); if (gpio_is_valid(pwn_gpio)) gpio_set_value(pwn_gpio, 1); } static int tc_power_on(struct device *dev) { int ret = 0; io_regulator = devm_regulator_get(dev, "DOVDD"); if (!IS_ERR(io_regulator)) { regulator_set_voltage(io_regulator, TC_VOLTAGE_DIGITAL_IO, TC_VOLTAGE_DIGITAL_IO); ret = regulator_enable(io_regulator); if (ret) { pr_err("%s:io set voltage error\n", __func__); return ret; } else { dev_dbg(dev, "%s:io set voltage ok\n", __func__); } } else { pr_err("%s: cannot get io voltage error\n", __func__); io_regulator = NULL; } core_regulator = devm_regulator_get(dev, "DVDD"); if (!IS_ERR(core_regulator)) { regulator_set_voltage(core_regulator, TC_VOLTAGE_DIGITAL_CORE, TC_VOLTAGE_DIGITAL_CORE); ret = regulator_enable(core_regulator); if (ret) { pr_err("%s:core set voltage error\n", __func__); return ret; } else { dev_dbg(dev, "%s:core set voltage ok\n", __func__); } } else { core_regulator = NULL; pr_err("%s: cannot get core voltage error\n", __func__); } analog_regulator = devm_regulator_get(dev, "AVDD"); if (!IS_ERR(analog_regulator)) { regulator_set_voltage(analog_regulator, TC_VOLTAGE_ANALOG, TC_VOLTAGE_ANALOG); ret = regulator_enable(analog_regulator); if (ret) { pr_err("%s:analog set voltage error\n", __func__); return ret; } else { dev_dbg(dev, "%s:analog set voltage ok\n", __func__); } } else { analog_regulator = NULL; pr_err("%s: cannot get analog voltage error\n", __func__); } return ret; } static void det_work_enable(int i) { mutex_lock(&access_lock); if (i) { det_work_timeout = DET_WORK_TIMEOUT_DEFERRED; schedule_delayed_work(&(det_work), msecs_to_jiffies(det_work_timeout)); det_work_disable = 0; } else { det_work_disable = 1; det_work_timeout = DET_WORK_TIMEOUT_DEFERRED; } mutex_unlock(&access_lock); pr_debug("%s: %d %d\n", __func__, det_work_disable, det_work_timeout); } static u8 cHDMIEDID[256] = { /* FIXME! This is the edid that my ASUS HDMI monitor returns */ 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x04, 0x69, 0xf3, 0x24, 0xd6, 0x12, 0x00, 0x00, 0x16, 0x16, 0x01, 0x03, 0x80, 0x34, 0x1d, 0x78, 0x2a, 0xc7, 0x20, 0xa4, 0x55, 0x49, 0x99, 0x27, 0x13, 0x50, 0x54, 0xbf, 0xef, 0x00, 0x71, 0x4f, 0x81, 0x40, 0x81, 0x80, 0x95, 0x00, 0xb3, 0x00, 0xd1, 0xc0, 0x01, 0x01, 0x01, 0x01, 0x02, 0x3a, 0x80, 0x18, 0x71, 0x38, 0x2d, 0x40, 0x58, 0x2c, 0x45, 0x00, 0x09, 0x25, 0x21, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x00, 0xff, 0x00, 0x43, 0x36, 0x4c, 0x4d, 0x54, 0x46, 0x30, 0x30, 0x34, 0x38, 0x32, 0x32, 0x0a, 0x00, 0x00, 0x00, 0xfd, 0x00, 0x37, 0x4b, 0x1e, 0x55, 0x10, 0x00, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x00, 0x00, 0x00, 0xfc, 0x00, 0x41, 0x53, 0x55, 0x53, 0x20, 0x56, 0x48, 0x32, 0x34, 0x32, 0x48, 0x0a, 0x20, 0x01, 0x78, 0x02, 0x03, 0x22, 0x71, 0x4f, 0x01, 0x02, 0x03, 0x11, 0x12, 0x13, 0x04, 0x14, 0x05, 0x0e, 0x0f, 0x1d, 0x1e, 0x1f, 0x10, 0x23, 0x09, 0x07, 0x01, 0x83, 0x01, 0x00, 0x00, 0x65, 0x03, 0x0c, 0x00, 0x10, 0x00, 0x8c, 0x0a, 0xd0, 0x8a, 0x20, 0xe0, 0x2d, 0x10, 0x10, 0x3e, 0x96, 0x00, 0x09, 0x25, 0x21, 0x00, 0x00, 0x18, 0x01, 0x1d, 0x00, 0x72, 0x51, 0xd0, 0x1e, 0x20, 0x6e, 0x28, 0x55, 0x00, 0x09, 0x25, 0x21, 0x00, 0x00, 0x1e, 0x01, 0x1d, 0x00, 0xbc, 0x52, 0xd0, 0x1e, 0x20, 0xb8, 0x28, 0x55, 0x40, 0x09, 0x25, 0x21, 0x00, 0x00, 0x1e, 0x8c, 0x0a, 0xd0, 0x90, 0x20, 0x40, 0x31, 0x20, 0x0c, 0x40, 0x55, 0x00, 0x09, 0x25, 0x21, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x73, }; /*! * Maintains the information on the current state of the sesor. */ static struct reg_value tc358743_setting_YUV422_2lane_30fps_720P_1280_720_125MHz[] = { {0x7080, 0x00000000, 0x00000000, 2, 0}, {0x0004, 0x00000004, 0x00000000, 2, 0}, {0x0002, 0x00000f00, 0x00000000, 2, 100}, {0x0002, 0x00000000, 0x00000000, 2, 1000}, {0x0006, 0x00000040, 0x00000000, 2, 0}, {0x0014, 0x00000000, 0x00000000, 2, 0}, {0x0016, 0x000005ff, 0x00000000, 2, 0}, // Program CSI Tx PLL {0x0020, 0x0000402d, 0x00000000, 2, 0}, {0x0022, 0x00000213, 0x00000000, 2, 0}, // CSI Tx PHY (32-bit Registers) {0x0140, 0x00000000, 0x00000000, 4, 0}, {0x0144, 0x00000000, 0x00000000, 4, 0}, {0x0148, 0x00000000, 0x00000000, 4, 0}, {0x014c, 0x00000000, 0x00000000, 4, 0}, {0x0150, 0x00000000, 0x00000000, 4, 0}, // CSI Tx PPI (32-bit Registers) {0x0210, 0x00000e00, 0x00000000, 4, 0}, {0x0214, 0x00000001, 0x00000000, 4, 0}, {0x0218, 0x00000801, 0x00000000, 4, 0}, {0x021c, 0x00000001, 0x00000000, 4, 0}, {0x0220, 0x00000001, 0x00000000, 4, 0}, {0x0224, 0x00004800, 0x00000000, 4, 0}, {0x0228, 0x00000005, 0x00000000, 4, 0}, {0x022c, 0x00000000, 0x00000000, 4, 0}, {0x0234, 0x0000001f, 0x00000000, 4, 0}, {0x0238, 0x00000001, 0x00000000, 4, 0}, //non-continuous clock {0x0204, 0x00000001, 0x00000000, 4, 0}, {0x0518, 0x00000001, 0x00000000, 4, 0}, {0x0500, 0xa300be82, 0x00000000, 4, 0}, // HDMI Interrupt Mask {0x8502, 0x00000001, 0x00000000, 1, 0}, {0x8512, 0x000000fe, 0x00000000, 1, 0}, {0x8514, 0x00000000, 0x00000000, 1, 0}, {0x8515, 0x00000000, 0x00000000, 1, 0}, {0x8516, 0x00000000, 0x00000000, 1, 0}, // HDMI Audio RefClk (26 MHz) {0x8531, 0x00000001, 0x00000000, 1, 0}, {0x8540, 0x0000008c, 0x00000000, 1, 0}, {0x8541, 0x0000000a, 0x00000000, 1, 0}, {0x8630, 0x000000b0, 0x00000000, 1, 0}, {0x8631, 0x0000001e, 0x00000000, 1, 0}, {0x8632, 0x00000004, 0x00000000, 1, 0}, {0x8670, 0x00000001, 0x00000000, 1, 0}, // HDMI PHY {0x8532, 0x00000080, 0x00000000, 1, 0}, {0x8536, 0x00000040, 0x00000000, 1, 0}, {0x853f, 0x0000000a, 0x00000000, 1, 0}, // EDID {0x85c7, 0x00000001, 0x00000000, 1, 0}, {0x85cb, 0x00000001, 0x00000000, 1, 0}, // HDMI System {0x8543, 0x00000032, 0x00000000, 1, 0}, // {0x8544, 0x00000000, 0x00000000, 1, 1000}, // {0x8544, 0x00000001, 0x00000000, 1, 100}, {0x8545, 0x00000031, 0x00000000, 1, 0}, {0x8546, 0x0000002d, 0x00000000, 1, 0}, // HDCP Setting {0x85d1, 0x00000001, 0x00000000, 1, 0}, {0x8560, 0x00000024, 0x00000000, 1, 0}, {0x8563, 0x00000011, 0x00000000, 1, 0}, {0x8564, 0x0000000f, 0x00000000, 1, 0}, // Video settings {0x8573, 0x00000081, 0x00000000, 1, 0}, {0x8571, 0x00000002, 0x00000000, 1, 0}, // HDMI Audio In Setting {0x8600, 0x00000000, 0x00000000, 1, 0}, {0x8602, 0x000000f3, 0x00000000, 1, 0}, {0x8603, 0x00000002, 0x00000000, 1, 0}, {0x8604, 0x0000000c, 0x00000000, 1, 0}, {0x8606, 0x00000005, 0x00000000, 1, 0}, {0x8607, 0x00000000, 0x00000000, 1, 0}, {0x8620, 0x00000022, 0x00000000, 1, 0}, {0x8640, 0x00000001, 0x00000000, 1, 0}, {0x8641, 0x00000065, 0x00000000, 1, 0}, {0x8642, 0x00000007, 0x00000000, 1, 0}, // {0x8651, 0x00000003, 0x00000000, 1, 0}, // Inverted LRCK polarity - (Sony) format {0x8652, 0x00000002, 0x00000000, 1, 0}, // Left-justified I2S (Phillips) format // {0x8652, 0x00000000, 0x00000000, 1, 0}, // Right-justified (Sony) format {0x8665, 0x00000010, 0x00000000, 1, 0}, // InfoFrame Extraction {0x8709, 0x000000ff, 0x00000000, 1, 0}, {0x870b, 0x0000002c, 0x00000000, 1, 0}, {0x870c, 0x00000053, 0x00000000, 1, 0}, {0x870d, 0x00000001, 0x00000000, 1, 0}, {0x870e, 0x00000030, 0x00000000, 1, 0}, {0x9007, 0x00000010, 0x00000000, 1, 0}, {0x854a, 0x00000001, 0x00000000, 1, 0}, // Output Control {0x0004, 0x00000cf7, 0x00000000, 2, 0}, }; static struct reg_value tc358743_setting_YUV422_4lane_720P_60fps_1280_720_133Mhz[] = { {0x7080, 0x00000000, 0x00000000, 2, 0}, {0x0004, 0x00000004, 0x00000000, 2, 0}, {0x0002, 0x00000f00, 0x00000000, 2, 100}, {0x0002, 0x00000000, 0x00000000, 2, 1000}, {0x0006, 0x00000000, 0x00000000, 2, 0}, {0x0014, 0x0000ffff, 0x00000000, 2, 0}, {0x0016, 0x000005ff, 0x00000000, 2, 0}, // Program CSI Tx PLL {0x0020, 0x00004062, 0x00000000, 2, 0}, {0x0022, 0x00000613, 0x00000000, 2, 0}, // CSI Tx PHY (32-bit Registers) {0x0140, 0x00000000, 0x00000000, 4, 0}, {0x0144, 0x00000000, 0x00000000, 4, 0}, {0x0148, 0x00000000, 0x00000000, 4, 0}, {0x014c, 0x00000000, 0x00000000, 4, 0}, {0x0150, 0x00000000, 0x00000000, 4, 0}, // CSI Tx PPI (32-bit Registers) {0x0210, 0x00000d00, 0x00000000, 4, 0}, {0x0214, 0x00000001, 0x00000000, 4, 0}, {0x0218, 0x00000701, 0x00000000, 4, 0}, {0x021c, 0x00000000, 0x00000000, 4, 0}, {0x0220, 0x00000001, 0x00000000, 4, 0}, {0x0224, 0x00004000, 0x00000000, 4, 0}, {0x0228, 0x00000005, 0x00000000, 4, 0}, {0x022c, 0x00000000, 0x00000000, 4, 0}, {0x0234, 0x0000001f, 0x00000000, 4, 0}, {0x0238, 0x00000001, 0x00000000, 4, 0}, {0x0204, 0x00000001, 0x00000000, 4, 0}, {0x0518, 0x00000001, 0x00000000, 4, 0}, {0x0500, 0xa300be86, 0x00000000, 4, 0}, // HDMI Interrupt Mask {0x8502, 0x00000001, 0x00000000, 1, 0}, {0x8512, 0x000000fe, 0x00000000, 1, 0}, {0x8514, 0x00000000, 0x00000000, 1, 0}, {0x8515, 0x00000000, 0x00000000, 1, 0}, {0x8516, 0x00000000, 0x00000000, 1, 0}, // HDMI Audio RefClk (26 MHz) {0x8531, 0x00000001, 0x00000000, 1, 0}, {0x8540, 0x00000a8c, 0x00000000, 1, 0}, {0x8630, 0x00041eb0, 0x00000000, 1, 0}, {0x8670, 0x00000001, 0x00000000, 1, 0}, // HDMI PHY {0x8532, 0x00000080, 0x00000000, 1, 0}, {0x8536, 0x00000040, 0x00000000, 1, 0}, {0x853f, 0x0000000a, 0x00000000, 1, 0}, // HDMI System {0x8543, 0x00000032, 0x00000000, 1, 0}, {0x8544, 0x00000000, 0x00000000, 1, 0}, {0x8545, 0x00000031, 0x00000000, 1, 0}, {0x8546, 0x0000002d, 0x00000000, 1, 0}, // EDID {0x85c7, 0x00000001, 0x00000000, 1, 0}, {0x85cb, 0x00000001, 0x00000000, 1, 0}, // HDCP Setting {0x85d1, 0x00000001, 0x00000000, 1, 0}, {0x8560, 0x00000024, 0x00000000, 1, 0}, {0x8563, 0x00000011, 0x00000000, 1, 0}, {0x8564, 0x0000000f, 0x00000000, 1, 0}, // RGB --> YUV Conversion // {0x8574, 0x00000000, 0x00000000, 1, 0}, {0x8573, 0x00000081, 0x00000000, 1, 0}, {0x8571, 0x00000002, 0x00000000, 1, 0}, // HDMI Audio In Setting {0x8600, 0x00000000, 0x00000000, 1, 0}, {0x8602, 0x000000f3, 0x00000000, 1, 0}, {0x8603, 0x00000002, 0x00000000, 1, 0}, {0x8604, 0x0000000c, 0x00000000, 1, 0}, {0x8606, 0x00000005, 0x00000000, 1, 0}, {0x8607, 0x00000000, 0x00000000, 1, 0}, {0x8620, 0x00000022, 0x00000000, 1, 0}, {0x8640, 0x00000001, 0x00000000, 1, 0}, {0x8641, 0x00000065, 0x00000000, 1, 0}, {0x8642, 0x00000007, 0x00000000, 1, 0}, {0x8652, 0x00000002, 0x00000000, 1, 0}, {0x8665, 0x00000010, 0x00000000, 1, 0}, // InfoFrame Extraction {0x8709, 0x000000ff, 0x00000000, 1, 0}, {0x870b, 0x0000002c, 0x00000000, 1, 0}, {0x870c, 0x00000053, 0x00000000, 1, 0}, {0x870d, 0x00000001, 0x00000000, 1, 0}, {0x870e, 0x00000030, 0x00000000, 1, 0}, {0x9007, 0x00000010, 0x00000000, 1, 0}, {0x854a, 0x00000001, 0x00000000, 1, 0}, // Output Control {0x0004, 0x00000cf7, 0x00000000, 2, 0}, }; static struct reg_value tc358743_setting_YUV422_2lane_color_bar_1280_720_125MHz[] = { {0x7080, 0x00000000, 0x00000000, 2, 0}, {0x0002, 0x00000f00, 0x00000000, 2, 100}, {0x0002, 0x00000000, 0x00000000, 2, 1000}, {0x0006, 0x00000000, 0x00000000, 2, 0}, {0x0004, 0x00000084, 0x00000000, 2, 0}, {0x0010, 0x0000001e, 0x00000000, 2, 0}, // Program CSI Tx PLL {0x0020, 0x0000405c, 0x00000000, 2, 0}, {0x0022, 0x00000613, 0x00000000, 2, 0}, // CSI Tx PHY (32-bit Registers) {0x0140, 0x00000000, 0x00000000, 4, 0}, {0x0144, 0x00000000, 0x00000000, 4, 0}, {0x0148, 0x00000000, 0x00000000, 4, 0}, {0x014c, 0x00000000, 0x00000000, 4, 0}, {0x0150, 0x00000000, 0x00000000, 4, 0}, // CSI Tx PPI (32-bit Registers) {0x0210, 0x00000e00, 0x00000000, 4, 0}, {0x0214, 0x00000001, 0x00000000, 4, 0}, {0x0218, 0x00000801, 0x00000000, 4, 0}, {0x021c, 0x00000000, 0x00000000, 4, 0}, {0x0220, 0x00000001, 0x00000000, 4, 0}, {0x0224, 0x00004000, 0x00000000, 4, 0}, {0x0228, 0x00000006, 0x00000000, 4, 0}, {0x022c, 0x00000000, 0x00000000, 4, 0}, {0x0234, 0x00000007, 0x00000000, 4, 0}, {0x0238, 0x00000001, 0x00000000, 4, 0}, //non-continuous clock {0x0204, 0x00000001, 0x00000000, 4, 0}, {0x0518, 0x00000001, 0x00000000, 4, 0}, {0x0500, 0xa30080a2, 0x00000000, 4, 0}, // 1280x720 colorbar {0x000a, 0x00000a00, 0x00000000, 2, 0}, {0x7080, 0x00000082, 0x00000000, 2, 0}, // 128 pixel black - repeat 128 times {0x7000, 0x0000007f, 0x00000000, 2, (1<<24)|(128<<16)}, // 128 pixel blue - repeat 64 times {0x7000, 0x000000ff, 0x00000000, 2, 0}, {0x7000, 0x00000000, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel red - repeat 64 times {0x7000, 0x00000000, 0x00000000, 2, 0}, {0x7000, 0x000000ff, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel pink - repeat 64 times {0x7000, 0x00007fff, 0x00000000, 2, 0}, {0x7000, 0x00007fff, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel green - repeat 64 times {0x7000, 0x00007f00, 0x00000000, 2, 0}, {0x7000, 0x00007f00, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel light blue - repeat 64 times {0x7000, 0x0000c0ff, 0x00000000, 2, 0}, {0x7000, 0x0000c000, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel yellow - repeat 64 times {0x7000, 0x0000ff00, 0x00000000, 2, 0}, {0x7000, 0x0000ffff, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel white - repeat 64 times {0x7000, 0x0000ff7f, 0x00000000, 2, 0}, {0x7000, 0x0000ff7f, 0x00000000, 2, (2<<24)|(64<<16)}, // 720 lines {0x7090, 0x000002cf, 0x00000000, 2, 0}, {0x7092, 0x00000580, 0x00000000, 2, 0}, {0x7094, 0x00000010, 0x00000000, 2, 0}, {0x7080, 0x00000083, 0x00000000, 2, 0}, }; static struct reg_value tc358743_setting_YUV422_4lane_color_bar_1280_720_125MHz[] = { {0x7080, 0x00000000, 0x00000000, 2, 0}, {0x0002, 0x00000f00, 0x00000000, 2, 100}, {0x0002, 0x00000000, 0x00000000, 2, 1000}, {0x0006, 0x00000000, 0x00000000, 2, 0}, {0x0004, 0x00000084, 0x00000000, 2, 0}, {0x0010, 0x0000001e, 0x00000000, 2, 0}, // Program CSI Tx PLL {0x0020, 0x0000405c, 0x00000000, 2, 0}, {0x0022, 0x00000613, 0x00000000, 2, 0}, // CSI Tx PHY (32-bit Registers) {0x0140, 0x00000000, 0x00000000, 4, 0}, {0x0144, 0x00000000, 0x00000000, 4, 0}, {0x0148, 0x00000000, 0x00000000, 4, 0}, {0x014c, 0x00000000, 0x00000000, 4, 0}, {0x0150, 0x00000000, 0x00000000, 4, 0}, // CSI Tx PPI (32-bit Registers) {0x0210, 0x00000e00, 0x00000000, 4, 0}, {0x0214, 0x00000001, 0x00000000, 4, 0}, {0x0218, 0x00000801, 0x00000000, 4, 0}, {0x021c, 0x00000000, 0x00000000, 4, 0}, {0x0220, 0x00000001, 0x00000000, 4, 0}, {0x0224, 0x00004000, 0x00000000, 4, 0}, {0x0228, 0x00000006, 0x00000000, 4, 0}, {0x022c, 0x00000000, 0x00000000, 4, 0}, {0x0234, 0x0000001F, 0x00000000, 4, 0}, //{0x0234, 0x00000007, 0x00000000, 4, 0}, {0x0238, 0x00000001, 0x00000000, 4, 0}, //non-continuous clock {0x0204, 0x00000001, 0x00000000, 4, 0}, {0x0518, 0x00000001, 0x00000000, 4, 0}, {0x0500, 0xa30080a6, 0x00000000, 4, 0}, //{0x0500, 0xa30080a2, 0x00000000, 4, 0}, // 1280x720 colorbar {0x000a, 0x00000a00, 0x00000000, 2, 0}, {0x7080, 0x00000082, 0x00000000, 2, 0}, // 128 pixel black - repeat 128 times {0x7000, 0x0000007f, 0x00000000, 2, (1<<24)|(128<<16)}, // 128 pixel blue - repeat 64 times {0x7000, 0x000000ff, 0x00000000, 2, 0}, {0x7000, 0x00000000, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel red - repeat 64 times {0x7000, 0x00000000, 0x00000000, 2, 0}, {0x7000, 0x000000ff, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel pink - repeat 64 times {0x7000, 0x00007fff, 0x00000000, 2, 0}, {0x7000, 0x00007fff, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel green - repeat 64 times {0x7000, 0x00007f00, 0x00000000, 2, 0}, {0x7000, 0x00007f00, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel light blue - repeat 64 times {0x7000, 0x0000c0ff, 0x00000000, 2, 0}, {0x7000, 0x0000c000, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel yellow - repeat 64 times {0x7000, 0x0000ff00, 0x00000000, 2, 0}, {0x7000, 0x0000ffff, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel white - repeat 64 times {0x7000, 0x0000ff7f, 0x00000000, 2, 0}, {0x7000, 0x0000ff7f, 0x00000000, 2, (2<<24)|(64<<16)}, // 720 lines {0x7090, 0x000002cf, 0x00000000, 2, 0}, {0x7092, 0x00000300, 0x00000000, 2, 0}, //{0x7092, 0x00000580, 0x00000000, 2, 0}, {0x7094, 0x00000010, 0x00000000, 2, 0}, {0x7080, 0x00000083, 0x00000000, 2, 0}, }; static struct reg_value tc358743_setting_YUV422_4lane_color_bar_1024_720_200MHz[] = { {0x7080, 0x00000000, 0x00000000, 2, 0}, {0x0002, 0x00000f00, 0x00000000, 2, 100}, {0x0002, 0x00000000, 0x00000000, 2, 1000}, {0x0006, 0x00000000, 0x00000000, 2, 0}, {0x0004, 0x00000084, 0x00000000, 2, 0}, {0x0010, 0x0000001e, 0x00000000, 2, 0}, // Program CSI Tx PLL {0x0020, 0x00004050, 0x00000000, 2, 0}, {0x0022, 0x00000213, 0x00000000, 2, 0}, // CSI Tx PHY (32-bit Registers) {0x0140, 0x00000000, 0x00000000, 4, 0}, {0x0144, 0x00000000, 0x00000000, 4, 0}, {0x0148, 0x00000000, 0x00000000, 4, 0}, {0x014c, 0x00000000, 0x00000000, 4, 0}, {0x0150, 0x00000000, 0x00000000, 4, 0}, // CSI Tx PPI (32-bit Registers) {0x0210, 0x00001800, 0x00000000, 4, 0}, {0x0214, 0x00000002, 0x00000000, 4, 0}, {0x0218, 0x00001102, 0x00000000, 4, 0}, {0x021c, 0x00000000, 0x00000000, 4, 0}, {0x0220, 0x00000003, 0x00000000, 4, 0}, {0x0224, 0x00004000, 0x00000000, 4, 0}, {0x0228, 0x00000007, 0x00000000, 4, 0}, {0x022c, 0x00000001, 0x00000000, 4, 0}, {0x0234, 0x0000001f, 0x00000000, 4, 0}, {0x0238, 0x00000001, 0x00000000, 4, 0}, //non-continuous clock {0x0204, 0x00000001, 0x00000000, 4, 0}, {0x0518, 0x00000001, 0x00000000, 4, 0}, {0x0500, 0xa30080a6, 0x00000000, 4, 0}, // 1280x720 colorbar {0x000a, 0x00000800, 0x00000000, 2, 0}, {0x7080, 0x00000082, 0x00000000, 2, 0}, // 128 pixel black - repeat 128 times {0x7000, 0x0000007f, 0x00000000, 2, (1<<24)|(128<<16)}, // 128 pixel blue - repeat 64 times {0x7000, 0x000000ff, 0x00000000, 2, 0}, {0x7000, 0x00000000, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel red - repeat 64 times {0x7000, 0x00000000, 0x00000000, 2, 0}, {0x7000, 0x000000ff, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel pink - repeat 64 times {0x7000, 0x00007fff, 0x00000000, 2, 0}, {0x7000, 0x00007fff, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel green - repeat 64 times {0x7000, 0x00007f00, 0x00000000, 2, 0}, {0x7000, 0x00007f00, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel light blue - repeat 64 times {0x7000, 0x0000c0ff, 0x00000000, 2, 0}, {0x7000, 0x0000c000, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel yellow - repeat 64 times {0x7000, 0x0000ff00, 0x00000000, 2, 0}, {0x7000, 0x0000ffff, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel white - repeat 64 times {0x7000, 0x0000ff7f, 0x00000000, 2, 0}, {0x7000, 0x0000ff7f, 0x00000000, 2, (2<<24)|(64<<16)}, // 720 lines {0x0020, 0x0000406f, 0x00000000, 2, 100}, {0x7090, 0x000002cf, 0x00000000, 2, 0}, {0x7092, 0x00000540, 0x00000000, 2, 0}, {0x7094, 0x00000010, 0x00000000, 2, 0}, {0x7080, 0x00000083, 0x00000000, 2, 0}, }; static struct reg_value tc358743_setting_YUV422_4lane_color_bar_1280_720_300MHz[] = { {0x7080, 0x00000000, 0x00000000, 2, 0}, {0x0002, 0x00000f00, 0x00000000, 2, 100}, {0x0002, 0x00000000, 0x00000000, 2, 1000}, {0x0006, 0x00000000, 0x00000000, 2, 0}, {0x0004, 0x00000084, 0x00000000, 2, 0}, {0x0010, 0x0000001e, 0x00000000, 2, 0}, // Program CSI Tx PLL {0x0020, 0x000080c7, 0x00000000, 2, 0}, {0x0022, 0x00000213, 0x00000000, 2, 0}, // CSI Tx PHY (32-bit Registers) {0x0140, 0x00000000, 0x00000000, 4, 0}, {0x0144, 0x00000000, 0x00000000, 4, 0}, {0x0148, 0x00000000, 0x00000000, 4, 0}, {0x014c, 0x00000000, 0x00000000, 4, 0}, {0x0150, 0x00000000, 0x00000000, 4, 0}, // CSI Tx PPI (32-bit Registers) {0x0210, 0x00001e00, 0x00000000, 4, 0}, {0x0214, 0x00000003, 0x00000000, 4, 0}, {0x0218, 0x00001402, 0x00000000, 4, 0}, {0x021c, 0x00000000, 0x00000000, 4, 0}, {0x0220, 0x00000003, 0x00000000, 4, 0}, {0x0224, 0x00004a00, 0x00000000, 4, 0}, {0x0228, 0x00000008, 0x00000000, 4, 0}, {0x022c, 0x00000002, 0x00000000, 4, 0}, {0x0234, 0x0000001f, 0x00000000, 4, 0}, {0x0238, 0x00000001, 0x00000000, 4, 0}, //non-continuous clock {0x0204, 0x00000001, 0x00000000, 4, 0}, {0x0518, 0x00000001, 0x00000000, 4, 0}, {0x0500, 0xa30080a6, 0x00000000, 4, 0}, // 1280x720 colorbar {0x000a, 0x00000a00, 0x00000000, 2, 0}, {0x7080, 0x00000082, 0x00000000, 2, 0}, // 128 pixel black - repeat 128 times {0x7000, 0x0000007f, 0x00000000, 2, (1<<24)|(128<<16)}, // 128 pixel blue - repeat 64 times {0x7000, 0x000000ff, 0x00000000, 2, 0}, {0x7000, 0x00000000, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel red - repeat 64 times {0x7000, 0x00000000, 0x00000000, 2, 0}, {0x7000, 0x000000ff, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel pink - repeat 64 times {0x7000, 0x00007fff, 0x00000000, 2, 0}, {0x7000, 0x00007fff, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel green - repeat 64 times {0x7000, 0x00007f00, 0x00000000, 2, 0}, {0x7000, 0x00007f00, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel light blue - repeat 64 times {0x7000, 0x0000c0ff, 0x00000000, 2, 0}, {0x7000, 0x0000c000, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel yellow - repeat 64 times {0x7000, 0x0000ff00, 0x00000000, 2, 0}, {0x7000, 0x0000ffff, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel white - repeat 64 times {0x7000, 0x0000ff7f, 0x00000000, 2, 0}, {0x7000, 0x0000ff7f, 0x00000000, 2, (2<<24)|(64<<16)}, // 720 lines {0x7090, 0x000002cf, 0x00000000, 2, 0}, {0x7092, 0x000006b8, 0x00000000, 2, 0}, {0x7094, 0x00000010, 0x00000000, 2, 0}, {0x7080, 0x00000083, 0x00000000, 2, 0}, }; static struct reg_value tc358743_setting_YUV422_4lane_color_bar_1920_1023_300MHz[] = { {0x7080, 0x00000000, 0x00000000, 2, 0}, {0x0002, 0x00000f00, 0x00000000, 2, 100}, {0x0002, 0x00000000, 0x00000000, 2, 1000}, {0x0006, 0x00000000, 0x00000000, 2, 0}, {0x0004, 0x00000084, 0x00000000, 2, 0}, {0x0010, 0x0000001e, 0x00000000, 2, 0}, // Program CSI Tx PLL {0x0020, 0x000080c7, 0x00000000, 2, 0}, {0x0022, 0x00000213, 0x00000000, 2, 0}, // CSI Tx PHY (32-bit Registers) {0x0140, 0x00000000, 0x00000000, 4, 0}, {0x0144, 0x00000000, 0x00000000, 4, 0}, {0x0148, 0x00000000, 0x00000000, 4, 0}, {0x014c, 0x00000000, 0x00000000, 4, 0}, {0x0150, 0x00000000, 0x00000000, 4, 0}, // CSI Tx PPI (32-bit Registers) {0x0210, 0x00001e00, 0x00000000, 4, 0}, {0x0214, 0x00000003, 0x00000000, 4, 0}, {0x0218, 0x00001402, 0x00000000, 4, 0}, {0x021c, 0x00000000, 0x00000000, 4, 0}, {0x0220, 0x00000003, 0x00000000, 4, 0}, {0x0224, 0x00004a00, 0x00000000, 4, 0}, {0x0228, 0x00000008, 0x00000000, 4, 0}, {0x022c, 0x00000002, 0x00000000, 4, 0}, {0x0234, 0x0000001f, 0x00000000, 4, 0}, {0x0238, 0x00000001, 0x00000000, 4, 0}, //non-continuous clock {0x0204, 0x00000001, 0x00000000, 4, 0}, {0x0518, 0x00000001, 0x00000000, 4, 0}, {0x0500, 0xa30080a6, 0x00000000, 4, 0}, // 1920x1023 colorbar {0x000a, 0x00000f00, 0x00000000, 2, 0}, {0x7080, 0x00000082, 0x00000000, 2, 0}, // 128 pixel black - repeat 128 times {0x7000, 0x0000007f, 0x00000000, 2, (1<<24)|(128<<16)}, // 128 pixel blue - repeat 64 times {0x7000, 0x000000ff, 0x00000000, 2, 0}, {0x7000, 0x00000000, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel red - repeat 64 times {0x7000, 0x00000000, 0x00000000, 2, 0}, {0x7000, 0x000000ff, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel pink - repeat 64 times {0x7000, 0x00007fff, 0x00000000, 2, 0}, {0x7000, 0x00007fff, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel green - repeat 64 times {0x7000, 0x00007f00, 0x00000000, 2, 0}, {0x7000, 0x00007f00, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel light blue - repeat 64 times {0x7000, 0x0000c0ff, 0x00000000, 2, 0}, {0x7000, 0x0000c000, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel yellow - repeat 64 times {0x7000, 0x0000ff00, 0x00000000, 2, 0}, {0x7000, 0x0000ffff, 0x00000000, 2, (2<<24)|(64<<16)}, // 128 pixel white - repeat 64 times {0x7000, 0x0000ff7f, 0x00000000, 2, 0}, {0x7000, 0x0000ff7f, 0x00000000, 2, (2<<24)|(64<<16)}, // 1023 lines {0x7090, 0x000003fe, 0x00000000, 2, 0}, {0x7092, 0x000004d8, 0x00000000, 2, 0}, {0x7094, 0x0000002d, 0x00000000, 2, 0}, {0x7080, 0x00000083, 0x00000000, 2, 0}, }; static struct reg_value tc358743_setting_YUV422_2lane_color_bar_640_480_174MHz[] = { {0x7080, 0x00000000, 0x00000000, 2, 0}, {0x0002, 0x00000f00, 0x00000000, 2, 100}, {0x0002, 0x00000000, 0x00000000, 2, 1000}, {0x0006, 0x00000000, 0x00000000, 2, 0}, {0x0004, 0x00000084, 0x00000000, 2, 0}, {0x0010, 0x0000001e, 0x00000000, 2, 0}, // Program CSI Tx PLL {0x0020, 0x00008073, 0x00000000, 2, 0}, {0x0022, 0x00000213, 0x00000000, 2, 0}, // CSI Tx PHY (32-bit Registers) {0x0140, 0x00000000, 0x00000000, 4, 0}, {0x0144, 0x00000000, 0x00000000, 4, 0}, {0x0148, 0x00000000, 0x00000000, 4, 0}, // {0x014c, 0x00000000, 0x00000000, 4, 0}, // {0x0150, 0x00000000, 0x00000000, 4, 0}, // CSI Tx PPI (32-bit Registers) {0x0210, 0x00001200, 0x00000000, 4, 0}, {0x0214, 0x00000002, 0x00000000, 4, 0}, {0x0218, 0x00000b02, 0x00000000, 4, 0}, {0x021c, 0x00000001, 0x00000000, 4, 0}, {0x0220, 0x00000103, 0x00000000, 4, 0}, {0x0224, 0x00004000, 0x00000000, 4, 0}, {0x0228, 0x00000008, 0x00000000, 4, 0}, {0x022c, 0x00000002, 0x00000000, 4, 0}, {0x0234, 0x0000001f, 0x00000000, 4, 0}, {0x0238, 0x00000000, 0x00000000, 4, 0}, {0x0204, 0x00000001, 0x00000000, 4, 0}, {0x0518, 0x00000001, 0x00000000, 4, 0}, {0x0500, 0xA3008082, 0x00000000, 4, 0}, // 640x480 colorbar {0x000a, 0x00000500, 0x00000000, 2, 0}, {0x7080, 0x00000082, 0x00000000, 2, 0}, // 80 pixel black - repeate 80 times {0x7000, 0x0000007f, 0x00000000, 2, (1<<24)|(80<<16)}, // 80 pixel blue - repeate 40 times {0x7000, 0x000000ff, 0x00000000, 2, 0}, {0x7000, 0x00000000, 0x00000000, 2, (2<<24)|(40<<16)}, // 80 pixel red - repeate 40 times {0x7000, 0x00000000, 0x00000000, 2, 0}, {0x7000, 0x000000ff, 0x00000000, 2, (2<<24)|(40<<16)}, // 80 pixel pink - repeate 40 times {0x7000, 0x00007fff, 0x00000000, 2, 0}, {0x7000, 0x00007fff, 0x00000000, 2, (2<<24)|(40<<16)}, // 80 pixel green - repeate 40 times {0x7000, 0x00007f00, 0x00000000, 2, 0}, {0x7000, 0x00007f00, 0x00000000, 2, (2<<24)|(40<<16)}, // 80 pixel light blue - repeate 40 times {0x7000, 0x0000c0ff, 0x00000000, 2, 0}, {0x7000, 0x0000c000, 0x00000000, 2, (2<<24)|(40<<16)}, // 80 pixel yellow - repeate 40 times {0x7000, 0x0000ff00, 0x00000000, 2, 0}, {0x7000, 0x0000ffff, 0x00000000, 2, (2<<24)|(40<<16)}, // 80 pixel white - repeate 40 times {0x7000, 0x0000ff7f, 0x00000000, 2, 0}, {0x7000, 0x0000ff7f, 0x00000000, 2, (2<<24)|(40<<16)}, // 480 lines {0x7090, 0x000001df, 0x00000000, 2, 0}, {0x7092, 0x00000898, 0x00000000, 2, 0}, {0x7094, 0x00000285, 0x00000000, 2, 0}, {0x7080, 0x00000083, 0x00000000, 2, 0}, }; static struct reg_value tc358743_setting_YUV422_2lane_color_bar_640_480_108MHz_cont[] = { {0x7080, 0x00000000, 0x00000000, 2, 0}, {0x0002, 0x00000f00, 0x00000000, 2, 100}, {0x0002, 0x00000000, 0x00000000, 2, 1000}, {0x0006, 0x00000000, 0x00000000, 2, 0}, {0x0004, 0x00000084, 0x00000000, 2, 0}, {0x0010, 0x0000001e, 0x00000000, 2, 0}, // Program CSI Tx PLL {0x0020, 0x0000404F, 0x00000000, 2, 0}, {0x0022, 0x00000613, 0x00000000, 2, 0}, // CSI Tx PHY (32-bit Registers) {0x0140, 0x00000000, 0x00000000, 4, 0}, {0x0144, 0x00000000, 0x00000000, 4, 0}, {0x0148, 0x00000000, 0x00000000, 4, 0}, {0x014c, 0x00000000, 0x00000000, 4, 0}, {0x0150, 0x00000000, 0x00000000, 4, 0}, // CSI Tx PPI (32-bit Registers) {0x0210, 0x00001800, 0x00000000, 4, 0}, {0x0214, 0x00000002, 0x00000000, 4, 0}, {0x0218, 0x00001102, 0x00000000, 4, 0}, {0x021c, 0x00000000, 0x00000000, 4, 0}, {0x0220, 0x00000003, 0x00000000, 4, 0}, {0x0224, 0x00004000, 0x00000000, 4, 0}, {0x0228, 0x00000007, 0x00000000, 4, 0}, {0x022c, 0x00000001, 0x00000000, 4, 0}, {0x0234, 0x0000001f, 0x00000000, 4, 0}, {0x0238, 0x00000001, 0x00000000, 4, 0}, {0x0204, 0x00000001, 0x00000000, 4, 0}, {0x0518, 0x00000001, 0x00000000, 4, 0}, {0x0500, 0xA30080A2, 0x00000000, 4, 0}, // 640x480 colorbar {0x000a, 0x00000500, 0x00000000, 2, 0}, {0x7080, 0x00000082, 0x00000000, 2, 0}, // 80 pixel black - repeate 80 times {0x7000, 0x0000007f, 0x00000000, 2, (1<<24)|(80<<16)}, // 80 pixel blue - repeate 40 times {0x7000, 0x000000ff, 0x00000000, 2, 0}, {0x7000, 0x00000000, 0x00000000, 2, (2<<24)|(40<<16)}, // 80 pixel red - repeate 40 times {0x7000, 0x00000000, 0x00000000, 2, 0}, {0x7000, 0x000000ff, 0x00000000, 2, (2<<24)|(40<<16)}, // 80 pixel pink - repeate 40 times {0x7000, 0x00007fff, 0x00000000, 2, 0}, {0x7000, 0x00007fff, 0x00000000, 2, (2<<24)|(40<<16)}, // 80 pixel green - repeate 40 times {0x7000, 0x00007f00, 0x00000000, 2, 0}, {0x7000, 0x00007f00, 0x00000000, 2, (2<<24)|(40<<16)}, // 80 pixel light blue - repeate 40 times {0x7000, 0x0000c0ff, 0x00000000, 2, 0}, {0x7000, 0x0000c000, 0x00000000, 2, (2<<24)|(40<<16)}, // 80 pixel yellow - repeate 40 times {0x7000, 0x0000ff00, 0x00000000, 2, 0}, {0x7000, 0x0000ffff, 0x00000000, 2, (2<<24)|(40<<16)}, // 80 pixel white - repeate 40 times {0x7000, 0x0000ff7f, 0x00000000, 2, 0}, {0x7000, 0x0000ff7f, 0x00000000, 2, (2<<24)|(40<<16)}, // 480 lines {0x7090, 0x000001df, 0x00000000, 2, 0}, {0x7092, 0x00000700, 0x00000000, 2, 0}, {0x7094, 0x00000010, 0x00000000, 2, 0}, {0x7080, 0x00000083, 0x00000000, 2, 0}, }; //480p RGB2YUV442 static struct reg_value tc358743_setting_YUV422_2lane_60fps_640_480_125Mhz[] = { {0x7080, 0x00000000, 0x00000000, 2, 0}, {0x0004, 0x00000004, 0x00000000, 2, 0}, {0x0002, 0x00000f00, 0x00000000, 2, 100}, {0x0002, 0x00000000, 0x00000000, 2, 1000}, {0x0006, 0x00000040, 0x00000000, 2, 0}, // {0x000a, 0x000005a0, 0x00000000, 2, 0}, // {0x0010, 0x0000001e, 0x00000000, 2, 0}, {0x0014, 0x00000000, 0x00000000, 2, 0}, {0x0016, 0x000005ff, 0x00000000, 2, 0}, // Program CSI Tx PLL {0x0020, 0x0000405c, 0x00000000, 2, 0}, {0x0022, 0x00000613, 0x00000000, 2, 0}, // CSI Tx PHY (32-bit Registers) {0x0140, 0x00000000, 0x00000000, 4, 0}, {0x0144, 0x00000000, 0x00000000, 4, 0}, {0x0148, 0x00000000, 0x00000000, 4, 0}, {0x014c, 0x00000000, 0x00000000, 4, 0}, {0x0150, 0x00000000, 0x00000000, 4, 0}, // CSI Tx PPI (32-bit Registers) {0x0210, 0x00000d00, 0x00000000, 4, 0}, {0x0214, 0x00000001, 0x00000000, 4, 0}, {0x0218, 0x00000701, 0x00000000, 4, 0}, {0x021c, 0x00000000, 0x00000000, 4, 0}, {0x0220, 0x00000001, 0x00000000, 4, 0}, {0x0224, 0x00004000, 0x00000000, 4, 0}, {0x0228, 0x00000005, 0x00000000, 4, 0}, {0x022c, 0x00000000, 0x00000000, 4, 0}, {0x0234, 0x0000001f, 0x00000000, 4, 0}, {0x0238, 0x00000001, 0x00000000, 4, 0}, {0x0204, 0x00000001, 0x00000000, 4, 0}, {0x0518, 0x00000001, 0x00000000, 4, 0}, {0x0500, 0xA30080A2, 0x00000000, 4, 0}, // HDMI Interrupt Mask {0x8502, 0x00000001, 0x00000000, 1, 0}, {0x8512, 0x000000fe, 0x00000000, 1, 0}, {0x8514, 0x00000000, 0x00000000, 1, 0}, {0x8515, 0x00000000, 0x00000000, 1, 0}, {0x8516, 0x00000000, 0x00000000, 1, 0}, // HDMI Audio RefClk (26 MHz) {0x8531, 0x00000001, 0x00000000, 1, 0}, {0x8540, 0x00000a8c, 0x00000000, 1, 0}, {0x8630, 0x00041eb0, 0x00000000, 1, 0}, {0x8670, 0x00000001, 0x00000000, 1, 0}, // HDMI PHY {0x8532, 0x00000080, 0x00000000, 1, 0}, {0x8536, 0x00000040, 0x00000000, 1, 0}, {0x853f, 0x0000000a, 0x00000000, 1, 0}, // HDMI System {0x8543, 0x00000032, 0x00000000, 1, 0}, {0x8544, 0x00000000, 0x00000000, 1, 100}, // {0x8544, 0x00000001, 0x00000000, 1, 100}, {0x8545, 0x00000031, 0x00000000, 1, 0}, {0x8546, 0x0000002d, 0x00000000, 1, 0}, // EDID {0x85c7, 0x00000001, 0x00000000, 1, 0}, {0x85cb, 0x00000001, 0x00000000, 1, 0}, // HDCP Setting {0x85d1, 0x00000001, 0x00000000, 1, 0}, {0x8560, 0x00000024, 0x00000000, 1, 0}, {0x8563, 0x00000011, 0x00000000, 1, 0}, {0x8564, 0x0000000f, 0x00000000, 1, 0}, // RGB --> YUV Conversion {0x8573, 0x00000081, 0x00000000, 1, 0}, {0x8571, 0x00000002, 0x00000000, 1, 0}, // HDMI Audio In Setting {0x8600, 0x00000000, 0x00000000, 1, 0}, {0x8602, 0x000000f3, 0x00000000, 1, 0}, {0x8603, 0x00000002, 0x00000000, 1, 0}, {0x8604, 0x0000000c, 0x00000000, 1, 0}, {0x8606, 0x00000005, 0x00000000, 1, 0}, {0x8607, 0x00000000, 0x00000000, 1, 0}, {0x8620, 0x00000022, 0x00000000, 1, 0}, {0x8640, 0x00000001, 0x00000000, 1, 0}, {0x8641, 0x00000065, 0x00000000, 1, 0}, {0x8642, 0x00000007, 0x00000000, 1, 0}, {0x8652, 0x00000002, 0x00000000, 1, 0}, {0x8665, 0x00000010, 0x00000000, 1, 0}, // InfoFrame Extraction {0x8709, 0x000000ff, 0x00000000, 1, 0}, {0x870b, 0x0000002c, 0x00000000, 1, 0}, {0x870c, 0x00000053, 0x00000000, 1, 0}, {0x870d, 0x00000001, 0x00000000, 1, 0}, {0x870e, 0x00000030, 0x00000000, 1, 0}, {0x9007, 0x00000010, 0x00000000, 1, 0}, {0x854a, 0x00000001, 0x00000000, 1, 0}, // Output Control {0x0004, 0x00000cf7, 0x00000000, 2, 0}, }; //480p RGB2YUV442 static struct reg_value tc358743_setting_YUV422_2lane_60fps_720_480_125Mhz[] = { {0x7080, 0x00000000, 0x00000000, 2, 0}, {0x0004, 0x00000004, 0x00000000, 2, 0}, {0x0002, 0x00000f00, 0x00000000, 2, 100}, {0x0002, 0x00000000, 0x00000000, 2, 1000}, {0x0006, 0x00000040, 0x00000000, 2, 0}, {0x000a, 0x000005a0, 0x00000000, 2, 0}, // {0x0010, 0x0000001e, 0x00000000, 2, 0}, {0x0014, 0x00000000, 0x00000000, 2, 0}, {0x0016, 0x000005ff, 0x00000000, 2, 0}, // Program CSI Tx PLL {0x0020, 0x0000405b, 0x00000000, 2, 0}, {0x0022, 0x00000613, 0x00000000, 2, 0}, // CSI Tx PHY (32-bit Registers) {0x0140, 0x00000000, 0x00000000, 4, 0}, {0x0144, 0x00000000, 0x00000000, 4, 0}, {0x0148, 0x00000000, 0x00000000, 4, 0}, {0x014c, 0x00000000, 0x00000000, 4, 0}, {0x0150, 0x00000000, 0x00000000, 4, 0}, // CSI Tx PPI (32-bit Registers) {0x0210, 0x00000d00, 0x00000000, 4, 0}, {0x0214, 0x00000001, 0x00000000, 4, 0}, {0x0218, 0x00000701, 0x00000000, 4, 0}, {0x021c, 0x00000000, 0x00000000, 4, 0}, {0x0220, 0x00000001, 0x00000000, 4, 0}, {0x0224, 0x00004000, 0x00000000, 4, 0}, {0x0228, 0x00000005, 0x00000000, 4, 0}, {0x022c, 0x00000000, 0x00000000, 4, 0}, {0x0234, 0x0000001f, 0x00000000, 4, 0}, {0x0238, 0x00000001, 0x00000000, 4, 0}, {0x0204, 0x00000001, 0x00000000, 4, 0}, {0x0518, 0x00000001, 0x00000000, 4, 0}, {0x0500, 0xA30080A2, 0x00000000, 4, 0}, // HDMI Interrupt Mask {0x8502, 0x00000001, 0x00000000, 1, 0}, {0x8512, 0x000000fe, 0x00000000, 1, 0}, {0x8514, 0x00000000, 0x00000000, 1, 0}, {0x8515, 0x00000000, 0x00000000, 1, 0}, {0x8516, 0x00000000, 0x00000000, 1, 0}, // HDMI Audio RefClk (27 MHz) {0x8531, 0x00000001, 0x00000000, 1, 0}, {0x8540, 0x00000a8c, 0x00000000, 1, 0}, {0x8630, 0x00041eb0, 0x00000000, 1, 0}, {0x8670, 0x00000001, 0x00000000, 1, 0}, // HDMI PHY {0x8532, 0x00000080, 0x00000000, 1, 0}, {0x8536, 0x00000040, 0x00000000, 1, 0}, {0x853f, 0x0000000a, 0x00000000, 1, 0}, // HDMI System {0x8543, 0x00000032, 0x00000000, 1, 0}, {0x8544, 0x00000000, 0x00000000, 1, 100}, // {0x8544, 0x00000001, 0x00000000, 1, 100}, {0x8545, 0x00000031, 0x00000000, 1, 0}, {0x8546, 0x0000002d, 0x00000000, 1, 0}, // EDID {0x85c7, 0x00000001, 0x00000000, 1, 0}, {0x85cb, 0x00000001, 0x00000000, 1, 0}, // HDCP Setting {0x85d1, 0x00000001, 0x00000000, 1, 0}, {0x8560, 0x00000024, 0x00000000, 1, 0}, {0x8563, 0x00000011, 0x00000000, 1, 0}, {0x8564, 0x0000000f, 0x00000000, 1, 0}, // RGB --> YUV Conversion {0x8573, 0x00000081, 0x00000000, 1, 0}, {0x8571, 0x00000002, 0x00000000, 1, 0}, // HDMI Audio In Setting {0x8600, 0x00000000, 0x00000000, 1, 0}, {0x8602, 0x000000f3, 0x00000000, 1, 0}, {0x8603, 0x00000002, 0x00000000, 1, 0}, {0x8604, 0x0000000c, 0x00000000, 1, 0}, {0x8606, 0x00000005, 0x00000000, 1, 0}, {0x8607, 0x00000000, 0x00000000, 1, 0}, {0x8620, 0x00000022, 0x00000000, 1, 0}, {0x8640, 0x00000001, 0x00000000, 1, 0}, {0x8641, 0x00000065, 0x00000000, 1, 0}, {0x8642, 0x00000007, 0x00000000, 1, 0}, {0x8652, 0x00000002, 0x00000000, 1, 0}, {0x8665, 0x00000010, 0x00000000, 1, 0}, // InfoFrame Extraction {0x8709, 0x000000ff, 0x00000000, 1, 0}, {0x870b, 0x0000002c, 0x00000000, 1, 0}, {0x870c, 0x00000053, 0x00000000, 1, 0}, {0x870d, 0x00000001, 0x00000000, 1, 0}, {0x870e, 0x00000030, 0x00000000, 1, 0}, {0x9007, 0x00000010, 0x00000000, 1, 0}, {0x854a, 0x00000001, 0x00000000, 1, 0}, // Output Control {0x0004, 0x00000cf7, 0x00000000, 2, 0}, }; static struct reg_value tc358743_setting_YUV422_4lane_1080P_60fps_1920_1080_300MHz[] = { {0x7080, 0x00000000, 0x00000000, 2, 0}, {0x0004, 0x00000084, 0x00000000, 2, 0}, {0x0002, 0x00000f00, 0x00000000, 2, 100},//0}, {0x0002, 0x00000000, 0x00000000, 2, 1000},//0}, {0x0006, 0x00000000, 0x00000000, 2, 0}, {0x0014, 0x00000000, 0x00000000, 2, 0}, {0x0016, 0x000005ff, 0x00000000, 2, 0}, // Program CSI Tx PLL {0x0020, 0x000080c7, 0x00000000, 2, 0}, {0x0022, 0x00000213, 0x00000000, 2, 0}, // CSI Tx PHY (32-bit Registers) {0x0140, 0x00000000, 0x00000000, 4, 0}, {0x0144, 0x00000000, 0x00000000, 4, 0}, {0x0148, 0x00000000, 0x00000000, 4, 0}, {0x014c, 0x00000000, 0x00000000, 4, 0}, {0x0150, 0x00000000, 0x00000000, 4, 0}, // CSI Tx PPI (32-bit Registers) {0x0210, 0x00001e00, 0x00000000, 4, 0}, {0x0214, 0x00000003, 0x00000000, 4, 0}, {0x0218, 0x00001402, 0x00000000, 4, 0}, {0x021c, 0x00000000, 0x00000000, 4, 0}, {0x0220, 0x00000003, 0x00000000, 4, 0}, {0x0224, 0x00004a00, 0x00000000, 4, 0}, {0x0228, 0x00000008, 0x00000000, 4, 0}, {0x022c, 0x00000002, 0x00000000, 4, 0}, {0x0234, 0x0000001f, 0x00000000, 4, 0}, {0x0238, 0x00000001, 0x00000000, 4, 0}, {0x0204, 0x00000001, 0x00000000, 4, 0}, {0x0518, 0x00000001, 0x00000000, 4, 0}, {0x0500, 0xa30080a6, 0x00000000, 4, 0}, // HDMI Interrupt Mask {0x8502, 0x00000001, 0x00000000, 1, 0}, {0x8512, 0x000000fe, 0x00000000, 1, 0}, {0x8514, 0x00000000, 0x00000000, 1, 0}, {0x8515, 0x00000000, 0x00000000, 1, 0}, {0x8516, 0x00000000, 0x00000000, 1, 0}, // HDMI Audio RefClk (27 MHz) {0x8531, 0x00000001, 0x00000000, 1, 0}, {0x8540, 0x00000a8c, 0x00000000, 1, 0}, {0x8630, 0x00041eb0, 0x00000000, 1, 0}, {0x8670, 0x00000001, 0x00000000, 1, 0}, // HDMI PHY {0x8532, 0x00000080, 0x00000000, 1, 0}, {0x8536, 0x00000040, 0x00000000, 1, 0}, {0x853f, 0x0000000a, 0x00000000, 1, 0}, // HDMI System {0x8543, 0x00000032, 0x00000000, 1, 0}, {0x8544, 0x00000010, 0x00000000, 1, 100}, {0x8545, 0x00000031, 0x00000000, 1, 0}, {0x8546, 0x0000002d, 0x00000000, 1, 0}, // EDID {0x85c7, 0x00000001, 0x00000000, 1, 0}, {0x85cb, 0x00000001, 0x00000000, 1, 0}, // HDCP Setting {0x85d1, 0x00000001, 0x00000000, 1, 0}, {0x8560, 0x00000024, 0x00000000, 1, 0}, {0x8563, 0x00000011, 0x00000000, 1, 0}, {0x8564, 0x0000000f, 0x00000000, 1, 0}, // RGB --> YUV Conversion {0x8571, 0x00000002, 0x00000000, 1, 0}, {0x8573, 0x00000081, 0x00000000, 1, 0}, {0x8576, 0x00000060, 0x00000000, 1, 0}, // HDMI Audio In Setting {0x8600, 0x00000000, 0x00000000, 1, 0}, {0x8602, 0x000000f3, 0x00000000, 1, 0}, {0x8603, 0x00000002, 0x00000000, 1, 0}, {0x8604, 0x0000000c, 0x00000000, 1, 0}, {0x8606, 0x00000005, 0x00000000, 1, 0}, {0x8607, 0x00000000, 0x00000000, 1, 0}, {0x8620, 0x00000022, 0x00000000, 1, 0}, {0x8640, 0x00000001, 0x00000000, 1, 0}, {0x8641, 0x00000065, 0x00000000, 1, 0}, {0x8642, 0x00000007, 0x00000000, 1, 0}, {0x8652, 0x00000002, 0x00000000, 1, 0}, {0x8665, 0x00000010, 0x00000000, 1, 0}, // InfoFrame Extraction {0x8709, 0x000000ff, 0x00000000, 1, 0}, {0x870b, 0x0000002c, 0x00000000, 1, 0}, {0x870c, 0x00000053, 0x00000000, 1, 0}, {0x870d, 0x00000001, 0x00000000, 1, 0}, {0x870e, 0x00000030, 0x00000000, 1, 0}, {0x9007, 0x00000010, 0x00000000, 1, 0}, {0x854a, 0x00000001, 0x00000000, 1, 0}, // Output Control {0x0004, 0x00000cf7, 0x00000000, 2, 0}, }; static struct reg_value tc358743_setting_YUV422_4lane_1080P_30fps_1920_1080_300MHz[] = { {0x7080, 0x00000000, 0x00000000, 2, 0}, // IR control resister {0x0004, 0x00000084, 0x00000000, 2, 0}, // Internal Generated output pattern,Do not send InfoFrame data out to CSI2,Audio output to CSI2-TX i/f,I2C address index increments on every data byte transfer, disable audio and video TX buffers {0x0002, 0x00000f00, 0x00000000, 2, 100},//0}, // Reset devices and set normal operatio (not sleep) {0x0002, 0x00000000, 0x00000000, 2, 1000},//0}, // Clear reset bits {0x0006, 0x000001f8, 0x00000000, 2, 0}, // FIFO level = 1f8 = 504 {0x0014, 0x00000000, 0x00000000, 2, 0}, // Clear interrupt status bits {0x0016, 0x000005ff, 0x00000000, 2, 0}, // Mask audio mute, CSI-TX, and the other interrups // Program CSI Tx PLL //{0x0020, 0x000080c7, 0x00000000, 2, 0}, // Input divider setting = 0x8 -> Division ratio = (PRD3..0) + 1 = 9, Feedback divider setting = 0xc7 -> Division ratio = (FBD8...0) + 1 = 200 {0x0020, 0x000080c7, 0x00000000, 2, 0}, // Input divider setting = 0x8 -> Division ratio = (PRD3..0) + 1 = 9, Feedback divider setting = 0xc7 -> Division ratio = (FBD8...0) + 1 = 200 {0x0022, 0x00000213, 0x00000000, 2, 0}, // HSCK frequency = 500MHz – 1GHz HSCK frequency, Loop bandwidth setting = 50% of maximum loop bandwidth (default), REFCLK toggling –> normal operation, REFCLK stops -> no oscillation, Bypass clock = normal operation, clocks switched off (output LOW), PLL Reset normal operation, PLL Enable = PLL on // CSI Tx PHY (32-bit Registers) {0x0140, 0x00000000, 0x00000000, 4, 0}, // Clock Lane DPHY Control: Bypass Lane Enable from PPI Layer enable. {0x0144, 0x00000000, 0x00000000, 4, 0}, // Data Lane 0 DPHY Control: Bypass Lane Enable from PPI Layer enable. {0x0148, 0x00000000, 0x00000000, 4, 0}, // Data Lane 1 DPHY Control: Bypass Lane Enable from PPI Layer enable. {0x014c, 0x00000000, 0x00000000, 4, 0}, // Data Lane 2 DPHY Control: Bypass Lane Enable from PPI Layer enable. {0x0150, 0x00000000, 0x00000000, 4, 0}, // Data Lane 3 DPHY Control: Bypass Lane Enable from PPI Layer enable. // CSI Tx PPI (32-bit Registers) {0x0210, 0x00001e00, 0x00000000, 4, 0}, // LINEINITCNT: Line Initialization Wait Counter = 0x1e00 = 7680 {0x0214, 0x00000003, 0x00000000, 4, 0}, // LPTXTIMECNT: SYSLPTX Timing Generation Counter = 3 {0x0218, 0x00001402, 0x00000000, 4, 0}, // TCLK_HEADERCNT: TCLK_ZERO Counter = 0x14 = 20, TCLK_PREPARE Counter = 0x02 = 2 {0x021c, 0x00000000, 0x00000000, 4, 0}, // TCLK_TRAILCNT: TCLK_TRAIL Counter = 0 {0x0220, 0x00000003, 0x00000000, 4, 0}, // THS_HEADERCNT: THS_ZERO Counter = 0, THS_PREPARE Counter = 3 {0x0224, 0x00004a00, 0x00000000, 4, 0}, // TWAKEUP: TWAKEUP Counter = 0x4a00 = 18944 {0x0228, 0x00000008, 0x00000000, 4, 0}, // TCLK_POSTCNT: TCLK_POST Counter = 8 {0x022c, 0x00000002, 0x00000000, 4, 0}, // THS_TRAILCNT: THS_TRAIL Counter = 2 {0x0234, 0x0000001f, 0x00000000, 4, 0}, // HSTXVREGEN: Enable voltage regulators for lanes and clk {0x0238, 0x00000001, 0x00000000, 4, 0}, // TXOPTIONCNTRL: Set Continuous Clock Mode {0x0204, 0x00000001, 0x00000000, 4, 0}, // PPI STARTCNTRL: start PPI function {0x0518, 0x00000001, 0x00000000, 4, 0}, // CSI_START: start {0x0500, 0xa30080a6, 0x00000000, 4, 0}, // CSI Configuration Register: set register 0x040C with data 0x80a6 (CSI MOde, Disables the HTX_TO timer, High-Speed data transfer is performed to Tx, DSCClk Stays in HS mode when Data Lane goes to LP, 4 Data Lanes,The EOT packet is automatically granted at the end of HS transfer then is transmitted) // HDMI Interrupt Mask {0x8502, 0x00000001, 0x00000000, 1, 0}, // SYSTEM INTERRUPT: clear DDC power change detection interrupt {0x8512, 0x000000fe, 0x00000000, 1, 0}, // SYS INTERRUPT MASK: DDC power change detection interrupt not masked {0x8514, 0x00000000, 0x00000000, 1, 0}, // PACKET INTERRUPT MASK: unmask all {0x8515, 0x00000000, 0x00000000, 1, 0}, // CBIT INTERRUPT MASK: unmask all {0x8516, 0x00000000, 0x00000000, 1, 0}, // AUDIO INTERRUPT MASK: unmask all // HDMI Audio RefClk (27 MHz) {0x8531, 0x00000001, 0x00000000, 1, 0}, // PHY CONTROL0: 27MHz, DDC5V detection operation. {0x8540, 0x00000a8c, 0x00000000, 1, 0}, // SYS FREQ0 Register: 27MHz {0x8630, 0x00041eb0, 0x00000000, 1, 0}, // Audio FS Lock Detect Control: for 27MHz {0x8670, 0x00000001, 0x00000000, 1, 0}, // AUDIO PLL Setting: For REFCLK = 27MHz // HDMI PHY {0x8532, 0x00000080, 0x00000000, 1, 0}, // {0x8536, 0x00000040, 0x00000000, 1, 0}, // {0x853f, 0x0000000a, 0x00000000, 1, 0}, // // HDMI System {0x8543, 0x00000032, 0x00000000, 1, 0}, // DDC CONTROL: DDC_ACK output terminal H active, DDC5V_active detect delay 200ms {0x8544, 0x00000010, 0x00000000, 1, 100}, // HPD Control Register: HOTPLUG output ON/OFF control mode = DDC5V detection interlock {0x8545, 0x00000031, 0x00000000, 1, 0}, // ANA CONTROL: PLL charge pump setting for Audio = normal, DAC/PLL power ON/OFF setting for Audio = ON {0x8546, 0x0000002d, 0x00000000, 1, 0}, // AVMUTE CONTROL: AVM_CTL = 0x2d // EDID {0x85c7, 0x00000001, 0x00000000, 1, 0}, // EDID MODE REGISTER: nternal EDID-RAM & DDC2B mode {0x85cb, 0x00000001, 0x00000000, 1, 0}, // EDID Length REGISTER 2: EDID data size stored in RAM (upper address bits) = 0x1 (Size = 0x100 = 256) // HDCP Setting {0x85d1, 0x00000001, 0x00000000, 1, 0}, // {0x8560, 0x00000024, 0x00000000, 1, 0}, // HDCP MODE: HDCP automatic reset when DVI⇔HDMI switched = on, HDCP Line Rekey timing switch = 7clk mode (Data island delay ON), Bcaps[5] KSVINFO_READY(0x8840[5]) auto clear mode = Auto clear using AKSV write {0x8563, 0x00000011, 0x00000000, 1, 0}, // {0x8564, 0x0000000f, 0x00000000, 1, 0}, // // RGB --> YUV Conversion {0x8571, 0x00000002, 0x00000000, 1, 0}, // {0x8573, 0x000000c1, 0x00000000, 1, 0}, // VOUT SET2 REGISTER: 422 fixed output, Video Output 422 conversion mode selection 000: During 444 input, 3tap filter; during 422 input, simple decimation, Enable RGB888 to YUV422 Conversion (Fixed Color output) {0x8574, 0x00000008, 0x00000000, 1, 0}, // VOUT SET3 REGISTER (VOUT_SET3): Follow register bit 0x8573[7] setting {0x8576, 0x00000060, 0x00000000, 1, 0}, // VOUT_COLOR: Output Color = 601 YCbCr Limited, Input Pixel Repetition judgment = automatic, Input Pixel Repetition HOST setting = no repetition // HDMI Audio In Setting {0x8600, 0x00000000, 0x00000000, 1, 0}, {0x8602, 0x000000f3, 0x00000000, 1, 0}, {0x8603, 0x00000002, 0x00000000, 1, 0}, {0x8604, 0x0000000c, 0x00000000, 1, 0}, {0x8606, 0x00000005, 0x00000000, 1, 0}, {0x8607, 0x00000000, 0x00000000, 1, 0}, {0x8620, 0x00000022, 0x00000000, 1, 0}, {0x8640, 0x00000001, 0x00000000, 1, 0}, {0x8641, 0x00000065, 0x00000000, 1, 0}, {0x8642, 0x00000007, 0x00000000, 1, 0}, {0x8652, 0x00000002, 0x00000000, 1, 0}, {0x8665, 0x00000010, 0x00000000, 1, 0}, // InfoFrame Extraction {0x8709, 0x000000ff, 0x00000000, 1, 0}, // PACKET INTERRUPT MODE: all enable {0x870b, 0x0000002c, 0x00000000, 1, 0}, // NO PACKET LIMIT: NO_ACP_LIMIT = 0x2, NO_AVI_LIMIT = 0xC {0x870c, 0x00000053, 0x00000000, 1, 0}, // When VS receive interrupt is detected, VS storage register automatic clear, When ACP receive interrupt is detected, ACP storage register automatic clear, When AVI receive interrupt occurs, judge input video signal with RGB and no Repetition, When AVI receive interrupt is detected, AVI storage register automatic clear. {0x870d, 0x00000001, 0x00000000, 1, 0}, // ERROR PACKET LIMIT: Packet continuing receive error occurrence detection threshold = 1 {0x870e, 0x00000030, 0x00000000, 1, 0}, // NO PACKET LIMIT: {0x9007, 0x00000010, 0x00000000, 1, 0}, // {0x854a, 0x00000001, 0x00000000, 1, 0}, // Initialization completed flag // Output Control {0x0004, 0x00000cf7, 0x00000000, 2, 0}, // Configuration Control Register: Power Island Normal, I2S/TDM clock are free running, Enable 2 Audio channels, Audio channel number Auto detect by HW, I2S/TDM Data no delay, Select YCbCr422 8-bit (HDMI YCbCr422 12-bit data format), Send InfoFrame data out to CSI2, Audio output to I2S i/f (valid for 2 channel only), I2C address index increments on every data byte transfer, Audio and Video tx buffres enable. }; /* list of image formats supported by TCM825X sensor */ static const struct v4l2_fmtdesc tc358743_formats[] = { { .description = "RGB888 (RGB24)", .pixelformat = V4L2_PIX_FMT_RGB24, /* 24 RGB-8-8-8 */ .flags = MIPI_DT_RGB888 // 0x24 }, { .description = "RAW12 (Y/CbCr 4:2:0)", .pixelformat = V4L2_PIX_FMT_UYVY, /* 12 Y/CbCr 4:2:0 */ .flags = MIPI_DT_RAW12 // 0x2c }, { .description = "YUV 4:2:2 8-bit", .pixelformat = V4L2_PIX_FMT_YUYV, /* 8 8-bit color */ .flags = MIPI_DT_YUV422 // 0x1e /* UYVY... */ }, }; static struct tc358743_mode_info tc358743_mode_info_data[2][tc358743_mode_MAX] = { [0][tc358743_mode_720P_60_1280_720] = {tc358743_mode_720P_60_1280_720, 1280, 720, 12, 0, 4, 133, tc358743_setting_YUV422_4lane_720P_60fps_1280_720_133Mhz, ARRAY_SIZE(tc358743_setting_YUV422_4lane_720P_60fps_1280_720_133Mhz), MIPI_DT_YUV422 }, [0][tc358743_mode_1080P_1920_1080] = {tc358743_mode_1080P_1920_1080, 1920, 1080, 15, 0x0b, 4, 300, tc358743_setting_YUV422_4lane_1080P_60fps_1920_1080_300MHz, ARRAY_SIZE(tc358743_setting_YUV422_4lane_1080P_60fps_1920_1080_300MHz), MIPI_DT_YUV422 }, [0][tc358743_mode_INIT1] = {tc358743_mode_INIT1, 1280, 720, 12, 0, 2, 125, tc358743_setting_YUV422_2lane_color_bar_1280_720_125MHz, ARRAY_SIZE(tc358743_setting_YUV422_2lane_color_bar_1280_720_125MHz), MIPI_DT_YUV422 }, [0][tc358743_mode_INIT2] = {tc358743_mode_INIT2, 1280, 720, 12, 0, 4, 125, tc358743_setting_YUV422_4lane_color_bar_1280_720_125MHz, ARRAY_SIZE(tc358743_setting_YUV422_4lane_color_bar_1280_720_125MHz), MIPI_DT_YUV422 }, [0][tc358743_mode_INIT] = {tc358743_mode_INIT, 640, 480, 6, 1, 2, 108, tc358743_setting_YUV422_2lane_color_bar_640_480_108MHz_cont, ARRAY_SIZE(tc358743_setting_YUV422_2lane_color_bar_640_480_108MHz_cont), MIPI_DT_YUV422 }, [0][tc358743_mode_INIT4] = {tc358743_mode_INIT4, 640, 480, 6, 1, 2, 174, tc358743_setting_YUV422_2lane_color_bar_640_480_174MHz, ARRAY_SIZE(tc358743_setting_YUV422_2lane_color_bar_640_480_174MHz), MIPI_DT_YUV422 }, [0][tc358743_mode_INIT3] = {tc358743_mode_INIT3, 1024, 720, 6, 1, 4, 300, tc358743_setting_YUV422_4lane_color_bar_1024_720_200MHz, ARRAY_SIZE(tc358743_setting_YUV422_4lane_color_bar_1024_720_200MHz), MIPI_DT_YUV422 }, [0][tc358743_mode_720P_1280_720] = {tc358743_mode_720P_1280_720, 1280, 720, 12, (0x3e)<<8|(0x3c), 2, 125, tc358743_setting_YUV422_2lane_30fps_720P_1280_720_125MHz, ARRAY_SIZE(tc358743_setting_YUV422_2lane_30fps_720P_1280_720_125MHz), MIPI_DT_YUV422, }, [0][tc358743_mode_480P_720_480] = {tc358743_mode_480P_720_480, 720, 480, 6, (0x02)<<8|(0x00), 2, 125, tc358743_setting_YUV422_2lane_60fps_720_480_125Mhz, ARRAY_SIZE(tc358743_setting_YUV422_2lane_60fps_720_480_125Mhz), MIPI_DT_YUV422, }, [0][tc358743_mode_480P_640_480] = {tc358743_mode_480P_640_480, 640, 480, 6, (0x02)<<8|(0x00), 2, 125, tc358743_setting_YUV422_2lane_60fps_640_480_125Mhz, ARRAY_SIZE(tc358743_setting_YUV422_2lane_60fps_640_480_125Mhz), MIPI_DT_YUV422, }, [0][tc358743_mode_INIT5] = {tc358743_mode_INIT5, 1280, 720, 12, 0, 4, 300, tc358743_setting_YUV422_4lane_color_bar_1280_720_300MHz, ARRAY_SIZE(tc358743_setting_YUV422_4lane_color_bar_1280_720_300MHz), MIPI_DT_YUV422 }, [0][tc358743_mode_INIT6] = {tc358743_mode_INIT6, 1920, 1023, 15, 0, 4, 300, tc358743_setting_YUV422_4lane_color_bar_1920_1023_300MHz, ARRAY_SIZE(tc358743_setting_YUV422_4lane_color_bar_1920_1023_300MHz), MIPI_DT_YUV422 }, [1][tc358743_mode_720P_60_1280_720] = {tc358743_mode_720P_60_1280_720, 1280, 720, 12, 0, 4, 133, tc358743_setting_YUV422_4lane_720P_60fps_1280_720_133Mhz, ARRAY_SIZE(tc358743_setting_YUV422_4lane_720P_60fps_1280_720_133Mhz), MIPI_DT_YUV422 }, [1][tc358743_mode_1080P_1920_1080] = {tc358743_mode_1080P_1920_1080, 1920, 1080, 15, 0xa, 4, 300, tc358743_setting_YUV422_4lane_1080P_30fps_1920_1080_300MHz, ARRAY_SIZE(tc358743_setting_YUV422_4lane_1080P_30fps_1920_1080_300MHz), MIPI_DT_YUV422 }, [1][tc358743_mode_INIT1] = {tc358743_mode_INIT1, 1280, 720, 12, 0, 2, 125, tc358743_setting_YUV422_2lane_color_bar_1280_720_125MHz, ARRAY_SIZE(tc358743_setting_YUV422_2lane_color_bar_1280_720_125MHz), MIPI_DT_YUV422 }, [1][tc358743_mode_INIT2] = {tc358743_mode_INIT2, 1280, 720, 12, 0, 4, 125, tc358743_setting_YUV422_4lane_color_bar_1280_720_125MHz, ARRAY_SIZE(tc358743_setting_YUV422_4lane_color_bar_1280_720_125MHz), MIPI_DT_YUV422 }, [1][tc358743_mode_INIT] = {tc358743_mode_INIT, 640, 480, 6, 1, 2, 108, tc358743_setting_YUV422_2lane_color_bar_640_480_108MHz_cont, ARRAY_SIZE(tc358743_setting_YUV422_2lane_color_bar_640_480_108MHz_cont), MIPI_DT_YUV422 }, [1][tc358743_mode_INIT4] = {tc358743_mode_INIT4, 640, 480, 6, 1, 2, 174, tc358743_setting_YUV422_2lane_color_bar_640_480_174MHz, ARRAY_SIZE(tc358743_setting_YUV422_2lane_color_bar_640_480_174MHz), MIPI_DT_YUV422 }, [1][tc358743_mode_INIT3] = {tc358743_mode_INIT3, 1024, 720, 6, 1, 4, 300, tc358743_setting_YUV422_4lane_color_bar_1024_720_200MHz, ARRAY_SIZE(tc358743_setting_YUV422_4lane_color_bar_1024_720_200MHz), MIPI_DT_YUV422 }, [1][tc358743_mode_720P_1280_720] = {tc358743_mode_720P_1280_720, 1280, 720, 12, (0x3e)<<8|(0x3c), 2, 125, tc358743_setting_YUV422_2lane_30fps_720P_1280_720_125MHz, ARRAY_SIZE(tc358743_setting_YUV422_2lane_30fps_720P_1280_720_125MHz), MIPI_DT_YUV422, }, [1][tc358743_mode_480P_720_480] = {tc358743_mode_480P_720_480, 720, 480, 6, (0x02)<<8|(0x00), 2, 125, tc358743_setting_YUV422_2lane_60fps_720_480_125Mhz, ARRAY_SIZE(tc358743_setting_YUV422_2lane_60fps_720_480_125Mhz), MIPI_DT_YUV422, }, [0][tc358743_mode_480P_640_480] = {tc358743_mode_480P_640_480, 640, 480, 1, (0x02)<<8|(0x00), 2, 125, tc358743_setting_YUV422_2lane_60fps_640_480_125Mhz, ARRAY_SIZE(tc358743_setting_YUV422_2lane_60fps_640_480_125Mhz), MIPI_DT_YUV422, }, [1][tc358743_mode_INIT5] = {tc358743_mode_INIT5, 1280, 720, 12, 0, 4, 300, tc358743_setting_YUV422_4lane_color_bar_1280_720_300MHz, ARRAY_SIZE(tc358743_setting_YUV422_4lane_color_bar_1280_720_300MHz), MIPI_DT_YUV422 }, [1][tc358743_mode_INIT6] = {tc358743_mode_INIT6, 1920, 1023, 15, 0, 4, 300, tc358743_setting_YUV422_4lane_color_bar_1920_1023_300MHz, ARRAY_SIZE(tc358743_setting_YUV422_4lane_color_bar_1920_1023_300MHz), MIPI_DT_YUV422 }, }; static int tc358743_probe(struct i2c_client *adapter, const struct i2c_device_id *device_id); static int tc358743_remove(struct i2c_client *client); static s32 tc358743_read_reg(u16 reg, u32 *val); static s32 tc358743_write_reg(u16 reg, u32 val, int len); static const struct i2c_device_id tc358743_id[] = { {"tc358743_mipi", 0}, {}, }; MODULE_DEVICE_TABLE(i2c, tc358743_id); static struct i2c_driver tc358743_i2c_driver = { .driver = { .owner = THIS_MODULE, .name = "tc358743_mipi", }, .probe = tc358743_probe, .remove = tc358743_remove, .id_table = tc358743_id, }; struct _reg_size { u16 startaddr, endaddr; int size; } tc358743_read_reg_size [] = { {0x0000, 0x005a, 2}, {0x0140, 0x0150, 4}, {0x0204, 0x0238, 4}, {0x040c, 0x0418, 4}, {0x044c, 0x0454, 4}, {0x0500, 0x0518, 4}, {0x0600, 0x06cc, 4}, {0x7000, 0x7100, 2}, {0x8500, 0x8bff, 1}, {0x8c00, 0x8fff, 4}, {0x9000, 0x90ff, 1}, {0x9100, 0x92ff, 1}, {0, 0, 0}, }; static s32 tc358743_write_reg(u16 reg, u32 val, int len) { int i = 0; u32 data = val; u8 au8Buf[6] = {0}; int size = 0; while (0 != tc358743_read_reg_size[i].startaddr || 0 != tc358743_read_reg_size[i].endaddr || 0 != tc358743_read_reg_size[i].size) { if (tc358743_read_reg_size[i].startaddr <= reg && tc358743_read_reg_size[i].endaddr >= reg) { size = tc358743_read_reg_size[i].size; break; } i++; } if (!size) { pr_err("%s:write reg error:reg=%x is not found\n",__func__, reg); return -1; } if (size == 3) { size = 2; } else if (size != len) { pr_err("%s:write reg len error:reg=%x %d instead of %d\n", __func__, reg, len, size); return 0; } while (len > 0) { i = 0; au8Buf[i++] = (reg >> 8) & 0xff; au8Buf[i++] = reg & 0xff; while (size-- > 0) { au8Buf[i++] = (u8)data; data >>= 8; } if (i2c_master_send(tc358743_data.i2c_client, au8Buf, i) < 0) { pr_err("%s:write reg error:reg=%x,val=%x\n", __func__, reg, val); return -1; } len -= (u8)size; reg += (u16)size; } return 0; } static s32 tc358743_read_reg(u16 reg, u32 *val) { u8 au8RegBuf[2] = {0}; u32 u32RdVal = 0; int i=0; int size = 0; while (0 != tc358743_read_reg_size[i].startaddr || 0 != tc358743_read_reg_size[i].endaddr || 0 != tc358743_read_reg_size[i].size) { if (tc358743_read_reg_size[i].startaddr <= reg && tc358743_read_reg_size[i].endaddr >= reg) { size = tc358743_read_reg_size[i].size; break; } i++; } if (!size) return -1; au8RegBuf[0] = reg >> 8; au8RegBuf[1] = reg & 0xff; if (2 != i2c_master_send(tc358743_data.i2c_client, au8RegBuf, 2)) { pr_err("%s:read reg error:reg=%x\n", __func__, reg); return -1; } if (size /*of(u32RdVal)*/ != i2c_master_recv(tc358743_data.i2c_client, (char *)&u32RdVal, size /*of(u32RdVal)*/)) { pr_err("%s:read reg error:reg=%x,val=%x\n", __func__, reg, u32RdVal); return -1; } *val = u32RdVal; return size; } static int tc358743_write_edid(u8 *edid, int len) { int i = 0, off = 0; u8 au8Buf[8+2] = {0}; int size = 0; u16 reg; reg = 0x8C00; off = 0; size = ARRAY_SIZE(au8Buf)-2; pr_debug("Write EDID: %d (%d)\n", len, size); while (len > 0) { i = 0; au8Buf[i++] = (reg >> 8) & 0xff; au8Buf[i++] = reg & 0xff; while (i < ARRAY_SIZE(au8Buf)) { au8Buf[i++] = edid[off++]; } if (i2c_master_send(tc358743_data.i2c_client, au8Buf, i) < 0) { pr_err("%s:write reg error:reg=%x,val=%x\n", __func__, reg, off); return -1; } len -= (u8)size; reg += (u16)size; } pr_debug("Activate EDID\n"); tc358743_write_reg(0x85c7, 0x01, 1); tc358743_write_reg(0x85ca, 0x00, 1); tc358743_write_reg(0x85cb, 0x01, 1); return 0; } static int tc358743_reset(struct sensor_data *sensor) { u32 tgt_fps; /* target frames per secound */ enum tc358743_frame_rate frame_rate = tc358743_60_fps; int ret = -1; det_work_enable(0); while (ret) { tc_standby(1); mdelay(100); tc_standby(0); mdelay(1000); tgt_fps = sensor->streamcap.timeperframe.denominator / sensor->streamcap.timeperframe.numerator; if (tgt_fps == 60) frame_rate = tc358743_60_fps; else if (tgt_fps == 30) frame_rate = tc358743_30_fps; pr_debug("%s: capture mode: %d extended mode: %d fps: %d\n", __func__,sensor->streamcap.capturemode, sensor->streamcap.extendedmode, tgt_fps); ret = tc358743_init_mode(frame_rate, sensor->streamcap.capturemode); if (ret) pr_err("%s: Fail to init tc35874! - retry\n", __func__); } det_work_enable(1); return ret; } void mipi_csi2_swreset(struct mipi_csi2_info *info); #include "../../../../mxc/mipi/mxc_mipi_csi2.h" static int tc358743_init_mode(enum tc358743_frame_rate frame_rate, enum tc358743_mode mode) { struct reg_value *pModeSetting = NULL; s32 i = 0; s32 iModeSettingArySize = 0; register u32 RepeateLines = 0; register int RepeateTimes = 0; register u32 Delay_ms = 0; register u16 RegAddr = 0; register u32 Mask = 0; register u32 Val = 0; u8 Length; u32 RegVal = 0; int retval = 0; void *mipi_csi2_info; u32 mipi_reg; u32 mipi_reg_test[10]; pr_debug("%s rate: %d mode: %d\n", __func__, frame_rate, mode); if ((mode > tc358743_mode_MAX || mode < 0) && (mode != tc358743_mode_INIT)) { pr_debug("%s Wrong tc358743 mode detected! %d. Set mode 0\n", __func__, mode); mode = 0; } mipi_csi2_info = mipi_csi2_get_info(); pr_debug("%s rate: %d mode: %d, info %p\n", __func__, frame_rate, mode, mipi_csi2_info); /* initial mipi dphy */ tc358743_toggle_hpd(!hpd_active); if (mipi_csi2_info) { pr_debug("%s: mipi_csi2_info:\n" "mipi_en: %d\n" "ipu_id: %d\n" "csi_id: %d\n" "v_channel: %d\n" "lanes: %d\n" "datatype: %d\n" "dphy_clk: %p\n" "pixel_clk: %p\n" "mipi_csi2_base:%p\n" "pdev: %p\n" , __func__, ((struct mipi_csi2_info *)mipi_csi2_info)->mipi_en, ((struct mipi_csi2_info *)mipi_csi2_info)->ipu_id, ((struct mipi_csi2_info *)mipi_csi2_info)->csi_id, ((struct mipi_csi2_info *)mipi_csi2_info)->v_channel, ((struct mipi_csi2_info *)mipi_csi2_info)->lanes, ((struct mipi_csi2_info *)mipi_csi2_info)->datatype, ((struct mipi_csi2_info *)mipi_csi2_info)->dphy_clk, ((struct mipi_csi2_info *)mipi_csi2_info)->pixel_clk, ((struct mipi_csi2_info *)mipi_csi2_info)->mipi_csi2_base, ((struct mipi_csi2_info *)mipi_csi2_info)->pdev ); if (!mipi_csi2_get_status(mipi_csi2_info)) mipi_csi2_enable(mipi_csi2_info); if (mipi_csi2_get_status(mipi_csi2_info)) { int ifmt; if (tc358743_mode_info_data[frame_rate][mode].lanes != 0) { pr_debug("%s Change lanes: from %d to %d\n", __func__, ((struct mipi_csi2_info *)mipi_csi2_info)->lanes, tc358743_mode_info_data[frame_rate][mode].lanes); ((struct mipi_csi2_info *)mipi_csi2_info)->lanes = tc358743_mode_info_data[frame_rate][mode].lanes; ((struct mipi_csi2_info *)mipi_csi2_info)->lanes = tc358743_mode_info_data[frame_rate][mode].lanes; } pr_debug("Now Using %d lanes\n",mipi_csi2_set_lanes(mipi_csi2_info)); /*Only reset MIPI CSI2 HW at sensor initialize*/ if (!hdmi_mode) // is this during reset mipi_csi2_reset(mipi_csi2_info); pr_debug("%s format: %x\n", __func__, tc358743_data.pix.pixelformat); for (ifmt = 0; ifmt < ARRAY_SIZE(tc358743_formats); ifmt++) if (tc358743_mode_info_data[frame_rate][mode].flags == tc358743_formats[ifmt].flags) { tc358743_data.pix.pixelformat = tc358743_formats[ifmt].pixelformat; pr_debug("%s: %s (%x, %x)\n", __func__, tc358743_formats[ifmt].description, tc358743_data.pix.pixelformat, tc358743_formats[ifmt].flags); mipi_csi2_set_datatype(mipi_csi2_info, tc358743_formats[ifmt].flags); break; } if (ifmt >= ARRAY_SIZE(tc358743_formats)) { pr_err("currently this sensor format (0x%x) can not be supported!\n", tc358743_data.pix.pixelformat); return -1; } } else { pr_err("Can not enable mipi csi2 driver!\n"); return -1; } } else { pr_err("Fail to get mipi_csi2_info!\n"); return -1; } { pModeSetting = tc358743_mode_info_data[frame_rate][mode].init_data_ptr; iModeSettingArySize = tc358743_mode_info_data[frame_rate][mode].init_data_size; tc358743_data.pix.width = tc358743_mode_info_data[frame_rate][mode].width; tc358743_data.pix.height = tc358743_mode_info_data[frame_rate][mode].height; pr_debug("%s: Set %d regs from %p for frs %d mode %d with width %d height %d\n", __func__, iModeSettingArySize, pModeSetting, frame_rate, mode, tc358743_data.pix.width, tc358743_data.pix.height); for (i = 0; i < iModeSettingArySize; ++i) { pModeSetting = tc358743_mode_info_data[frame_rate][mode].init_data_ptr + i; Delay_ms = pModeSetting->u32Delay_ms & (0xffff); RegAddr = pModeSetting->u16RegAddr; Val = pModeSetting->u32Val; Mask = pModeSetting->u32Mask; Length = pModeSetting->u8Length; if (Mask) { retval = tc358743_read_reg(RegAddr, &RegVal); if (retval < 0) break; RegVal &= ~(u8)Mask; Val &= Mask; Val |= RegVal; } retval = tc358743_write_reg(RegAddr, Val, Length); if (retval < 0) break; if (Delay_ms) msleep(Delay_ms); if (0 != ((pModeSetting->u32Delay_ms>>16) & (0xff))) { if (!RepeateTimes) { RepeateTimes = (pModeSetting->u32Delay_ms>>16) & (0xff); RepeateLines = (pModeSetting->u32Delay_ms>>24) & (0xff); } if (--RepeateTimes > 0) { i -= RepeateLines; } } } if (retval < 0) { pr_err("%s: Fail to write REGS to tc35874!\n", __func__); goto err; } } if (!hdmi_mode) // is this during reset if ((retval = tc358743_write_edid(cHDMIEDID, ARRAY_SIZE(cHDMIEDID)))) pr_err("%s: Fail to write EDID to tc35874!\n", __func__); tc358743_toggle_hpd(hpd_active); if (mipi_csi2_info) { unsigned int i = 0; /* wait for mipi sensor ready */ mipi_reg = mipi_csi2_dphy_status(mipi_csi2_info); while ((mipi_reg == 0x200) && (i < 10)) { mipi_reg_test[i] = mipi_reg; mipi_reg = mipi_csi2_dphy_status(mipi_csi2_info); i++; msleep(10); } if (i >= 10) { pr_err("mipi csi2 can not receive sensor clk!\n"); return -1; } { int j; for (j = 0; j < i; j++) { pr_debug("%d mipi csi2 dphy status %x\n", j, mipi_reg_test[j]); } } i = 0; /* wait for mipi stable */ mipi_reg = mipi_csi2_get_error1(mipi_csi2_info); while ((mipi_reg != 0x0) && (i < 10)) { mipi_reg_test[i] = mipi_reg; mipi_reg = mipi_csi2_get_error1(mipi_csi2_info); i++; msleep(10); } if (i >= 10) { pr_err("mipi csi2 can not reveive data correctly!\n"); return -1; } { int j; for (j = 0; j < i; j++) { pr_debug("%d mipi csi2 err1 %x\n", j, mipi_reg_test[j]); } } } err: return (retval>0)?0:retval; } /* --------------- IOCTL functions from v4l2_int_ioctl_desc --------------- */ static int ioctl_g_ifparm(struct v4l2_int_device *s, struct v4l2_ifparm *p) { pr_debug("%s\n", __func__); if (s == NULL) { pr_err(" ERROR!! no slave device set!\n"); return -1; } memset(p, 0, sizeof(*p)); p->u.bt656.clock_curr = TC358743_XCLK_MIN; //tc358743_data.mclk; pr_debug("%s: clock_curr=mclk=%d\n", __func__, tc358743_data.mclk); p->if_type = V4L2_IF_TYPE_BT656; p->u.bt656.mode = V4L2_IF_TYPE_BT656_MODE_NOBT_8BIT; p->u.bt656.clock_min = TC358743_XCLK_MIN; p->u.bt656.clock_max = TC358743_XCLK_MAX; p->u.bt656.bt_sync_correct = 1; /* Indicate external vsync */ return 0; } /*! * ioctl_s_power - V4L2 sensor interface handler for VIDIOC_S_POWER ioctl * @s: pointer to standard V4L2 device structure * @on: indicates power mode (on or off) * * Turns the power on or off, depending on the value of on and returns the * appropriate error code. */ static int ioctl_s_power(struct v4l2_int_device *s, int on) { struct sensor_data *sensor = s->priv; pr_debug("%s: %d\n", __func__, on); if (on && !sensor->on) { if (io_regulator) if (regulator_enable(io_regulator) != 0) return -EIO; if (core_regulator) if (regulator_enable(core_regulator) != 0) return -EIO; if (gpo_regulator) if (regulator_enable(gpo_regulator) != 0) return -EIO; if (analog_regulator) if (regulator_enable(analog_regulator) != 0) return -EIO; /* Make sure power on */ tc_standby(0); } else if (!on && sensor->on) { if (analog_regulator) regulator_disable(analog_regulator); if (core_regulator) regulator_disable(core_regulator); if (io_regulator) regulator_disable(io_regulator); if (gpo_regulator) regulator_disable(gpo_regulator); if (!hdmi_mode) tc358743_reset(sensor); } sensor->on = on; return 0; } /*! * ioctl_g_parm - V4L2 sensor interface handler for VIDIOC_G_PARM ioctl * @s: pointer to standard V4L2 device structure * @a: pointer to standard V4L2 VIDIOC_G_PARM ioctl structure * * Returns the sensor's video CAPTURE parameters. */ static int ioctl_g_parm(struct v4l2_int_device *s, struct v4l2_streamparm *a) { struct sensor_data *sensor = s->priv; struct v4l2_captureparm *cparm = &a->parm.capture; int ret = 0; pr_debug("%s type: %x\n", __func__, a->type); switch (a->type) { /* This is the only case currently handled. */ case V4L2_BUF_TYPE_VIDEO_CAPTURE: memset(a, 0, sizeof(*a)); a->type = V4L2_BUF_TYPE_VIDEO_CAPTURE; cparm->capability = sensor->streamcap.capability; cparm->timeperframe = sensor->streamcap.timeperframe; cparm->capturemode = sensor->streamcap.capturemode; cparm->extendedmode = sensor->streamcap.extendedmode; ret = 0; break; /* These are all the possible cases. */ case V4L2_BUF_TYPE_VIDEO_OUTPUT: case V4L2_BUF_TYPE_VIDEO_OVERLAY: case V4L2_BUF_TYPE_VBI_CAPTURE: case V4L2_BUF_TYPE_VBI_OUTPUT: case V4L2_BUF_TYPE_SLICED_VBI_CAPTURE: case V4L2_BUF_TYPE_SLICED_VBI_OUTPUT: ret = -EINVAL; break; default: pr_debug(" type is unknown - %d\n", a->type); ret = -EINVAL; break; } det_work_enable(1); pr_debug("%s done %d\n", __func__, ret); return ret; } static int tc358743_toggle_hpd(int active) { int ret = 0; if (active) { ret += tc358743_write_reg(0x8544, 0x00, 1); mdelay(500); ret += tc358743_write_reg(0x8544, 0x10, 1); } else { ret += tc358743_write_reg(0x8544, 0x10, 1); mdelay(500); ret += tc358743_write_reg(0x8544, 0x00, 1); } return ret; } /*! * ioctl_s_parm - V4L2 sensor interface handler for VIDIOC_S_PARM ioctl * @s: pointer to standard V4L2 device structure * @a: pointer to standard V4L2 VIDIOC_S_PARM ioctl structure * * Configures the sensor to use the input parameters, if possible. If * not possible, reverts to the old parameters and returns the * appropriate error code. */ static int ioctl_s_parm(struct v4l2_int_device *s, struct v4l2_streamparm *a) { struct sensor_data *sensor = s->priv; struct v4l2_fract *timeperframe = &a->parm.capture.timeperframe; u32 tgt_fps; /* target frames per secound */ enum tc358743_frame_rate frame_rate = tc358743_60_fps, frame_rate_now = tc358743_60_fps; int ret = 0; pr_debug("%s\n", __func__); det_work_enable(0); /* Make sure power on */ tc_standby(0); switch (a->type) { /* This is the only case currently handled. */ case V4L2_BUF_TYPE_VIDEO_CAPTURE: /* Check that the new frame rate is allowed. */ if ((timeperframe->numerator == 0) || (timeperframe->denominator == 0)) { timeperframe->denominator = DEFAULT_FPS; timeperframe->numerator = 1; } tgt_fps = timeperframe->denominator / timeperframe->numerator; if (tgt_fps > MAX_FPS) { timeperframe->denominator = MAX_FPS; timeperframe->numerator = 1; } else if (tgt_fps < MIN_FPS) { timeperframe->denominator = MIN_FPS; timeperframe->numerator = 1; } /* Actual frame rate we use */ tgt_fps = timeperframe->denominator / timeperframe->numerator; if (tgt_fps == 60) frame_rate = tc358743_60_fps; else if (tgt_fps == 30) frame_rate = tc358743_30_fps; else { pr_err(" The camera frame rate is not supported!\n"); ret = -EINVAL; break; } if ((u32)a->parm.capture.capturemode > tc358743_mode_MAX) { a->parm.capture.capturemode = 0; pr_debug("%s: Forse extended mode: %d \n", __func__,(u32)a->parm.capture.capturemode); } tgt_fps = sensor->streamcap.timeperframe.denominator / sensor->streamcap.timeperframe.numerator; if (tgt_fps == 60) frame_rate_now = tc358743_60_fps; else if (tgt_fps == 30) frame_rate_now = tc358743_30_fps; if (frame_rate_now != frame_rate || sensor->streamcap.capturemode != (u32)a->parm.capture.capturemode || sensor->streamcap.extendedmode != (u32)a->parm.capture.extendedmode) { sensor->streamcap.timeperframe = *timeperframe; sensor->streamcap.capturemode = (u32)a->parm.capture.capturemode; sensor->streamcap.extendedmode = (u32)a->parm.capture.extendedmode; pr_debug("%s: capture mode: %d extended mode: %d \n", __func__,sensor->streamcap.capturemode, sensor->streamcap.extendedmode); ret = tc358743_init_mode(frame_rate, sensor->streamcap.capturemode); } else { pr_debug("%s: Keep current settings\n", __func__); } break; /* These are all the possible cases. */ case V4L2_BUF_TYPE_VIDEO_OUTPUT: case V4L2_BUF_TYPE_VIDEO_OVERLAY: case V4L2_BUF_TYPE_VBI_CAPTURE: case V4L2_BUF_TYPE_VBI_OUTPUT: case V4L2_BUF_TYPE_SLICED_VBI_CAPTURE: case V4L2_BUF_TYPE_SLICED_VBI_OUTPUT: pr_debug(" type is not " \ "V4L2_BUF_TYPE_VIDEO_CAPTURE but %d\n", a->type); ret = -EINVAL; break; default: pr_debug(" type is unknown - %d\n", a->type); ret = -EINVAL; break; } if (ret) det_work_enable(1); return ret; } /*! * ioctl_g_ctrl - V4L2 sensor interface handler for VIDIOC_G_CTRL ioctl * @s: pointer to standard V4L2 device structure * @vc: standard V4L2 VIDIOC_G_CTRL ioctl structure * * If the requested control is supported, returns the control's current * value from the video_control[] array. Otherwise, returns -EINVAL * if the control is not supported. */ static int ioctl_g_ctrl(struct v4l2_int_device *s, struct v4l2_control *vc) { int ret = 0; pr_debug("%s\n", __func__); switch (vc->id) { case V4L2_CID_BRIGHTNESS: vc->value = tc358743_data.brightness; break; case V4L2_CID_HUE: vc->value = tc358743_data.hue; break; case V4L2_CID_CONTRAST: vc->value = tc358743_data.contrast; break; case V4L2_CID_SATURATION: vc->value = tc358743_data.saturation; break; case V4L2_CID_RED_BALANCE: vc->value = tc358743_data.red; break; case V4L2_CID_BLUE_BALANCE: vc->value = tc358743_data.blue; break; case V4L2_CID_EXPOSURE: vc->value = tc358743_data.ae_mode; break; default: ret = -EINVAL; } return ret; } /*! * ioctl_s_ctrl - V4L2 sensor interface handler for VIDIOC_S_CTRL ioctl * @s: pointer to standard V4L2 device structure * @vc: standard V4L2 VIDIOC_S_CTRL ioctl structure * * If the requested control is supported, sets the control's current * value in HW (and updates the video_control[] array). Otherwise, * returns -EINVAL if the control is not supported. */ static int ioctl_s_ctrl(struct v4l2_int_device *s, struct v4l2_control *vc) { int retval = 0; pr_debug("In tc358743:ioctl_s_ctrl %d\n", vc->id); switch (vc->id) { case V4L2_CID_BRIGHTNESS: break; case V4L2_CID_CONTRAST: break; case V4L2_CID_SATURATION: break; case V4L2_CID_HUE: break; case V4L2_CID_AUTO_WHITE_BALANCE: break; case V4L2_CID_DO_WHITE_BALANCE: break; case V4L2_CID_RED_BALANCE: break; case V4L2_CID_BLUE_BALANCE: break; case V4L2_CID_GAMMA: break; case V4L2_CID_EXPOSURE: break; case V4L2_CID_AUTOGAIN: break; case V4L2_CID_GAIN: break; case V4L2_CID_HFLIP: break; case V4L2_CID_VFLIP: break; default: retval = -EPERM; break; } return retval; } int get_pixelformat(int index) { int ifmt; for (ifmt = 0; ifmt < ARRAY_SIZE(tc358743_formats); ifmt++) if (tc358743_mode_info_data[0][index].flags == tc358743_formats[ifmt].flags) break; if (ifmt == ARRAY_SIZE(tc358743_formats)) ifmt = 0; /* Default = RBG888 */ return ifmt; } /*! * ioctl_enum_framesizes - V4L2 sensor interface handler for * VIDIOC_ENUM_FRAMESIZES ioctl * @s: pointer to standard V4L2 device structure * @fsize: standard V4L2 VIDIOC_ENUM_FRAMESIZES ioctl structure * * Return 0 if successful, otherwise -EINVAL. */ static int ioctl_enum_framesizes(struct v4l2_int_device *s, struct v4l2_frmsizeenum *fsize) { pr_debug("%s, INDEX: %d\n", __func__,fsize->index); if (fsize->index > tc358743_mode_MAX) return -EINVAL; fsize->pixel_format = tc358743_formats[get_pixelformat(fsize->index)].pixelformat; fsize->discrete.width = tc358743_mode_info_data[0][fsize->index].width; fsize->discrete.height = tc358743_mode_info_data[0][fsize->index].height; pr_debug("%s %d:%d format: %x\n", __func__, fsize->discrete.width, fsize->discrete.height, fsize->pixel_format); return 0; } /*! * ioctl_g_chip_ident - V4L2 sensor interface handler for * VIDIOC_DBG_G_CHIP_IDENT ioctl * @s: pointer to standard V4L2 device structure * @id: pointer to int * * Return 0. */ static int ioctl_g_chip_ident(struct v4l2_int_device *s, int *id) { ((struct v4l2_dbg_chip_ident *)id)->match.type = V4L2_CHIP_MATCH_I2C_DRIVER; strcpy(((struct v4l2_dbg_chip_ident *)id)->match.name, "tc358743_mipi"); return 0; } /*! * ioctl_init - V4L2 sensor interface handler for VIDIOC_INT_INIT * @s: pointer to standard V4L2 device structure */ static int ioctl_init(struct v4l2_int_device *s) { pr_debug("%s\n", __func__); return 0; } /*! * ioctl_enum_fmt_cap - V4L2 sensor interface handler for VIDIOC_ENUM_FMT * @s: pointer to standard V4L2 device structure * @fmt: pointer to standard V4L2 fmt description structure * * Return 0. */ static int ioctl_enum_fmt_cap(struct v4l2_int_device *s, struct v4l2_fmtdesc *fmt) { pr_debug("%s\n", __func__); if (fmt->index > tc358743_mode_MAX) return -EINVAL; fmt->pixelformat = tc358743_formats[get_pixelformat(fmt->index)].pixelformat; pr_debug("%s: format: %x\n", __func__, fmt->pixelformat); return 0; } static int ioctl_try_fmt_cap(struct v4l2_int_device *s, struct v4l2_format *f) { struct sensor_data *sensor = s->priv; u32 tgt_fps; /* target frames per secound */ enum tc358743_frame_rate frame_rate; // enum image_size isize; int ifmt; struct v4l2_pix_format *pix = &f->fmt.pix; pr_debug("%s\n", __func__); tgt_fps = sensor->streamcap.timeperframe.denominator / sensor->streamcap.timeperframe.numerator; if (tgt_fps == 60) { frame_rate = tc358743_60_fps; } else if (tgt_fps == 30) { frame_rate = tc358743_30_fps; } else { pr_debug("%s: %d fps (%d,%d) is not supported\n", __func__, tgt_fps, sensor->streamcap.timeperframe.denominator,sensor->streamcap.timeperframe.numerator); return -EINVAL; } tc358743_data.pix.width = pix->width = tc358743_mode_info_data[frame_rate][sensor->streamcap.capturemode].width; tc358743_data.pix.height = pix->height = tc358743_mode_info_data[frame_rate][sensor->streamcap.capturemode].height; for (ifmt = 0; ifmt < ARRAY_SIZE(tc358743_formats); ifmt++) if (tc358743_mode_info_data[frame_rate][sensor->streamcap.capturemode].flags == tc358743_formats[ifmt].flags) break; if (ifmt == ARRAY_SIZE(tc358743_formats)) ifmt = 0; /* Default = RBG888 */ tc358743_data.pix.pixelformat = pix->pixelformat = tc358743_formats[ifmt].pixelformat; pix->field = V4L2_FIELD_NONE; pix->bytesperline = pix->width * 4; pix->sizeimage = pix->bytesperline * pix->height; pix->priv = 0; switch (pix->pixelformat) { case V4L2_PIX_FMT_UYVY: default: pix->colorspace = V4L2_COLORSPACE_SRGB; break; } { u32 u32val; int ret = tc358743_read_reg(0x8520,&u32val); pr_debug("SYS_STATUS: 0x%x, ret val: %d \n",u32val,ret); ret = tc358743_read_reg(0x8521,&u32val); pr_debug("VI_STATUS0: 0x%x, ret val: %d \n",u32val,ret); ret = tc358743_read_reg(0x8522,&u32val); pr_debug("VI_STATUS1: 0x%x, ret val: %d \n",u32val,ret); ret = tc358743_read_reg(0x8525,&u32val); pr_debug("VI_STATUS2: 0x%x, ret val: %d \n",u32val,ret); ret = tc358743_read_reg(0x8528,&u32val); pr_debug("VI_STATUS3: 0x%x, ret val: %d \n",u32val,ret); pr_debug("%s %d:%d format: %x\n", __func__, pix->width, pix->height, pix->pixelformat); } return 0; } /*! * ioctl_g_fmt_cap - V4L2 sensor interface handler for ioctl_g_fmt_cap * @s: pointer to standard V4L2 device structure * @f: pointer to standard V4L2 v4l2_format structure * * Returns the sensor's current pixel format in the v4l2_format * parameter. */ static int ioctl_g_fmt_cap(struct v4l2_int_device *s, struct v4l2_format *f) { pr_debug("%s\n", __func__); return ioctl_try_fmt_cap(s, f); } /*! * ioctl_dev_init - V4L2 sensor interface handler for vidioc_int_dev_init_num * @s: pointer to standard V4L2 device structure * * Initialise the device when slave attaches to the master. */ static int ioctl_dev_init(struct v4l2_int_device *s) { struct sensor_data *sensor = s->priv; u32 tgt_xclk; /* target xclk */ u32 tgt_fps; /* target frames per secound */ int ret = 0; enum tc358743_frame_rate frame_rate; void *mipi_csi2_info; pr_debug("%s\n", __func__); tc358743_data.on = true; /* mclk */ tgt_xclk = tc358743_data.mclk; tgt_xclk = min(tgt_xclk, (u32)TC358743_XCLK_MAX); tgt_xclk = max(tgt_xclk, (u32)TC358743_XCLK_MIN); tc358743_data.mclk = tgt_xclk; pr_debug("%s: Setting mclk to %d MHz\n", __func__, tc358743_data.mclk / 1000000); // set_mclk_rate(&tc358743_data.mclk, tc358743_data.mclk_source); // pr_debug("%s: After mclk to %d MHz\n", __func__, tc358743_data.mclk / 1000000); /* Default camera frame rate is set in probe */ tgt_fps = sensor->streamcap.timeperframe.denominator / sensor->streamcap.timeperframe.numerator; if (tgt_fps == 60) frame_rate = tc358743_60_fps; else if (tgt_fps == 30) frame_rate = tc358743_30_fps; else return -EINVAL; mipi_csi2_info = mipi_csi2_get_info(); /* enable mipi csi2 */ if (mipi_csi2_info) { mipi_csi2_enable(mipi_csi2_info); } else { pr_err("Fail to get mipi_csi2_info!\n"); return -EPERM; } pr_debug("%s done\n", __func__); return ret; } /*! * ioctl_dev_exit - V4L2 sensor interface handler for vidioc_int_dev_exit_num * @s: pointer to standard V4L2 device structure * * Delinitialise the device when slave detaches to the master. */ static int ioctl_dev_exit(struct v4l2_int_device *s) { void *mipi_csi2_info; mipi_csi2_info = mipi_csi2_get_info(); /* disable mipi csi2 */ if (mipi_csi2_info) if (mipi_csi2_get_status(mipi_csi2_info)) mipi_csi2_disable(mipi_csi2_info); return 0; } /*! * This structure defines all the ioctls for this module and links them to the * enumeration. */ static struct v4l2_int_ioctl_desc tc358743_ioctl_desc[] = { {vidioc_int_dev_init_num, (v4l2_int_ioctl_func*) ioctl_dev_init}, {vidioc_int_dev_exit_num, ioctl_dev_exit}, {vidioc_int_s_power_num, (v4l2_int_ioctl_func*) ioctl_s_power}, {vidioc_int_g_ifparm_num, (v4l2_int_ioctl_func*) ioctl_g_ifparm}, {vidioc_int_init_num, (v4l2_int_ioctl_func*) ioctl_init}, {vidioc_int_enum_fmt_cap_num, (v4l2_int_ioctl_func *) ioctl_enum_fmt_cap}, {vidioc_int_try_fmt_cap_num, (v4l2_int_ioctl_func *)ioctl_try_fmt_cap}, {vidioc_int_g_fmt_cap_num, (v4l2_int_ioctl_func *) ioctl_g_fmt_cap}, {vidioc_int_g_parm_num, (v4l2_int_ioctl_func *) ioctl_g_parm}, {vidioc_int_s_parm_num, (v4l2_int_ioctl_func *) ioctl_s_parm}, {vidioc_int_g_ctrl_num, (v4l2_int_ioctl_func *) ioctl_g_ctrl}, {vidioc_int_s_ctrl_num, (v4l2_int_ioctl_func *) ioctl_s_ctrl}, {vidioc_int_enum_framesizes_num, (v4l2_int_ioctl_func *) ioctl_enum_framesizes}, {vidioc_int_g_chip_ident_num, (v4l2_int_ioctl_func *) ioctl_g_chip_ident}, }; static struct v4l2_int_slave tc358743_slave = { .ioctls = tc358743_ioctl_desc, .num_ioctls = ARRAY_SIZE(tc358743_ioctl_desc), }; static struct v4l2_int_device tc358743_int_device = { .module = THIS_MODULE, .name = "tc358743", .type = v4l2_int_type_slave, .u = { .slave = &tc358743_slave, }, }; #ifdef AUDIO_ENABLE struct imx_ssi { struct platform_device *ac97_dev; struct snd_soc_dai *imx_ac97; struct clk *clk; void __iomem *base; int irq; int fiq_enable; unsigned int offset; unsigned int flags; void (*ac97_reset) (struct snd_ac97 *ac97); void (*ac97_warm_reset)(struct snd_ac97 *ac97); struct imx_pcm_dma_params dma_params_rx; struct imx_pcm_dma_params dma_params_tx; int enabled; struct platform_device *soc_platform_pdev; struct platform_device *soc_platform_pdev_fiq; }; #define SSI_SCR 0x10 #define SSI_SRCR 0x20 #define SSI_STCCR 0x24 #define SSI_SRCCR 0x28 #define SSI_SCR_I2S_MODE_NORM (0 << 5) #define SSI_SCR_I2S_MODE_MSTR (1 << 5) #define SSI_SCR_I2S_MODE_SLAVE (2 << 5) #define SSI_I2S_MODE_MASK (3 << 5) #define SSI_SCR_SYN (1 << 4) #define SSI_SRCR_RSHFD (1 << 4) #define SSI_SRCR_RSCKP (1 << 3) #define SSI_SRCR_RFSI (1 << 2) #define SSI_SRCR_REFS (1 << 0) #define SSI_STCCR_WL(x) ((((x) - 2) >> 1) << 13) #define SSI_STCCR_WL_MASK (0xf << 13) #define SSI_SRCCR_WL(x) ((((x) - 2) >> 1) << 13) #define SSI_SRCCR_WL_MASK (0xf << 13) /* Audio setup */ static int imxpac_tc358743_hw_params(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *params) { struct snd_soc_pcm_runtime *rtd = substream->private_data; struct snd_soc_dai *codec_dai = rtd->codec_dai; struct snd_soc_dai *cpu_dai = rtd->cpu_dai; int ret; ret = snd_soc_dai_set_fmt(cpu_dai, SND_SOC_DAIFMT_I2S | SND_SOC_DAIFMT_NB_IF | SND_SOC_DAIFMT_CBM_CFM); if (ret) { pr_err("%s: failed set cpu dai format\n", __func__); return ret; } ret = snd_soc_dai_set_fmt(codec_dai, SND_SOC_DAIFMT_I2S | SND_SOC_DAIFMT_NB_NF | SND_SOC_DAIFMT_CBM_CFM); if (ret) { pr_err("%s: failed set codec dai format\n", __func__); return ret; } ret = snd_soc_dai_set_sysclk(codec_dai, 0, CODEC_CLOCK, SND_SOC_CLOCK_OUT); if (ret) { pr_err("%s: failed setting codec sysclk\n", __func__); return ret; } snd_soc_dai_set_tdm_slot(cpu_dai, 0xffffffc, 0xffffffc, 2, 0); ret = snd_soc_dai_set_sysclk(cpu_dai, IMX_SSP_SYS_CLK, 0, SND_SOC_CLOCK_IN); if (ret) { pr_err("can't set CPU system clock IMX_SSP_SYS_CLK\n"); return ret; } #if 1 // clear SSI_SRCR_RXBIT0 and SSI_SRCR_RSHFD in order to push Right-justified MSB data fro { struct imx_ssi *ssi = snd_soc_dai_get_drvdata(cpu_dai); u32 scr = 0, srcr = 0, stccr = 0, srccr = 0; pr_debug("%s: base %p\n", __func__, (void *)ssi->base); scr = readl(ssi->base + SSI_SCR); pr_debug("%s: SSI_SCR before: %p\n", __func__, (void *)scr); writel(scr, ssi->base + SSI_SCR); pr_debug("%s: SSI_SCR after: %p\n", __func__, (void *)scr); srcr = readl(ssi->base + SSI_SRCR); pr_debug("%s: SSI_SRCR before: %p\n", __func__, (void *)srcr); writel(srcr, ssi->base + SSI_SRCR); pr_debug("%s: SSI_SRCR after: %p\n", __func__, (void *)srcr); stccr = readl(ssi->base + SSI_STCCR); pr_debug("%s: SSI_STCCR before: %p\n", __func__, (void *)stccr); stccr &= ~SSI_STCCR_WL_MASK; stccr |= SSI_STCCR_WL(16); writel(stccr, ssi->base + SSI_STCCR); pr_debug("%s: SSI_STCCR after: %p\n", __func__, (void *)stccr); srccr = readl(ssi->base + SSI_SRCCR); pr_debug("%s: SSI_SRCCR before: %p\n", __func__, (void *)srccr); srccr &= ~SSI_SRCCR_WL_MASK; srccr |= SSI_SRCCR_WL(16); writel(srccr, ssi->base + SSI_SRCCR); pr_debug("%s: SSI_SRCCR after: %p\n", __func__, (void *)srccr); } #endif return 0; } /* Headphones jack detection DAPM pins */ static struct snd_soc_jack_pin hs_jack_pins_a[] = { }; /* imx_3stack card dapm widgets */ static struct snd_soc_dapm_widget imx_3stack_dapm_widgets_a[] = { }; static struct snd_kcontrol_new tc358743_machine_controls_a[] = { }; /* imx_3stack machine connections to the codec pins */ static struct snd_soc_dapm_route audio_map_a[] = { }; static int imx_3stack_tc358743_init(struct snd_soc_pcm_runtime *rtd) { struct snd_soc_codec *codec = rtd->codec; int ret; struct snd_soc_jack *hs_jack; struct snd_soc_jack_pin *hs_jack_pins; int hs_jack_pins_size; struct snd_soc_dapm_widget *imx_3stack_dapm_widgets; int imx_3stack_dapm_widgets_size; struct snd_kcontrol_new *tc358743_machine_controls; int tc358743_machine_controls_size; struct snd_soc_dapm_route *audio_map; int audio_map_size; int gpio_num = -1; char *gpio_name; pr_debug("%s started\n", __func__); hs_jack_pins = hs_jack_pins_a; hs_jack_pins_size = ARRAY_SIZE(hs_jack_pins_a); imx_3stack_dapm_widgets = imx_3stack_dapm_widgets_a; imx_3stack_dapm_widgets_size = ARRAY_SIZE(imx_3stack_dapm_widgets_a); tc358743_machine_controls = tc358743_machine_controls_a; tc358743_machine_controls_size = ARRAY_SIZE(tc358743_machine_controls_a); audio_map = audio_map_a; audio_map_size = ARRAY_SIZE(audio_map_a); gpio_num = -1; //card_a_gpio_num; gpio_name = NULL; ret = snd_soc_add_controls(codec, tc358743_machine_controls, tc358743_machine_controls_size); if (ret) { pr_err("%s: snd_soc_add_controls failed. err = %d\n", __func__, ret); return ret; } /* Add imx_3stack specific widgets */ snd_soc_dapm_new_controls(&codec->dapm, imx_3stack_dapm_widgets, imx_3stack_dapm_widgets_size); /* Set up imx_3stack specific audio path audio_map */ snd_soc_dapm_add_routes(&codec->dapm, audio_map, audio_map_size); snd_soc_dapm_enable_pin(&codec->dapm, hs_jack_pins->pin); snd_soc_dapm_sync(&codec->dapm); hs_jack = kzalloc(sizeof(struct snd_soc_jack), GFP_KERNEL); ret = snd_soc_jack_new(codec, hs_jack_pins->pin, SND_JACK_HEADPHONE, hs_jack); if (ret) { pr_err("%s: snd_soc_jack_new failed. err = %d\n", __func__, ret); return ret; } ret = snd_soc_jack_add_pins(hs_jack,hs_jack_pins_size, hs_jack_pins); if (ret) { pr_err("%s: snd_soc_jack_add_pinsfailed. err = %d\n", __func__, ret); return ret; } return 0; } static struct snd_soc_ops imxpac_tc358743_snd_ops = { .hw_params = imxpac_tc358743_hw_params, }; static struct snd_soc_dai_link imxpac_tc358743_dai = { .name = "tc358743", .stream_name = "TC358743", .codec_dai_name = "tc358743-hifi", .platform_name = "imx-pcm-audio.2", .codec_name = "tc358743_mipi.1-000f", .cpu_dai_name = "imx-ssi.2", .init = imx_3stack_tc358743_init, .ops = &imxpac_tc358743_snd_ops, }; static struct snd_soc_card imxpac_tc358743 = { .name = "cpuimx-audio_hdmi_in", .dai_link = &imxpac_tc358743_dai, .num_links = 1, }; static struct platform_device *imxpac_tc358743_snd_device; static struct platform_device *imxpac_tc358743_snd_device; static int imx_audmux_config(int slave, int master) { unsigned int ptcr, pdcr; slave = slave - 1; master = master - 1; /* SSI0 mastered by port 5 */ ptcr = MXC_AUDMUX_V2_PTCR_SYN | MXC_AUDMUX_V2_PTCR_TFSDIR | MXC_AUDMUX_V2_PTCR_TFSEL(master | 0x8) | MXC_AUDMUX_V2_PTCR_TCLKDIR | MXC_AUDMUX_V2_PTCR_RFSDIR | MXC_AUDMUX_V2_PTCR_RFSEL(master | 0x8) | MXC_AUDMUX_V2_PTCR_RCLKDIR | MXC_AUDMUX_V2_PTCR_RCSEL(master | 0x8) | MXC_AUDMUX_V2_PTCR_TCSEL(master | 0x8); pdcr = MXC_AUDMUX_V2_PDCR_RXDSEL(master); mxc_audmux_v2_configure_port(slave, ptcr, pdcr); ptcr = MXC_AUDMUX_V2_PTCR_SYN; pdcr = MXC_AUDMUX_V2_PDCR_RXDSEL(master); mxc_audmux_v2_configure_port(master, ptcr, pdcr); return 0; } static int __devinit imx_tc358743_probe(struct platform_device *pdev) { struct mxc_audio_platform_data *plat = pdev->dev.platform_data; int ret = 0; imx_audmux_config(plat->src_port, plat->ext_port); ret = -EINVAL; if (plat->init && plat->init()) return ret; printk("%s %d %s\n",__func__,__LINE__,pdev->name); return 0; } static int imx_tc358743_remove(struct platform_device *pdev) { struct mxc_audio_platform_data *plat = pdev->dev.platform_data; if (plat->finit) plat->finit(); return 0; } static struct platform_driver imx_tc358743_audio1_driver = { .probe = imx_tc358743_probe, .remove = imx_tc358743_remove, .driver = { .name = "imx-tc358743", }, }; /* Codec setup */ static int tc358743_codec_probe(struct snd_soc_codec *codec) { return 0; } static int tc358743_codec_remove(struct snd_soc_codec *codec) { return 0; } static int tc358743_codec_suspend(struct snd_soc_codec *codec, pm_message_t state) { // tc358743_set_bias_level(codec, SND_SOC_BIAS_OFF); return 0; } static int tc358743_codec_resume(struct snd_soc_codec *codec) { // tc358743_set_bias_level(codec, SND_SOC_BIAS_STANDBY); return 0; } static int tc358743_set_bias_level(struct snd_soc_codec *codec, enum snd_soc_bias_level level) { return 0; } static const u8 tc358743_reg[0] = { }; static struct snd_soc_codec_driver soc_codec_dev_tc358743 = { .set_bias_level = tc358743_set_bias_level, .reg_cache_size = ARRAY_SIZE(tc358743_reg), .reg_word_size = sizeof(u8), .reg_cache_default = tc358743_reg, .probe = tc358743_codec_probe, .remove = tc358743_codec_remove, .suspend = tc358743_codec_suspend, .resume = tc358743_codec_resume, }; #define AIC3X_RATES SNDRV_PCM_RATE_8000_96000 #define AIC3X_FORMATS (SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_S20_3LE | \ SNDRV_PCM_FMTBIT_S24_LE) static int tc358743_hw_params(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *params, struct snd_soc_dai *dai) { return 0; } static int tc358743_mute(struct snd_soc_dai *dai, int mute) { return 0; } static int tc358743_set_dai_sysclk(struct snd_soc_dai *codec_dai, int clk_id, unsigned int freq, int dir) { return 0; } static int tc358743_set_dai_fmt(struct snd_soc_dai *codec_dai, unsigned int fmt) { return 0; } static struct snd_soc_dai_ops tc358743_dai_ops = { .hw_params = tc358743_hw_params, .digital_mute = tc358743_mute, .set_sysclk = tc358743_set_dai_sysclk, .set_fmt = tc358743_set_dai_fmt, }; static struct snd_soc_dai_driver tc358743_dai = { .name = "tc358743-hifi", .capture = { .stream_name = "Capture", .channels_min = 1, .channels_max = 2, .rates = AIC3X_RATES, .formats = AIC3X_FORMATS,}, .ops = &tc358743_dai_ops, .symmetric_rates = 1, }; #endif static char tc358743_mode_list[16][12] = { "None", "VGA", "240p/480i", "288p/576i", "W240p/480i", "W288p/576i", "480p", "576p", "W480p", "W576p", "WW480p", "WW576p", "720p", "1035i", "1080i", "1080p" }; static char tc358743_fps_list[tc358743_max_fps+1] = { [tc358743_60_fps] = 60, [tc358743_30_fps] = 30, [tc358743_max_fps] = 0 }; static int tc358743_audio_list[16] = { 44100, 0, 48000, 32000, 22050, 384000, 24000, 352800, 88200, 768000, 96000, 705600, 176400, 0, 192000, 0 }; static char str_on[80]; static void report_netlink(void) { char *envp[2]; envp[0] = &str_on[0]; envp[1] = NULL; sprintf(envp[0], "HDMI RX: %d (%s) %d %d", (unsigned char)hdmi_mode & 0xf, tc358743_mode_list[(unsigned char)hdmi_mode & 0xf], tc358743_fps_list[fps], tc358743_audio_list[audio]); kobject_uevent_env(&(tc358743_data.i2c_client->dev.kobj), KOBJ_CHANGE, envp); det_work_timeout = DET_WORK_TIMEOUT_DEFAULT; pr_debug("%s: HDMI RX (%d) mode: %s fps: %d (%d, %d) audio: %d\n", __func__, (unsigned char)hdmi_mode, tc358743_mode_list[(unsigned char)hdmi_mode & 0xf], fps, bounce, det_work_timeout, tc358743_audio_list[audio]); } static void det_worker(struct work_struct *work) { u32 u32val; u16 reg; int ret; mutex_lock(&access_lock); if (!det_work_disable) { reg = 0x8621; ret = tc358743_read_reg(reg, &u32val); if (ret > 0) { if (audio != (((unsigned char)u32val) & 0x0f)) { audio = ((unsigned char)u32val) & 0x0f; report_netlink(); } } reg = 0x852f; ret = tc358743_read_reg(reg, &u32val); if (ret > 0) { while (1) { if (u32val & TC3587430_HDMI_DETECT) { lock = u32val & TC3587430_HDMI_DETECT; reg = 0x8521; ret = tc358743_read_reg(reg, &u32val); if (ret < 0) { pr_err("%s: Error reading mode\n", __func__); } } else { if (lock) { // check if it is realy un-plug lock = 0; u32val = 0x0; hdmi_mode = 0xF0; // fake mode to detect un-plug if mode was not detected before. } } if ((unsigned char)hdmi_mode != (unsigned char)u32val) { if (u32val) det_work_timeout = DET_WORK_TIMEOUT_DEFERRED; else det_work_timeout = DET_WORK_TIMEOUT_DEFAULT; bounce = MAX_BOUNCE; pr_debug("%s: HDMI RX (%d != %d) mode: %s fps: %d (%d, %d)\n", __func__, (unsigned char)hdmi_mode, (unsigned char)u32val, tc358743_mode_list[(unsigned char)hdmi_mode & 0xf], fps, bounce, det_work_timeout); hdmi_mode = u32val; } else if (bounce) { bounce--; det_work_timeout = DET_WORK_TIMEOUT_DEFAULT; } if (1 == bounce) { if (hdmi_mode >= 0xe) { reg = 0x852f; ret = tc358743_read_reg(reg, &u32val); if (ret > 0) fps = ((((unsigned char)u32val) & 0x0f) > 0xa)? tc358743_60_fps: tc358743_30_fps; } reg = 0x8621; ret = tc358743_read_reg(reg, &u32val); if (ret > 0) { audio = ((unsigned char)u32val) & 0x0f; report_netlink(); } } break; } } else { pr_err("%s: Error reading lock\n", __func__); } } else { det_work_timeout = DET_WORK_TIMEOUT_DEFERRED; } mutex_unlock(&access_lock); schedule_delayed_work(&(det_work), msecs_to_jiffies(det_work_timeout)); } static irqreturn_t tc358743_detect_handler(int irq, void *data) { pr_debug("%s: IRQ %d\n", __func__, tc358743_data.i2c_client->irq); schedule_delayed_work(&(det_work), msecs_to_jiffies(det_work_timeout)); return IRQ_HANDLED; } /*! * tc358743 I2C probe function * * @param adapter struct i2c_adapter * * @return Error code indicating success or failure */ #define DUMP_LENGTH 256 static u16 regoffs = 0; static ssize_t tc358743_show_regdump(struct device *dev, struct device_attribute *attr, char *buf) { int i, len = 0; int retval; u32 u32val; mutex_lock(&access_lock); for (i=0; i<DUMP_LENGTH; ) { retval = tc358743_read_reg(regoffs+i, &u32val); if (retval < 0) { u32val =0xff; retval = 1; } while (retval-- > 0) { if (0 == (i & 0xf)) len += sprintf(buf+len, "\n%04X:", regoffs+i); len += sprintf(buf+len, " %02X", u32val&0xff); u32val >>= 8; i++; } } mutex_unlock(&access_lock); len += sprintf(buf+len, "\n"); return len; } static DEVICE_ATTR(regdump, S_IRUGO, tc358743_show_regdump, NULL); static ssize_t tc358743_store_regoffs(struct device *device, struct device_attribute *attr, const char *buf, size_t count) { u32 val; int retval; retval = sscanf(buf, "%x", &val); if (1 == retval) regoffs = (u16)val; return count; } static ssize_t tc358743_show_regoffs(struct device *dev, struct device_attribute *attr, char *buf) { int len = 0; len += sprintf(buf+len, "0x%04X\n", regoffs); return len; } static DEVICE_ATTR(regoffs, S_IRUGO|S_IWUSR, tc358743_show_regoffs, tc358743_store_regoffs); static ssize_t tc358743_store_hpd(struct device *device, struct device_attribute *attr, const char *buf, size_t count) { u32 val; int retval; retval = sscanf(buf, "%d", &val); if (1 == retval) hpd_active = (u16)val; return count; } static ssize_t tc358743_show_hpd(struct device *dev, struct device_attribute *attr, char *buf) { int len = 0; len += sprintf(buf+len, "%d\n", hpd_active); return len; } static DEVICE_ATTR(hpd, S_IRUGO|S_IWUSR, tc358743_show_hpd, tc358743_store_hpd); static ssize_t tc358743_show_hdmirx(struct device *dev, struct device_attribute *attr, char *buf) { int len = 0; len += sprintf(buf+len, "%d\n", hdmi_mode); return len; } static DEVICE_ATTR(hdmirx, S_IRUGO, tc358743_show_hdmirx, NULL); static ssize_t tc358743_show_fps(struct device *dev, struct device_attribute *attr, char *buf) { int len = 0; len += sprintf(buf+len, "%d\n", tc358743_fps_list[fps]); return len; } static DEVICE_ATTR(fps, S_IRUGO, tc358743_show_fps, NULL); #ifdef AUDIO_ENABLE static ssize_t tc358743_show_audio(struct device *dev, struct device_attribute *attr, char *buf) { int len = 0; len += sprintf(buf+len, "%d\n", tc358743_audio_list[audio]); return len; } static DEVICE_ATTR(audio, S_IRUGO, tc358743_show_audio, NULL); #endif static int tc358743_probe(struct i2c_client *client, const struct i2c_device_id *id) { struct pwm_device *pwm; struct device *dev = &client->dev; int retval; struct regmap *gpr; struct sensor_data *sensor = &tc358743_data; u32 u32val; /* request power down pin */ pwn_gpio = of_get_named_gpio(dev->of_node, "pwn-gpios", 0); if (!gpio_is_valid(pwn_gpio)) { dev_warn(dev, "no sensor pwdn pin available"); } else { retval = devm_gpio_request_one(dev, pwn_gpio, GPIOF_OUT_INIT_HIGH, "tc_mipi_pwdn"); if (retval < 0) { dev_warn(dev, "request of pwn_gpio failed"); return retval; } } /* request reset pin */ rst_gpio = of_get_named_gpio(dev->of_node, "rst-gpios", 0); if (!gpio_is_valid(rst_gpio)) { dev_warn(dev, "no sensor reset pin available"); return -EINVAL; } retval = devm_gpio_request_one(dev, rst_gpio, GPIOF_OUT_INIT_HIGH, "tc_mipi_reset"); if (retval < 0) { dev_warn(dev, "request of tc_mipi_reset failed"); return retval; } /* Set initial values for the sensor struct. */ memset(sensor, 0, sizeof(*sensor)); sensor->sensor_clk = devm_clk_get(dev, "csi_mclk"); if (IS_ERR(sensor->sensor_clk)) { /* assuming clock enabled by default */ sensor->sensor_clk = NULL; dev_err(dev, "clock-frequency missing or invalid\n"); return PTR_ERR(sensor->sensor_clk); } retval = of_property_read_u32(dev->of_node, "mclk", &(sensor->mclk)); if (retval) { dev_err(dev, "mclk missing or invalid\n"); return retval; } retval = of_property_read_u32(dev->of_node, "mclk_source", (u32 *) &(sensor->mclk_source)); if (retval) { dev_err(dev, "mclk_source missing or invalid\n"); return retval; } retval = of_property_read_u32(dev->of_node, "ipu_id", &sensor->ipu_id); if (retval) { dev_err(dev, "ipu_id missing or invalid\n"); return retval; } retval = of_property_read_u32(dev->of_node, "csi_id", &(sensor->csi)); if (retval) { dev_err(dev, "csi id missing or invalid\n"); return retval; } if (((unsigned)sensor->ipu_id > 1) || ((unsigned)sensor->csi > 1)) { dev_err(dev, "invalid ipu/csi\n"); return -EINVAL; } clk_prepare_enable(sensor->sensor_clk); sensor->io_init = tc_reset; sensor->i2c_client = client; sensor->pix.pixelformat = tc358743_formats[0].pixelformat; sensor->streamcap.capability = V4L2_MODE_HIGHQUALITY | V4L2_CAP_TIMEPERFRAME; sensor->streamcap.capturemode = 0; sensor->streamcap.extendedmode = tc358743_mode_1080P_1920_1080; sensor->streamcap.timeperframe.denominator = DEFAULT_FPS; sensor->streamcap.timeperframe.numerator = 1; sensor->pix.width = tc358743_mode_info_data[0][sensor->streamcap.capturemode].width; sensor->pix.height = tc358743_mode_info_data[0][sensor->streamcap.capturemode].height; pr_debug("%s: format: %x, capture mode: %d extended mode: %d fps: %d width: %d height: %d\n",__func__, sensor->pix.pixelformat, sensor->streamcap.capturemode, sensor->streamcap.extendedmode, sensor->streamcap.timeperframe.denominator * sensor->streamcap.timeperframe.numerator, sensor->pix.width, sensor->pix.height); pwm = pwm_get(dev, NULL); if (!IS_ERR(pwm)) { dev_info(dev, "found pwm%d, period=%d\n", pwm->pwm, pwm->period); pwm_config(pwm, pwm->period >> 1, pwm->period); pwm_enable(pwm); } tc_power_on(dev); tc_reset(); tc_standby(0); retval = tc358743_read_reg(TC358743_CHIP_ID_HIGH_BYTE, &u32val); if (retval < 0) { pr_err("%s:cannot find camera\n", __func__); retval = -ENODEV; goto err4; } gpr = syscon_regmap_lookup_by_compatible("fsl,imx6q-iomuxc-gpr"); if (!IS_ERR(gpr)) { if (of_machine_is_compatible("fsl,imx6q")) { if (sensor->csi == sensor->ipu_id) { int mask = sensor->csi ? (1 << 20) : (1 << 19); regmap_update_bits(gpr, IOMUXC_GPR1, mask, 0); } } else if (of_machine_is_compatible("fsl,imx6dl")) { int mask = sensor->csi ? (7 << 3) : (7 << 0); int val = sensor->csi ? (3 << 3) : (0 << 0); if (sensor->ipu_id) { dev_err(dev, "invalid ipu\n"); return -EINVAL; } regmap_update_bits(gpr, IOMUXC_GPR13, mask, val); } } else { pr_err("%s: failed to find fsl,imx6q-iomux-gpr regmap\n", __func__); } tc358743_int_device.priv = sensor; //retval = device_create_file(&client->dev, &dev_attr_audio); retval = device_create_file(&client->dev, &dev_attr_fps); retval = device_create_file(&client->dev, &dev_attr_hdmirx); retval = device_create_file(&client->dev, &dev_attr_hpd); retval = device_create_file(&client->dev, &dev_attr_regoffs); retval = device_create_file(&client->dev, &dev_attr_regdump); if (retval) { pr_err("%s: create bin file failed, error=%d\n", __func__, retval); goto err4; } #ifdef AUDIO_ENABLE /* Audio setup */ retval = snd_soc_register_codec(&client->dev, &soc_codec_dev_tc358743, &tc358743_dai, 1); if (retval) { pr_err("%s: register failed, error=%d\n", __func__, retval); goto err4; } retval = platform_driver_register(&imx_tc358743_audio1_driver); if (retval) { pr_err("%s: Platform driver register failed, error=%d\n", __func__, retval); goto err4; } imxpac_tc358743_snd_device = platform_device_alloc("soc-audio", 5); if (!imxpac_tc358743_snd_device) { pr_err("%s: Platform device allocation failed, error=%d\n", __func__, retval); goto err4; } platform_set_drvdata(imxpac_tc358743_snd_device, &imxpac_tc358743); retval = platform_device_add(imxpac_tc358743_snd_device); if (retval) { pr_err("%s: Platform device add failed, error=%d\n", __func__, retval); platform_device_put(imxpac_tc358743_snd_device); goto err4; } #endif #if 1 INIT_DELAYED_WORK(&(det_work), det_worker); if (sensor->i2c_client->irq) { retval = request_irq(sensor->i2c_client->irq, tc358743_detect_handler, IRQF_SHARED | IRQF_TRIGGER_FALLING, "tc358743_det", sensor); if (retval < 0) dev_warn(&sensor->i2c_client->dev, "cound not request det irq %d\n", sensor->i2c_client->irq); } schedule_delayed_work(&(det_work), msecs_to_jiffies(det_work_timeout)); #endif retval = tc358743_reset(sensor); tc_standby(1); retval = v4l2_int_device_register(&tc358743_int_device); if (retval) { pr_err("%s: v4l2_int_device_register failed, error=%d\n", __func__, retval); goto err4; } pr_debug("%s: finished, error=%d\n", __func__, retval); return retval; err4: pr_err("%s: failed, error=%d\n", __func__, retval); return retval; } /*! * tc358743 I2C detach function * * @param client struct i2c_client * * @return Error code indicating success or failure */ static int tc358743_remove(struct i2c_client *client) { // Stop delayed work cancel_delayed_work_sync(&(det_work)); // Remove IRQ if (tc358743_data.i2c_client->irq) { free_irq(tc358743_data.i2c_client->irq, &tc358743_data); } /*Remove sysfs entries*/ device_remove_file(&client->dev, &dev_attr_fps); device_remove_file(&client->dev, &dev_attr_hdmirx); device_remove_file(&client->dev, &dev_attr_hpd); device_remove_file(&client->dev, &dev_attr_regoffs); device_remove_file(&client->dev, &dev_attr_regdump); v4l2_int_device_unregister(&tc358743_int_device); if (gpo_regulator) { regulator_disable(gpo_regulator); regulator_put(gpo_regulator); } if (analog_regulator) { regulator_disable(analog_regulator); regulator_put(analog_regulator); } if (core_regulator) { regulator_disable(core_regulator); regulator_put(core_regulator); } if (io_regulator) { regulator_disable(io_regulator); regulator_put(io_regulator); } return 0; } /*! * tc358743 init function * Called by insmod tc358743_camera.ko. * * @return Error code indicating success or failure */ static __init int tc358743_init(void) { int err; err = i2c_add_driver(&tc358743_i2c_driver); if (err != 0) pr_err("%s:driver registration failed, error=%d\n", __func__, err); return err; } /*! * tc358743 cleanup function * Called on rmmod tc358743_camera.ko * * @return Error code indicating success or failure */ static void __exit tc358743_clean(void) { i2c_del_driver(&tc358743_i2c_driver); } module_init(tc358743_init); module_exit(tc358743_clean); MODULE_AUTHOR("Panasonic Avionics Corp."); MODULE_DESCRIPTION("Toshiba TC358743 HDMI-to-CSI2 Bridge MIPI Input Driver"); MODULE_LICENSE("GPL"); MODULE_VERSION("1.0"); MODULE_ALIAS("CSI");
captivo/linux-captivo
drivers/media/platform/mxc/capture/tc358743_h2c.c
C
gpl-2.0
111,500
/* * vhost-vdpa * * Copyright(c) 2017-2018 Intel Corporation. * Copyright(c) 2020 Red Hat, Inc. * * This work is licensed under the terms of the GNU GPL, version 2 or later. * See the COPYING file in the top-level directory. * */ #include "qemu/osdep.h" #include <linux/vhost.h> #include <linux/vfio.h> #include <sys/eventfd.h> #include <sys/ioctl.h> #include "hw/virtio/vhost.h" #include "hw/virtio/vhost-backend.h" #include "hw/virtio/virtio-net.h" #include "hw/virtio/vhost-vdpa.h" #include "qemu/main-loop.h" #include "cpu.h" static bool vhost_vdpa_listener_skipped_section(MemoryRegionSection *section) { return (!memory_region_is_ram(section->mr) && !memory_region_is_iommu(section->mr)) || /* * Sizing an enabled 64-bit BAR can cause spurious mappings to * addresses in the upper part of the 64-bit address space. These * are never accessed by the CPU and beyond the address width of * some IOMMU hardware. TODO: VDPA should tell us the IOMMU width. */ section->offset_within_address_space & (1ULL << 63); } static int vhost_vdpa_dma_map(struct vhost_vdpa *v, hwaddr iova, hwaddr size, void *vaddr, bool readonly) { struct vhost_msg_v2 msg = {}; int fd = v->device_fd; int ret = 0; msg.type = v->msg_type; msg.iotlb.iova = iova; msg.iotlb.size = size; msg.iotlb.uaddr = (uint64_t)(uintptr_t)vaddr; msg.iotlb.perm = readonly ? VHOST_ACCESS_RO : VHOST_ACCESS_RW; msg.iotlb.type = VHOST_IOTLB_UPDATE; if (write(fd, &msg, sizeof(msg)) != sizeof(msg)) { error_report("failed to write, fd=%d, errno=%d (%s)", fd, errno, strerror(errno)); return -EIO ; } return ret; } static int vhost_vdpa_dma_unmap(struct vhost_vdpa *v, hwaddr iova, hwaddr size) { struct vhost_msg_v2 msg = {}; int fd = v->device_fd; int ret = 0; msg.type = v->msg_type; msg.iotlb.iova = iova; msg.iotlb.size = size; msg.iotlb.type = VHOST_IOTLB_INVALIDATE; if (write(fd, &msg, sizeof(msg)) != sizeof(msg)) { error_report("failed to write, fd=%d, errno=%d (%s)", fd, errno, strerror(errno)); return -EIO ; } return ret; } static void vhost_vdpa_listener_region_add(MemoryListener *listener, MemoryRegionSection *section) { struct vhost_vdpa *v = container_of(listener, struct vhost_vdpa, listener); hwaddr iova; Int128 llend, llsize; void *vaddr; int ret; if (vhost_vdpa_listener_skipped_section(section)) { return; } if (unlikely((section->offset_within_address_space & ~TARGET_PAGE_MASK) != (section->offset_within_region & ~TARGET_PAGE_MASK))) { error_report("%s received unaligned region", __func__); return; } iova = TARGET_PAGE_ALIGN(section->offset_within_address_space); llend = int128_make64(section->offset_within_address_space); llend = int128_add(llend, section->size); llend = int128_and(llend, int128_exts64(TARGET_PAGE_MASK)); if (int128_ge(int128_make64(iova), llend)) { return; } memory_region_ref(section->mr); /* Here we assume that memory_region_is_ram(section->mr)==true */ vaddr = memory_region_get_ram_ptr(section->mr) + section->offset_within_region + (iova - section->offset_within_address_space); llsize = int128_sub(llend, int128_make64(iova)); ret = vhost_vdpa_dma_map(v, iova, int128_get64(llsize), vaddr, section->readonly); if (ret) { error_report("vhost vdpa map fail!"); if (memory_region_is_ram_device(section->mr)) { /* Allow unexpected mappings not to be fatal for RAM devices */ error_report("map ram fail!"); return ; } goto fail; } return; fail: if (memory_region_is_ram_device(section->mr)) { error_report("failed to vdpa_dma_map. pci p2p may not work"); return; } /* * On the initfn path, store the first error in the container so we * can gracefully fail. Runtime, there's not much we can do other * than throw a hardware error. */ error_report("vhost-vdpa: DMA mapping failed, unable to continue"); return; } static void vhost_vdpa_listener_region_del(MemoryListener *listener, MemoryRegionSection *section) { struct vhost_vdpa *v = container_of(listener, struct vhost_vdpa, listener); hwaddr iova; Int128 llend, llsize; int ret; bool try_unmap = true; if (vhost_vdpa_listener_skipped_section(section)) { return; } if (unlikely((section->offset_within_address_space & ~TARGET_PAGE_MASK) != (section->offset_within_region & ~TARGET_PAGE_MASK))) { error_report("%s received unaligned region", __func__); return; } iova = TARGET_PAGE_ALIGN(section->offset_within_address_space); llend = int128_make64(section->offset_within_address_space); llend = int128_add(llend, section->size); llend = int128_and(llend, int128_exts64(TARGET_PAGE_MASK)); if (int128_ge(int128_make64(iova), llend)) { return; } llsize = int128_sub(llend, int128_make64(iova)); if (try_unmap) { ret = vhost_vdpa_dma_unmap(v, iova, int128_get64(llsize)); if (ret) { error_report("vhost_vdpa dma unmap error!"); } } memory_region_unref(section->mr); } /* * IOTLB API is used by vhost-vpda which requires incremental updating * of the mapping. So we can not use generic vhost memory listener which * depends on the addnop(). */ static const MemoryListener vhost_vdpa_memory_listener = { .region_add = vhost_vdpa_listener_region_add, .region_del = vhost_vdpa_listener_region_del, }; static int vhost_vdpa_call(struct vhost_dev *dev, unsigned long int request, void *arg) { struct vhost_vdpa *v = dev->opaque; int fd = v->device_fd; assert(dev->vhost_ops->backend_type == VHOST_BACKEND_TYPE_VDPA); return ioctl(fd, request, arg); } static void vhost_vdpa_add_status(struct vhost_dev *dev, uint8_t status) { uint8_t s; if (vhost_vdpa_call(dev, VHOST_VDPA_GET_STATUS, &s)) { return; } s |= status; vhost_vdpa_call(dev, VHOST_VDPA_SET_STATUS, &s); } static int vhost_vdpa_init(struct vhost_dev *dev, void *opaque) { struct vhost_vdpa *v; uint64_t features; assert(dev->vhost_ops->backend_type == VHOST_BACKEND_TYPE_VDPA); v = opaque; dev->opaque = opaque ; vhost_vdpa_call(dev, VHOST_GET_FEATURES, &features); dev->backend_features = features; v->listener = vhost_vdpa_memory_listener; v->msg_type = VHOST_IOTLB_MSG_V2; vhost_vdpa_add_status(dev, VIRTIO_CONFIG_S_ACKNOWLEDGE | VIRTIO_CONFIG_S_DRIVER); return 0; } static int vhost_vdpa_cleanup(struct vhost_dev *dev) { struct vhost_vdpa *v; assert(dev->vhost_ops->backend_type == VHOST_BACKEND_TYPE_VDPA); v = dev->opaque; memory_listener_unregister(&v->listener); dev->opaque = NULL; return 0; } static int vhost_vdpa_memslots_limit(struct vhost_dev *dev) { return INT_MAX; } static int vhost_vdpa_set_mem_table(struct vhost_dev *dev, struct vhost_memory *mem) { if (mem->padding) { return -1; } return 0; } static int vhost_vdpa_set_features(struct vhost_dev *dev, uint64_t features) { int ret; ret = vhost_vdpa_call(dev, VHOST_SET_FEATURES, &features); uint8_t status = 0; if (ret) { return ret; } vhost_vdpa_add_status(dev, VIRTIO_CONFIG_S_FEATURES_OK); vhost_vdpa_call(dev, VHOST_VDPA_GET_STATUS, &status); return !(status & VIRTIO_CONFIG_S_FEATURES_OK); } int vhost_vdpa_get_device_id(struct vhost_dev *dev, uint32_t *device_id) { return vhost_vdpa_call(dev, VHOST_VDPA_GET_DEVICE_ID, device_id); } static int vhost_vdpa_reset_device(struct vhost_dev *dev) { uint8_t status = 0; return vhost_vdpa_call(dev, VHOST_VDPA_SET_STATUS, &status); } static int vhost_vdpa_get_vq_index(struct vhost_dev *dev, int idx) { assert(idx >= dev->vq_index && idx < dev->vq_index + dev->nvqs); return idx - dev->vq_index; } static int vhost_vdpa_set_vring_ready(struct vhost_dev *dev) { int i; for (i = 0; i < dev->nvqs; ++i) { struct vhost_vring_state state = { .index = dev->vq_index + i, .num = 1, }; vhost_vdpa_call(dev, VHOST_VDPA_SET_VRING_ENABLE, &state); } return 0; } static int vhost_vdpa_set_config(struct vhost_dev *dev, const uint8_t *data, uint32_t offset, uint32_t size, uint32_t flags) { struct vhost_vdpa_config *config; int ret; unsigned long config_size = offsetof(struct vhost_vdpa_config, buf); config = g_malloc(size + config_size); if (config == NULL) { return -1; } config->off = offset; config->len = size; memcpy(config->buf, data, size); ret = vhost_vdpa_call(dev, VHOST_VDPA_SET_CONFIG, config); g_free(config); return ret; } static int vhost_vdpa_get_config(struct vhost_dev *dev, uint8_t *config, uint32_t config_len) { struct vhost_vdpa_config *v_config; unsigned long config_size = offsetof(struct vhost_vdpa_config, buf); int ret; v_config = g_malloc(config_len + config_size); if (v_config == NULL) { return -1; } v_config->len = config_len; v_config->off = 0; ret = vhost_vdpa_call(dev, VHOST_VDPA_GET_CONFIG, v_config); memcpy(config, v_config->buf, config_len); g_free(v_config); return ret; } static int vhost_vdpa_dev_start(struct vhost_dev *dev, bool started) { struct vhost_vdpa *v = dev->opaque; if (started) { uint8_t status = 0; memory_listener_register(&v->listener, &address_space_memory); vhost_vdpa_set_vring_ready(dev); vhost_vdpa_add_status(dev, VIRTIO_CONFIG_S_DRIVER_OK); vhost_vdpa_call(dev, VHOST_VDPA_GET_STATUS, &status); return !(status & VIRTIO_CONFIG_S_DRIVER_OK); } else { vhost_vdpa_reset_device(dev); vhost_vdpa_add_status(dev, VIRTIO_CONFIG_S_ACKNOWLEDGE | VIRTIO_CONFIG_S_DRIVER); memory_listener_unregister(&v->listener); return 0; } } static int vhost_vdpa_set_log_base(struct vhost_dev *dev, uint64_t base, struct vhost_log *log) { return vhost_vdpa_call(dev, VHOST_SET_LOG_BASE, &base); } static int vhost_vdpa_set_vring_addr(struct vhost_dev *dev, struct vhost_vring_addr *addr) { return vhost_vdpa_call(dev, VHOST_SET_VRING_ADDR, addr); } static int vhost_vdpa_set_vring_num(struct vhost_dev *dev, struct vhost_vring_state *ring) { return vhost_vdpa_call(dev, VHOST_SET_VRING_NUM, ring); } static int vhost_vdpa_set_vring_base(struct vhost_dev *dev, struct vhost_vring_state *ring) { return vhost_vdpa_call(dev, VHOST_SET_VRING_BASE, ring); } static int vhost_vdpa_get_vring_base(struct vhost_dev *dev, struct vhost_vring_state *ring) { return vhost_vdpa_call(dev, VHOST_GET_VRING_BASE, ring); } static int vhost_vdpa_set_vring_kick(struct vhost_dev *dev, struct vhost_vring_file *file) { return vhost_vdpa_call(dev, VHOST_SET_VRING_KICK, file); } static int vhost_vdpa_set_vring_call(struct vhost_dev *dev, struct vhost_vring_file *file) { return vhost_vdpa_call(dev, VHOST_SET_VRING_CALL, file); } static int vhost_vdpa_get_features(struct vhost_dev *dev, uint64_t *features) { return vhost_vdpa_call(dev, VHOST_GET_FEATURES, features); } static int vhost_vdpa_set_owner(struct vhost_dev *dev) { return vhost_vdpa_call(dev, VHOST_SET_OWNER, NULL); } static int vhost_vdpa_vq_get_addr(struct vhost_dev *dev, struct vhost_vring_addr *addr, struct vhost_virtqueue *vq) { assert(dev->vhost_ops->backend_type == VHOST_BACKEND_TYPE_VDPA); addr->desc_user_addr = (uint64_t)(unsigned long)vq->desc_phys; addr->avail_user_addr = (uint64_t)(unsigned long)vq->avail_phys; addr->used_user_addr = (uint64_t)(unsigned long)vq->used_phys; return 0; } static bool vhost_vdpa_force_iommu(struct vhost_dev *dev) { return true; } const VhostOps vdpa_ops = { .backend_type = VHOST_BACKEND_TYPE_VDPA, .vhost_backend_init = vhost_vdpa_init, .vhost_backend_cleanup = vhost_vdpa_cleanup, .vhost_set_log_base = vhost_vdpa_set_log_base, .vhost_set_vring_addr = vhost_vdpa_set_vring_addr, .vhost_set_vring_num = vhost_vdpa_set_vring_num, .vhost_set_vring_base = vhost_vdpa_set_vring_base, .vhost_get_vring_base = vhost_vdpa_get_vring_base, .vhost_set_vring_kick = vhost_vdpa_set_vring_kick, .vhost_set_vring_call = vhost_vdpa_set_vring_call, .vhost_get_features = vhost_vdpa_get_features, .vhost_set_owner = vhost_vdpa_set_owner, .vhost_set_vring_endian = NULL, .vhost_backend_memslots_limit = vhost_vdpa_memslots_limit, .vhost_set_mem_table = vhost_vdpa_set_mem_table, .vhost_set_features = vhost_vdpa_set_features, .vhost_reset_device = vhost_vdpa_reset_device, .vhost_get_vq_index = vhost_vdpa_get_vq_index, .vhost_get_config = vhost_vdpa_get_config, .vhost_set_config = vhost_vdpa_set_config, .vhost_requires_shm_log = NULL, .vhost_migration_done = NULL, .vhost_backend_can_merge = NULL, .vhost_net_set_mtu = NULL, .vhost_set_iotlb_callback = NULL, .vhost_send_device_iotlb_msg = NULL, .vhost_dev_start = vhost_vdpa_dev_start, .vhost_get_device_id = vhost_vdpa_get_device_id, .vhost_vq_get_addr = vhost_vdpa_vq_get_addr, .vhost_force_iommu = vhost_vdpa_force_iommu, };
dslutz/qemu
hw/virtio/vhost-vdpa.c
C
gpl-2.0
14,501
/* * * Copyright (C) 2009 Texas Instruments Inc * * 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. * * This program 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 this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <linux/module.h> #include <linux/init.h> #include <linux/kernel.h> #include <linux/slab.h> #include <linux/fs.h> #include <linux/errno.h> #include <linux/types.h> #include <linux/cdev.h> #include <linux/interrupt.h> #include <linux/dma-mapping.h> #include <linux/uaccess.h> #include <linux/platform_device.h> #include <linux/major.h> #include <media/davinci/dm365_a3_hw.h> #include <media/davinci/vpss.h> /* Global structure */ static struct class *aew_class; struct aew_device *aew_dev_configptr; struct device *aewdev; /* device structure to make entry in device*/ static dev_t dev; /* For registeration of charatcer device*/ static struct cdev c_dev; int aew_validate_parameters(void) { int result = 0; /* Check horizontal Count */ if ((aew_dev_configptr->config->window_config.hz_cnt < AEW_WINDOW_HORIZONTAL_COUNT_MIN) || (aew_dev_configptr->config->window_config.hz_cnt > AEW_WINDOW_HORIZONTAL_COUNT_MAX)) { dev_err(aewdev, "\n Horizontal Count is incorrect"); result = -EINVAL; } /* Check Vertical Count */ if ((aew_dev_configptr->config->window_config.vt_cnt < AEW_WINDOW_VERTICAL_COUNT_MIN) || (aew_dev_configptr->config->window_config.vt_cnt > AEW_WINDOW_VERTICAL_COUNT_MAX)) { dev_err(aewdev, "\n Vertical Count is incorrect"); result = -EINVAL; } /* Check line increment */ if ((NOT_EVEN == CHECK_EVEN(aew_dev_configptr->config->window_config. hz_line_incr)) || (aew_dev_configptr->config->window_config.hz_line_incr < AEW_HZ_LINEINCR_MIN) || (aew_dev_configptr->config->window_config.hz_line_incr > AEW_HZ_LINEINCR_MAX)) { dev_err(aewdev, "\n Invalid Parameters"); dev_err(aewdev, "\n Horizontal Line Increment is incorrect"); result = -EINVAL; } /* Check line increment */ if ((NOT_EVEN == CHECK_EVEN(aew_dev_configptr->config->window_config. vt_line_incr)) || (aew_dev_configptr->config->window_config.vt_line_incr < AEW_VT_LINEINCR_MIN) || (aew_dev_configptr->config->window_config.vt_line_incr > AEW_VT_LINEINCR_MAX)) { dev_err(aewdev, "\n Invalid Parameters"); dev_err(aewdev, "\n Vertical Line Increment is incorrect"); result = -EINVAL; } /* Check width */ if ((NOT_EVEN == CHECK_EVEN(aew_dev_configptr->config->window_config.width)) || (aew_dev_configptr->config->window_config.width < AEW_WIDTH_MIN) || (aew_dev_configptr->config->window_config.width > AEW_WIDTH_MAX)) { dev_err(aewdev, "\n Width is incorrect"); result = -EINVAL; } /* Check Height */ if ((NOT_EVEN == CHECK_EVEN(aew_dev_configptr->config->window_config.height)) || (aew_dev_configptr->config->window_config.height < AEW_HEIGHT_MIN) || (aew_dev_configptr->config->window_config.height > AEW_HEIGHT_MAX)) { dev_err(aewdev, "\n height incorrect"); result = -EINVAL; } /* Check Horizontal Start */ if ((aew_dev_configptr->config->window_config.hz_start < AEW_HZSTART_MIN) || (aew_dev_configptr->config->window_config.hz_start > AEW_HZSTART_MAX)) { dev_err(aewdev, "\n horizontal start is incorrect"); result = -EINVAL; } if ((aew_dev_configptr->config->window_config.vt_start > AEW_VTSTART_MAX)) { dev_err(aewdev, "\n Vertical start is incorrect"); result = -EINVAL; } if ((aew_dev_configptr->config->alaw_enable > H3A_AEW_ENABLE) || (aew_dev_configptr->config->alaw_enable < H3A_AEW_DISABLE)) { dev_err(aewdev, "\n A Law setting is incorrect"); result = -EINVAL; } if (aew_dev_configptr->config->saturation_limit > AEW_AVELMT_MAX) { dev_err(aewdev, "\n Saturation Limit is incorrect"); result = -EINVAL; } /* Check Black Window Height */ if (NOT_EVEN == CHECK_EVEN(aew_dev_configptr->config->blackwindow_config.height) || (aew_dev_configptr->config->blackwindow_config.height < AEW_BLKWINHEIGHT_MIN) || (aew_dev_configptr->config->blackwindow_config.height > AEW_BLKWINHEIGHT_MAX)) { dev_err(aewdev, "\n Black Window height incorrect"); result = -EINVAL; } /* Check Black Window Height */ if ((NOT_EVEN == CHECK_EVEN(aew_dev_configptr->config->blackwindow_config. height)) || (aew_dev_configptr->config->blackwindow_config.vt_start < AEW_BLKWINVTSTART_MIN) || (aew_dev_configptr->config->blackwindow_config.vt_start > AEW_BLKWINVTSTART_MAX)) { dev_err(aewdev, "\n Black Window vertical Start is incorrect"); result = -EINVAL; } if (aew_dev_configptr->config->out_format < AEW_OUT_SUM_OF_SQUARES || aew_dev_configptr->config->out_format > AEW_OUT_SUM_ONLY) { dev_err(aewdev, "\n Invalid out_format"); result = -EINVAL; } if (aew_dev_configptr->config->sum_shift > AEW_SUMSHIFT_MAX) { dev_err(aewdev, "\n sum_shift param is invalid, max = %d", AEW_SUMSHIFT_MAX); result = -EINVAL; } return result; } /* inline function to free reserver pages */ inline void aew_free_pages(unsigned long addr, unsigned long bufsize) { unsigned long tempaddr; unsigned long size; tempaddr = addr; if (!addr) return; size = PAGE_SIZE << (get_order(bufsize)); while (size > 0) { ClearPageReserved(virt_to_page(addr)); addr += PAGE_SIZE; size -= PAGE_SIZE; } free_pages(tempaddr, get_order(bufsize)); } /* Function to perform hardware Configuration */ int aew_hardware_setup(void) { int result; /* Size for buffer in bytes */ int buff_size = 0; unsigned long adr; unsigned long size; unsigned int busyaew; /* Get the value of PCR register */ busyaew = aew_get_hw_state(); /* If H3A Engine is busy then return */ if (busyaew == 1) { dev_err(aewdev, "\n Error : AEW Engine is busy"); return -EBUSY; } result = aew_validate_parameters(); dev_dbg(aewdev, "Result = %d\n", result); if (result < 0) { dev_err(aewdev, "Error : Parameters are incorrect \n"); return result; } /* Deallocate the previously allocated buffers */ if (aew_dev_configptr->buff_old) aew_free_pages((unsigned long)aew_dev_configptr->buff_old, aew_dev_configptr->size_window); if (aew_dev_configptr->buff_curr) aew_free_pages((unsigned long)aew_dev_configptr-> buff_curr, aew_dev_configptr->size_window); if (aew_dev_configptr->buff_app) aew_free_pages((unsigned long)aew_dev_configptr-> buff_app, aew_dev_configptr->size_window); /* * Allocat the buffers as per the new buffer size * Allocate memory for old buffer */ if (aew_dev_configptr->config->out_format == AEW_OUT_SUM_ONLY) buff_size = (aew_dev_configptr->config->window_config.hz_cnt) * (aew_dev_configptr->config->window_config.vt_cnt) * AEW_WINDOW_SIZE_SUM_ONLY; else buff_size = (aew_dev_configptr->config->window_config.hz_cnt) * (aew_dev_configptr->config->window_config.vt_cnt) * AEW_WINDOW_SIZE; aew_dev_configptr->buff_old = (void *)__get_free_pages(GFP_KERNEL | GFP_DMA, get_order(buff_size)); if (aew_dev_configptr->buff_old == NULL) return -ENOMEM; /* Make pges reserved so that they will be swapped out */ adr = (unsigned long)aew_dev_configptr->buff_old; size = PAGE_SIZE << (get_order(buff_size)); while (size > 0) { /* * make sure the frame buffers * are never swapped out of memory */ SetPageReserved(virt_to_page(adr)); adr += PAGE_SIZE; size -= PAGE_SIZE; } /* Allocate memory for current buffer */ aew_dev_configptr->buff_curr = (void *)__get_free_pages(GFP_KERNEL | GFP_DMA, get_order(buff_size)); if (aew_dev_configptr->buff_curr == NULL) { /*Free all buffer that are allocated */ if (aew_dev_configptr->buff_old) aew_free_pages((unsigned long)aew_dev_configptr-> buff_old, buff_size); return -ENOMEM; } /* Make pges reserved so that they will be swapped out */ adr = (unsigned long)aew_dev_configptr->buff_curr; size = PAGE_SIZE << (get_order(buff_size)); while (size > 0) { /* * make sure the frame buffers * are never swapped out of memory */ SetPageReserved(virt_to_page(adr)); adr += PAGE_SIZE; size -= PAGE_SIZE; } /* Allocate memory for application buffer */ aew_dev_configptr->buff_app = (void *)__get_free_pages(GFP_KERNEL | GFP_DMA, get_order(buff_size)); if (aew_dev_configptr->buff_app == NULL) { /* Free all buffer that were allocated previously */ if (aew_dev_configptr->buff_old) aew_free_pages((unsigned long)aew_dev_configptr-> buff_old, buff_size); if (aew_dev_configptr->buff_curr) aew_free_pages((unsigned long)aew_dev_configptr-> buff_curr, buff_size); return -ENOMEM; } /* Make pages reserved so that they will be swapped out */ adr = (unsigned long)aew_dev_configptr->buff_app; size = PAGE_SIZE << (get_order(buff_size)); while (size > 0) { /* * make sure the frame buffers * are never swapped out of memory */ SetPageReserved(virt_to_page(adr)); adr += PAGE_SIZE; size -= PAGE_SIZE; } /* Set the registers */ aew_register_setup(aewdev, aew_dev_configptr); aew_dev_configptr->size_window = buff_size; aew_dev_configptr->aew_config = H3A_AEW_CONFIG; return 0; } /* This Function is called when driver is opened */ static int aew_open(struct inode *inode, struct file *filp) { /* Return if Device is in use (Single Channel Support is provided) */ if (aew_dev_configptr->in_use == AEW_IN_USE) return -EBUSY; /* Set the aew_dev_configptr structure */ aew_dev_configptr->config = NULL; /* Allocate memory for configuration structure of this channel */ aew_dev_configptr->config = (struct aew_configuration *) kmalloc(sizeof(struct aew_configuration), GFP_KERNEL); if (aew_dev_configptr->config == NULL) { dev_err(aewdev, "Error : Kmalloc fail\n"); return -ENOMEM; } /* Initiaze the wait queue */ init_waitqueue_head(&(aew_dev_configptr->aew_wait_queue)); /* Device is in use */ aew_dev_configptr->in_use = AEW_IN_USE; /* No Hardware Set up done */ aew_dev_configptr->aew_config = H3A_AEW_CONFIG_NOT_DONE; /* No statistics are available */ aew_dev_configptr->buffer_filled = 0; /* Set Window Size to 0 */ aew_dev_configptr->size_window = 0; /* Initialize the mutex */ mutex_init(&(aew_dev_configptr->read_blocked)); return 0; } static void aew_platform_release(struct device *device) { /* This is called when the reference count goes to zero */ } static int aew_probe(struct device *device) { aewdev = device; return 0; } static int aew_remove(struct device *device) { return 0; } /* This Function is called when driver is closed */ static int aew_release(struct inode *inode, struct file *filp) { aew_engine_setup(aewdev, 0); /* The Application has closed device so device is not in use */ aew_dev_configptr->in_use = AEW_NOT_IN_USE; /* Release memory for configuration structure of this channel */ kfree(aew_dev_configptr->config); /* Free Old Buffer */ if (aew_dev_configptr->buff_old) aew_free_pages((unsigned long)aew_dev_configptr->buff_old, aew_dev_configptr->size_window); /* Free Current Buffer */ if (aew_dev_configptr->buff_curr) aew_free_pages((unsigned long)aew_dev_configptr-> buff_curr, aew_dev_configptr->size_window); /* Free Application Buffer */ if (aew_dev_configptr->buff_app) aew_free_pages((unsigned long)aew_dev_configptr->buff_app, aew_dev_configptr->size_window); aew_dev_configptr->buff_old = NULL; aew_dev_configptr->buff_curr = NULL; aew_dev_configptr->config = NULL; aew_dev_configptr->buff_app = NULL; return 0; } /* * This function will process IOCTL commands sent by the application and * control the devices IO operations. */ static int aew_ioctl(struct inode *inode, struct file *filep, unsigned int cmd, unsigned long arg) { /* Stores Previous Configurations */ struct aew_configuration aewconfig = *(aew_dev_configptr->config); int result = 0; /* Decrement the semaphore */ result = mutex_lock_interruptible(&aew_dev_configptr->read_blocked); if (result) return result; /* * Extract the type and number bitfields, and don't decode wrong cmds: * verify the magic number */ if (_IOC_TYPE(cmd) != AEW_MAGIC_NO) { mutex_unlock(&aew_dev_configptr->read_blocked); return -ENOTTY; } /* verify the command number */ if (_IOC_NR(cmd) > AEW_IOC_MAXNR) { /* Release mutex in case of fault */ mutex_unlock(&aew_dev_configptr->read_blocked); return -ENOTTY; } /* check for the permission of the operation */ if (_IOC_DIR(cmd) & _IOC_READ) result = !access_ok(VERIFY_WRITE, (void __user *)arg, _IOC_SIZE(cmd)); else if (_IOC_DIR(cmd) & _IOC_WRITE) result = !access_ok(VERIFY_READ, (void __user *)arg, _IOC_SIZE(cmd)); if (result) { /* Release mutex in case of fault */ mutex_unlock(&aew_dev_configptr->read_blocked); return -EFAULT; } /* Switch according to IOCTL command */ switch (cmd) { /* * This ioctl is used to perform hardware set up * and will set all the registers for AF engine */ case AEW_S_PARAM: /* Copy config structure passed by user */ if (copy_from_user(aew_dev_configptr->config, (struct aew_configuration *)arg, sizeof(struct aew_configuration))) { *(aew_dev_configptr->config) = aewconfig; mutex_unlock(&aew_dev_configptr->read_blocked); return -EFAULT; } /* Call aew_hardware_setup to perform register configuration */ result = aew_hardware_setup(); if (!result) { /* * Hardware Set up is successful * Return the no of bytes required for buffer */ result = aew_dev_configptr->size_window; } else { /* Change Configuration Structure to original */ *(aew_dev_configptr->config) = aewconfig; dev_err(aewdev, "Error : AEW_S_PARAM failed\n"); } break; /* This ioctl is used to return parameters in user space */ case AEW_G_PARAM: if (aew_dev_configptr->aew_config == H3A_AEW_CONFIG) { if (copy_to_user ((struct aew_configuration *)arg, aew_dev_configptr->config, sizeof(struct aew_configuration))) { mutex_unlock(&aew_dev_configptr->read_blocked); return -EFAULT; } else result = aew_dev_configptr->size_window; } else { dev_err(aewdev, "Error : AEW Hardware is not configured.\n"); result = -EINVAL; } break; /* This ioctl is used to enable AEW Engine */ case AEW_ENABLE: /* Enable AEW Engine if Hardware set up is done */ if (aew_dev_configptr->aew_config == H3A_AEW_CONFIG_NOT_DONE) { dev_err(aewdev, "Error : AEW Hardware is not configured.\n"); result = -EINVAL; } else /* Enable AF Engine */ aew_engine_setup(aewdev, 1); break; /* This ioctl is used to disable AEW Engine */ case AEW_DISABLE: /* Disable AEW Engine */ aew_engine_setup(aewdev, 0); break; /* Invalid Command */ default: dev_err(aewdev, "Error: It should not come here!!\n"); result = -ENOTTY; break; } /* Release the mutex */ mutex_unlock(&aew_dev_configptr->read_blocked); return result; } /* This function will return statistics to user */ static ssize_t aew_read(struct file *filep, char *kbuff, size_t size, loff_t *offset) { void *buffer_temp; int result = 0; int ret; /* Semaphore will return immediately if read call is busy */ ret = mutex_trylock(&(aew_dev_configptr->read_blocked)); if (!ret) { dev_dbg(aewdev, "Read Call : busy : %d\n", ret); return -EBUSY; } /* First Check the size given by user */ if (size < aew_dev_configptr->size_window) { /* * Return Failure to applicaiton * if size is less than required size */ dev_dbg(aewdev, "Error : Invalid size of buffer\n"); mutex_unlock(&(aew_dev_configptr->read_blocked)); return -EINVAL; } /* * The value of buffer_filled flag determines * the status of statistics */ if (aew_dev_configptr->buffer_filled == 0) { /* Decrement the semaphore */ dev_dbg(aewdev, "READ CALL IS BLOCKED............\n"); /* Block the read call */ wait_event_interruptible_timeout(aew_dev_configptr-> aew_wait_queue, aew_dev_configptr-> buffer_filled, AEW_TIMEOUT); dev_dbg(aewdev, "Read Call is unbloked and waking up.......\n"); dev_dbg(aewdev, "Buffer Filled.... %d\n", aew_dev_configptr->buffer_filled); } if (aew_dev_configptr->buffer_filled == 1) { /* Disable the interrupts and then swap the buffers */ dev_dbg(aewdev, "READING............\n"); disable_irq(6); /* New Statistics are availaible */ aew_dev_configptr->buffer_filled = 0; /* Swap application buffer and old buffer */ buffer_temp = aew_dev_configptr->buff_old; aew_dev_configptr->buff_old = aew_dev_configptr->buff_app; aew_dev_configptr->buff_app = buffer_temp; /* Interrupts are enabled */ enable_irq(6); /* * Copy the entire statistics located in application * buffer to user space */ if (copy_to_user(kbuff, aew_dev_configptr->buff_app, aew_dev_configptr->size_window)) { dev_err(aewdev, "Error : Read Fault\n"); mutex_unlock(&(aew_dev_configptr->read_blocked)); return -EFAULT; } else result = aew_dev_configptr->size_window; dev_dbg(aewdev, "Reading Done........................\n"); } dev_dbg(aewdev, "APP BUFF VALUE %x\n", (*((unsigned int *)(aew_dev_configptr->buff_app)))); /* release the mutex */ mutex_unlock(&(aew_dev_configptr->read_blocked)); return result; } /* This function will handle interrupt generated by H3A Engine. */ static irqreturn_t aew_isr(int irq, void *dev_id) { /* EN AF Bit */ unsigned int enaew; /* Temporary Buffer for Swapping */ void *buffer_temp; /* Get the value of PCR register */ enaew = aew_get_enable(); /* If AEW engine is not enabled, interrupt is not for AEW */ if (!enaew) return IRQ_RETVAL(IRQ_NONE); /* * Interrupt is generated by AEW, so Service the Interrupt * Swap current buffer and old buffer */ if (aew_dev_configptr) { buffer_temp = aew_dev_configptr->buff_curr; aew_dev_configptr->buff_curr = aew_dev_configptr->buff_old; aew_dev_configptr->buff_old = buffer_temp; /* Set the AEWBUFSTAT REgister to current buffer Address */ aew_set_address(aewdev, (unsigned long)(virt_to_phys(aew_dev_configptr->buff_curr))); /* * Set buffer filled flag to indicate statistics are available */ aew_dev_configptr->buffer_filled = 1; /* new statistics are available. Wake up the read call */ wake_up(&(aew_dev_configptr->aew_wait_queue)); return IRQ_RETVAL(IRQ_HANDLED); } return IRQ_RETVAL(IRQ_NONE); } /* file Operation Structure*/ static const struct file_operations aew_fops = { .owner = THIS_MODULE, .open = aew_open, .read = aew_read, .ioctl = aew_ioctl, .release = aew_release, }; static struct platform_device aewdevice = { .name = "dm365_aew", .id = 2, .dev = { .release = aew_platform_release, } }; static struct device_driver aew_driver = { .name = "dm365_aew", .bus = &platform_bus_type, .probe = aew_probe, .remove = aew_remove, }; #define DRIVERNAME "DM365AEW" /* Function to register the AF character device driver. */ int __init aew_init(void) { int err; int result = 0; /* * Register the driver in the kernel * dynmically get the major number for the driver using * alloc_chrdev_region function */ result = alloc_chrdev_region(&dev, 0, 1, DRIVERNAME); if (result < 0) { printk(KERN_ERR "Error : Could not register character device"); return -ENODEV; } printk(KERN_INFO "aew major#: %d, minor# %d\n", MAJOR(dev), MINOR(dev)); /* allocate memory for device structure and initialize it with 0 */ aew_dev_configptr = kmalloc(sizeof(struct aew_device), GFP_KERNEL); if (!aew_dev_configptr) { printk(KERN_ERR "Error : kmalloc fail"); unregister_chrdev_region(dev, AEW_NR_DEVS); return -ENOMEM; } /* Initialize character device */ cdev_init(&c_dev, &aew_fops); c_dev.owner = THIS_MODULE; c_dev.ops = &aew_fops; err = cdev_add(&c_dev, dev, 1); if (err) { printk(KERN_ERR "Error : Error in Adding Davinci AEW"); unregister_chrdev_region(dev, AEW_NR_DEVS); kfree(aew_dev_configptr); return -err; } /* register driver as a platform driver */ if (driver_register(&aew_driver) != 0) { unregister_chrdev_region(dev, 1); cdev_del(&c_dev); return -EINVAL; } /* Register the drive as a platform device */ if (platform_device_register(&aewdevice) != 0) { driver_unregister(&aew_driver); unregister_chrdev_region(dev, 1); cdev_del(&c_dev); return -EINVAL; } aew_class = class_create(THIS_MODULE, "dm365_aew"); if (!aew_class) { printk(KERN_ERR "aew_init: error in creating device class\n"); driver_unregister(&aew_driver); platform_device_unregister(&aewdevice); unregister_chrdev_region(dev, 1); unregister_chrdev(MAJOR(dev), DRIVERNAME); cdev_del(&c_dev); return -EINVAL; } device_create(aew_class, NULL, dev, NULL, "dm365_aew"); /* Set up the Interrupt handler for H3AINT interrupt */ result = request_irq(6, aew_isr, IRQF_SHARED, "dm365_h3a_aew", (void *)aew_dev_configptr); if (result != 0) { printk(KERN_ERR "Error : Request IRQ Failed"); unregister_chrdev_region(dev, AEW_NR_DEVS); device_destroy(aew_class, dev); class_destroy(aew_class); kfree(aew_dev_configptr); driver_unregister(&aew_driver); platform_device_unregister(&aewdevice); cdev_del(&c_dev); return result; } /* Initialize device structure */ memset(aew_dev_configptr, 0, sizeof(struct aew_device)); aew_dev_configptr->in_use = AEW_NOT_IN_USE; aew_dev_configptr->buffer_filled = 0; printk(KERN_NOTICE "AEW Driver initialized\n"); return 0; } /* * This Function is called by the kernel while unloading the driver * This will unregister the Character Device Driver */ void __exit aew_cleanup(void) { /* Device is in use */ if (aew_dev_configptr->in_use == AEW_IN_USE) { printk(KERN_ERR "Error : Driver in use"); return; } free_irq(6, aew_dev_configptr); /* Free device structure */ kfree(aew_dev_configptr); aew_dev_configptr = NULL; unregister_chrdev_region(dev, AEW_NR_DEVS); driver_unregister(&aew_driver); device_destroy(aew_class, dev); class_destroy(aew_class); platform_device_unregister(&aewdevice); cdev_del(&c_dev); /* unregistering the driver from the kernel */ unregister_chrdev(MAJOR(dev), DRIVERNAME); } module_init(aew_init) module_exit(aew_cleanup) MODULE_LICENSE("GPL");
merlinholland/kernel
drivers/media/video/davinci/dm365_aew.c
C
gpl-2.0
22,941
/* * COM1 NS16550 support * originally from linux source (arch/ppc/boot/ns16550.c) * modified to use CONFIG_SYS_ISA_MEM and new defines */ #include <config.h> #include <ns16550.h> #define LCRVAL LCR_8N1 /* 8 data, 1 stop, no parity */ #define MCRVAL (MCR_DTR | MCR_RTS) /* RTS/DTR */ #define FCRVAL (FCR_FIFO_EN | FCR_RXSR | FCR_TXSR) /* Clear & enable FIFOs */ void NS16550_init (NS16550_t com_port, int baud_divisor) { com_port->ier = 0x00; #ifdef CONFIG_OMAP com_port->mdr1 = 0x7; /* mode select reset TL16C750*/ #endif com_port->lcr = LCR_BKSE | LCRVAL; com_port->dll = 0; com_port->dlm = 0; com_port->lcr = LCRVAL; com_port->mcr = MCRVAL; com_port->fcr = FCRVAL; com_port->lcr = LCR_BKSE | LCRVAL; com_port->dll = baud_divisor & 0xff; com_port->dlm = (baud_divisor >> 8) & 0xff; com_port->lcr = LCRVAL; #if defined(CONFIG_OMAP) #if defined(CONFIG_APTIX) com_port->mdr1 = 3; /* /13 mode so Aptix 6MHz can hit 115200 */ #else com_port->mdr1 = 0; /* /16 is proper to hit 115200 with 48MHz */ #endif #endif /* CONFIG_OMAP */ } #ifndef CONFIG_NS16550_MIN_FUNCTIONS void NS16550_reinit (NS16550_t com_port, int baud_divisor) { com_port->ier = 0x00; com_port->lcr = LCR_BKSE | LCRVAL; com_port->dll = 0; com_port->dlm = 0; com_port->lcr = LCRVAL; com_port->mcr = MCRVAL; com_port->fcr = FCRVAL; com_port->lcr = LCR_BKSE; com_port->dll = baud_divisor & 0xff; com_port->dlm = (baud_divisor >> 8) & 0xff; com_port->lcr = LCRVAL; } #endif /* CONFIG_NS16550_MIN_FUNCTIONS */ void NS16550_putc (NS16550_t com_port, char c) { while ((com_port->lsr & LSR_THRE) == 0); com_port->thr = c; } #ifndef CONFIG_NS16550_MIN_FUNCTIONS char NS16550_getc (NS16550_t com_port) { while ((com_port->lsr & LSR_DR) == 0) { #ifdef CONFIG_USB_TTY extern void usbtty_poll(void); usbtty_poll(); #endif } return (com_port->rbr); } int NS16550_tstc (NS16550_t com_port) { return ((com_port->lsr & LSR_DR) != 0); } #endif /* CONFIG_NS16550_MIN_FUNCTIONS */
diverger/uboot-lpc32xx
drivers/serial/ns16550.c
C
gpl-2.0
1,977
/* * ProFTPD - mod_sftp RFC4716 keystore * Copyright (c) 2008-2016 TJ Saunders * * 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. * * This program 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 this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Suite 500, Boston, MA 02110-1335, USA. * * As a special exemption, TJ Saunders and other respective copyright holders * give permission to link this program with OpenSSL, and distribute the * resulting executable, without including the source code for OpenSSL in the * source distribution. */ #include "mod_sftp.h" #include "keys.h" #include "keystore.h" #include "crypto.h" #include "rfc4716.h" /* File-based keystore implementation */ struct filestore_key { /* Supported headers. We don't really care about the Comment header * at the moment. */ const char *subject; /* Key data */ unsigned char *key_data; uint32_t key_datalen; }; struct filestore_data { pr_fh_t *fh; const char *path; unsigned int lineno; }; static const char *trace_channel = "ssh2"; /* This getline() function is quite similar to pr_fsio_getline(), except * that it a) enforces the 72-byte max line length from RFC4716, and b) * properly handles lines ending with CR, LF, or CRLF. * * Technically it allows one more byte than necessary, since the worst case * is 74 bytes (72 + CRLF); this also means 73 + CR or 73 + LF. The extra * byte is for the terminating NUL. */ static char *filestore_getline(sftp_keystore_t *store, pool *p) { char linebuf[75], *line = "", *res; struct filestore_data *store_data = store->keystore_data; while (TRUE) { size_t linelen; pr_signals_handle(); memset(&linebuf, '\0', sizeof(linebuf)); res = pr_fsio_gets(linebuf, sizeof(linebuf) - 1, store_data->fh); if (res == NULL) { if (errno == EINTR) { continue; } pr_trace_msg(trace_channel, 10, "reached end of '%s', no matching " "key found", store_data->path); errno = EOF; return NULL; } linelen = strlen(linebuf); if (linelen >= 1) { if (linebuf[linelen - 1] == '\r' || linebuf[linelen - 1] == '\n') { char *tmp; unsigned int header_taglen, header_valuelen; int have_line_continuation = FALSE; store_data->lineno++; linebuf[linelen - 1] = '\0'; line = pstrcat(p, line, linebuf, NULL); if (line[strlen(line) - 1] == '\\') { have_line_continuation = TRUE; line[strlen(line) - 1] = '\0'; } tmp = strchr(line, ':'); if (tmp == NULL) { return line; } /* We have a header. Make sure the header tag is not longer than * the specified length of 64 bytes, and that the header value is * not longer than 1024 bytes. */ header_taglen = tmp - line; if (header_taglen > 64) { (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION, "header tag too long (%u) on line %u of '%s'", header_taglen, store_data->lineno, store_data->path); errno = EINVAL; return NULL; } /* Header value starts at 2 after the ':' (one for the mandatory * space character. */ header_valuelen = strlen(line) - (header_taglen + 2); if (header_valuelen > 1024) { (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION, "header value too long (%u) on line %u of '%s'", header_valuelen, store_data->lineno, store_data->path); errno = EINVAL; return NULL; } if (!have_line_continuation) { return line; } continue; } else if (linelen >= 2 && linebuf[linelen - 2] == '\r' && linebuf[linelen - 1] == '\n') { char *tmp; unsigned int header_taglen, header_valuelen; int have_line_continuation = FALSE; store_data->lineno++; linebuf[linelen - 2] = '\0'; linebuf[linelen - 1] = '\0'; line = pstrcat(p, line, linebuf, NULL); if (line[strlen(line) - 1] == '\\') { have_line_continuation = TRUE; line[strlen(line) - 1] = '\0'; } tmp = strchr(line, ':'); if (tmp == NULL) { return line; } /* We have a header. Make sure the header tag is not longer than * the specified length of 64 bytes, and that the header value is * not longer than 1024 bytes. */ header_taglen = tmp - line; if (header_taglen > 64) { (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION, "header tag too long (%u) on line %u of '%s'", header_taglen, store_data->lineno, store_data->path); errno = EINVAL; return NULL; } /* Header value starts at 2 after the ':' (one for the mandatory * space character. */ header_valuelen = strlen(line) - (header_taglen + 2); if (header_valuelen > 1024) { (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION, "header value too long (%u) on line %u of '%s'", header_valuelen, store_data->lineno, store_data->path); errno = EINVAL; return NULL; } if (!have_line_continuation) { return line; } continue; } else if (linelen < sizeof(linebuf)) { /* No CR or LF terminator; maybe a badly formatted file? Try to * work with the data, if we can. */ line = pstrcat(p, line, linebuf, NULL); return line; } else { (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION, "line too long (%lu) on line %u of '%s'", (unsigned long) linelen, store_data->lineno, store_data->path); (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION, "Make sure that '%s' is a RFC4716 formatted key", store_data->path); errno = EINVAL; break; } } } return NULL; } static struct filestore_key *filestore_get_key(sftp_keystore_t *store, pool *p) { char *line; BIO *bio = NULL; struct filestore_key *key = NULL; struct filestore_data *store_data = store->keystore_data; size_t begin_markerlen = 0, end_markerlen = 0; line = filestore_getline(store, p); while (line == NULL && errno == EINVAL) { line = filestore_getline(store, p); } begin_markerlen = strlen(SFTP_SSH2_PUBKEY_BEGIN_MARKER); end_markerlen = strlen(SFTP_SSH2_PUBKEY_END_MARKER); while (line) { pr_signals_handle(); if (key == NULL && strncmp(line, SFTP_SSH2_PUBKEY_BEGIN_MARKER, begin_markerlen + 1) == 0) { key = pcalloc(p, sizeof(struct filestore_key)); bio = BIO_new(BIO_s_mem()); } else if (key != NULL && strncmp(line, SFTP_SSH2_PUBKEY_END_MARKER, end_markerlen + 1) == 0) { if (bio) { BIO *b64 = NULL, *bmem = NULL; char chunk[1024], *data = NULL; int chunklen; long datalen = 0; /* Add a base64 filter BIO, and read the data out, thus base64-decoding * the key. Write the decoded data into another memory BIO. */ b64 = BIO_new(BIO_f_base64()); BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL); bio = BIO_push(b64, bio); bmem = BIO_new(BIO_s_mem()); memset(chunk, '\0', sizeof(chunk)); chunklen = BIO_read(bio, chunk, sizeof(chunk)); if (chunklen < 0 && !BIO_should_retry(bio)) { (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION, "unable to base64-decode data in '%s': %s", store_data->path, sftp_crypto_get_errors()); BIO_free_all(bio); BIO_free_all(bmem); errno = EPERM; return NULL; } while (chunklen > 0) { pr_signals_handle(); if (BIO_write(bmem, chunk, chunklen) < 0) { (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION, "error writing to memory BIO: %s", sftp_crypto_get_errors()); BIO_free_all(bio); BIO_free_all(bmem); errno = EPERM; return NULL; } memset(chunk, '\0', sizeof(chunk)); chunklen = BIO_read(bio, chunk, sizeof(chunk)); } datalen = BIO_get_mem_data(bmem, &data); if (data != NULL && datalen > 0) { key->key_data = palloc(p, datalen); key->key_datalen = datalen; memcpy(key->key_data, data, datalen); } else { (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION, "error base64-decoding key data in '%s'", store_data->path); } BIO_free_all(bio); bio = NULL; BIO_free_all(bmem); } break; } else { if (key) { if (strstr(line, ": ") != NULL) { if (strncasecmp(line, "Subject: ", 9) == 0) { key->subject = pstrdup(p, line + 9); } } else { if (BIO_write(bio, line, strlen(line)) < 0) { (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION, "error buffering base64 data"); } } } } line = filestore_getline(store, p); while (line == NULL && errno == EINVAL) { line = filestore_getline(store, p); } } return key; } static int filestore_verify_host_key(sftp_keystore_t *store, pool *p, const char *user, const char *host_fqdn, const char *host_user, unsigned char *key_data, uint32_t key_len) { struct filestore_key *key = NULL; struct filestore_data *store_data = store->keystore_data; int res = -1; if (!store_data->path) { errno = EPERM; return -1; } /* XXX Note that this will scan the file from the beginning, each time. * There's room for improvement; perhaps mmap() the file into memory? */ key = filestore_get_key(store, p); while (key) { int ok; pr_signals_handle(); ok = sftp_keys_compare_keys(p, key_data, key_len, key->key_data, key->key_datalen); if (ok != TRUE) { if (ok == -1) { (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION, "error comparing keys from '%s': %s", store_data->path, strerror(errno)); } } else { /* XXX Verify that the user and the host_user match?? */ res = 0; break; } key = filestore_get_key(store, p); } if (res == 0) { pr_trace_msg(trace_channel, 10, "found matching public key for host '%s' " "in '%s'", host_fqdn, store_data->path); } if (pr_fsio_lseek(store_data->fh, 0, SEEK_SET) < 0) { (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION, "error seeking to start of '%s': %s", store_data->path, strerror(errno)); return -1; } store_data->lineno = 0; return res; } static int filestore_verify_user_key(sftp_keystore_t *store, pool *p, const char *user, unsigned char *key_data, uint32_t key_len) { struct filestore_key *key = NULL; struct filestore_data *store_data = store->keystore_data; unsigned int count = 0; int res = -1; if (!store_data->path) { errno = EPERM; return -1; } /* XXX Note that this will scan the file from the beginning, each time. * There's room for improvement; perhaps mmap() the file into memory? */ key = filestore_get_key(store, p); while (key) { int ok; pr_signals_handle(); count++; ok = sftp_keys_compare_keys(p, key_data, key_len, key->key_data, key->key_datalen); if (ok != TRUE) { if (ok == -1) { (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION, "error comparing keys from '%s': %s", store_data->path, strerror(errno)); } else { pr_trace_msg(trace_channel, 10, "failed to match key #%u from file '%s'", count, store_data->path); } } else { /* If we are configured to check for Subject headers, and if the file key * has a Subject header, and that header value does not match the * logging in user, then continue looking. */ if ((sftp_opts & SFTP_OPT_MATCH_KEY_SUBJECT) && key->subject != NULL) { if (strcmp(key->subject, user) != 0) { (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION, "found matching key for user '%s' in '%s', but Subject " "header ('%s') does not match, skipping key", user, store_data->path, key->subject); } else { res = 0; break; } } else { res = 0; break; } } key = filestore_get_key(store, p); } if (res == 0) { pr_trace_msg(trace_channel, 10, "found matching public key for user '%s' " "in '%s'", user, store_data->path); } if (pr_fsio_lseek(store_data->fh, 0, SEEK_SET) < 0) { (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION, "error seeking to start of '%s': %s", store_data->path, strerror(errno)); return -1; } store_data->lineno = 0; return res; } static int filestore_close(sftp_keystore_t *store) { struct filestore_data *store_data = store->keystore_data; pr_fsio_close(store_data->fh); return 0; } static sftp_keystore_t *filestore_open(pool *parent_pool, int requested_key_type, const char *store_info, const char *user) { int xerrno; sftp_keystore_t *store; pool *filestore_pool; struct filestore_data *store_data; pr_fh_t *fh; char buf[PR_TUNABLE_PATH_MAX+1], *path; struct stat st; filestore_pool = make_sub_pool(parent_pool); pr_pool_tag(filestore_pool, "SFTP File-based Keystore Pool"); store = pcalloc(filestore_pool, sizeof(sftp_keystore_t)); store->keystore_pool = filestore_pool; /* Open the file. The given path (store_info) may need to be * interpolated. */ session.user = (char *) user; memset(buf, '\0', sizeof(buf)); switch (pr_fs_interpolate(store_info, buf, sizeof(buf)-1)) { case 1: /* Interpolate occurred; make a copy of the interpolated path. */ path = pstrdup(filestore_pool, buf); break; default: /* Otherwise, use the path as is. */ path = pstrdup(filestore_pool, store_info); break; } session.user = NULL; PRIVS_ROOT fh = pr_fsio_open(path, O_RDONLY|O_NONBLOCK); xerrno = errno; PRIVS_RELINQUISH if (fh == NULL) { destroy_pool(filestore_pool); errno = xerrno; return NULL; } if (pr_fsio_set_block(fh) < 0) { xerrno = errno; destroy_pool(filestore_pool); (void) pr_fsio_close(fh); errno = xerrno; return NULL; } /* Stat the opened file to determine the optimal buffer size for IO. */ memset(&st, 0, sizeof(st)); if (pr_fsio_fstat(fh, &st) < 0) { xerrno = errno; destroy_pool(filestore_pool); (void) pr_fsio_close(fh); errno = xerrno; return NULL; } if (S_ISDIR(st.st_mode)) { destroy_pool(filestore_pool); (void) pr_fsio_close(fh); errno = EISDIR; return NULL; } fh->fh_iosz = st.st_blksize; store_data = pcalloc(filestore_pool, sizeof(struct filestore_data)); store->keystore_data = store_data; store_data->path = path; store_data->fh = fh; store_data->lineno = 0; store->store_ktypes = requested_key_type; switch (requested_key_type) { case SFTP_SSH2_HOST_KEY_STORE: store->verify_host_key = filestore_verify_host_key; break; case SFTP_SSH2_USER_KEY_STORE: store->verify_user_key = filestore_verify_user_key; break; } store->store_close = filestore_close; return store; } int sftp_rfc4716_init(void) { sftp_keystore_register_store("file", filestore_open, SFTP_SSH2_HOST_KEY_STORE|SFTP_SSH2_USER_KEY_STORE); return 0; } int sftp_rfc4716_free(void) { sftp_keystore_unregister_store("file", SFTP_SSH2_HOST_KEY_STORE|SFTP_SSH2_USER_KEY_STORE); return 0; }
pghmcfc/proftpd
contrib/mod_sftp/rfc4716.c
C
gpl-2.0
16,496
/* packet-hdmi.c * Routines for HDMI dissection * Copyright 2014 Martin Kaiser <martin@kaiser.cx> * * Wireshark - Network traffic analyzer * By Gerald Combs <gerald@wireshark.org> * Copyright 1998 Gerald Combs * * 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. * * This program 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 this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ /* this dissector handles I2C messages on the HDMI Display Data Channel (DDC) * * EDID (Extended Display Identification Data) messages are dissected here, * HDCP messages are passed on to the HDCP dissector */ #include "config.h" #include <glib.h> #include <epan/packet.h> #include <epan/ptvcursor.h> #include <epan/expert.h> #include <epan/wmem/wmem.h> #include "packet-hdmi.h" void proto_register_hdmi(void); void proto_reg_handoff_hdmi(void); static int proto_hdmi = -1; static dissector_handle_t hdcp_handle; static gint ett_hdmi = -1; static gint ett_hdmi_edid = -1; static int hf_hdmi_addr = -1; static int hf_hdmi_edid_offset = -1; static int hf_hdmi_edid_hdr = -1; static int hf_hdmi_edid_manf_id = -1; static int hf_hdmi_edid_manf_prod_code = -1; static int hf_hdmi_edid_manf_serial = -1; static int hf_hdmi_edid_manf_week = -1; static int hf_hdmi_edid_mod_year = -1; static int hf_hdmi_edid_manf_year = -1; /* also called Source and Sink in the HDMI spec */ #define ADDR_TRX "Transmitter" #define ADDR_RCV "Receiver" /* we use 8bit I2C addresses, including the direction bit */ #define ADDR8_HDCP_WRITE 0x74 /* transmitter->receiver */ #define ADDR8_HDCP_READ 0x75 /* r->t */ #define ADDR8_EDID_WRITE 0xA0 /* t->r */ #define ADDR8_EDID_READ 0xA1 /* r->t */ #define HDCP_ADDR8(x) (x==ADDR8_HDCP_WRITE || x==ADDR8_HDCP_READ) static const value_string hdmi_addr[] = { { ADDR8_HDCP_WRITE, "transmitter writes HDCP data for receiver" }, { ADDR8_HDCP_READ, "transmitter reads HDCP data from receiver" }, { ADDR8_EDID_WRITE, "EDID request" }, { ADDR8_EDID_READ, "EDID read" }, { 0, NULL } }; #define EDID_HDR_VALUE G_GUINT64_CONSTANT(0x00ffffffffffff00) /* grab 5 bits, from bit n to n+4, from a big-endian number x map those bits to a capital letter such that A==1, B==2, ... */ #define CAPITAL_LETTER(x, n) ('A'-1 + (((x) & (0x1F<<n)) >> n)) gboolean sub_check_hdmi(packet_info *pinfo _U_) { /* by looking at the i2c_phdr only, we can't decide if this packet is HDMI this function is called when the user explicitly selected HDMI in the preferences therefore, we always return TRUE and hand the data to the (new style) dissector who sees the 8bit address and the packet content */ return TRUE; } /* dissect EDID data from the receiver return the offset after the dissected data */ static gint dissect_hdmi_edid(tvbuff_t *tvb, gint offset, packet_info *pinfo, proto_tree *tree) { proto_item *ti, *yi; proto_tree *edid_tree; guint64 edid_hdr; guint16 manf_id; gchar manf_id_str[4]; /* 3 letters + 0-termination */ guint8 week, year; int year_hf; guint8 edid_ver, edid_rev; ti = proto_tree_add_text(tree, tvb, offset, tvb_reported_length_remaining(tvb, offset), "Extended Display Identification Data (EDID)"); edid_tree = proto_item_add_subtree(ti, ett_hdmi_edid); edid_hdr = tvb_get_ntoh64(tvb, offset); if (edid_hdr != EDID_HDR_VALUE) return offset; /* XXX handle fragmented EDID messages */ col_append_sep_str(pinfo->cinfo, COL_INFO, NULL, "EDID"); proto_tree_add_item(edid_tree, hf_hdmi_edid_hdr, tvb, offset, 8, ENC_LITTLE_ENDIAN); offset += 8; /* read as big endian for easier splitting */ manf_id = tvb_get_ntohs(tvb, offset); /* XXX check that MSB is 0 */ manf_id_str[0] = CAPITAL_LETTER(manf_id, 10); manf_id_str[1] = CAPITAL_LETTER(manf_id, 5); manf_id_str[2] = CAPITAL_LETTER(manf_id, 0); manf_id_str[3] = 0; proto_tree_add_string(edid_tree, hf_hdmi_edid_manf_id, tvb, offset, 2, manf_id_str); offset += 2; proto_tree_add_item(edid_tree, hf_hdmi_edid_manf_prod_code, tvb, offset, 2, ENC_LITTLE_ENDIAN); offset += 2; proto_tree_add_item(edid_tree, hf_hdmi_edid_manf_serial, tvb, offset, 4, ENC_LITTLE_ENDIAN); offset += 4; week = tvb_get_guint8(tvb, offset); proto_tree_add_item(edid_tree, hf_hdmi_edid_manf_week, tvb, offset, 1, ENC_LITTLE_ENDIAN); offset++; year_hf = week==255 ? hf_hdmi_edid_mod_year : hf_hdmi_edid_manf_year; year = tvb_get_guint8(tvb, offset); yi = proto_tree_add_item(edid_tree, year_hf, tvb, offset, 1, ENC_LITTLE_ENDIAN); proto_item_append_text(yi, " (year %d)", 1990+year); offset++; edid_ver = tvb_get_guint8(tvb, offset); edid_rev = tvb_get_guint8(tvb, offset+1); /* XXX make this filterable */ proto_tree_add_text(edid_tree, tvb, offset, 2, "EDID Version %d.%d", edid_ver, edid_rev); /* XXX dissect the parts following the EDID header */ return tvb_reported_length(tvb); } static int dissect_hdmi(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_) { guint8 addr; gint offset=0; proto_item *pi; proto_tree *hdmi_tree; /* the I2C address in the first byte is always handled by the HDMI dissector, even if the packet contains HDCP data */ addr = tvb_get_guint8(tvb, 0); if (!try_val_to_str(addr, hdmi_addr)) return 0; /* no HDMI packet */ col_set_str(pinfo->cinfo, COL_PROTOCOL, "HDMI"); col_clear(pinfo->cinfo, COL_INFO); pi = proto_tree_add_protocol_format(tree, proto_hdmi, tvb, 0, tvb_reported_length(tvb), "HDMI"); hdmi_tree = proto_item_add_subtree(pi, ett_hdmi); if (addr&0x01) { SET_ADDRESS(&pinfo->src, AT_STRINGZ, (int)strlen(ADDR_RCV)+1, ADDR_RCV); SET_ADDRESS(&pinfo->dst, AT_STRINGZ, (int)strlen(ADDR_TRX)+1, ADDR_TRX); pinfo->p2p_dir = P2P_DIR_RECV; } else { SET_ADDRESS(&pinfo->src, AT_STRINGZ, (int)strlen(ADDR_TRX)+1, ADDR_TRX); SET_ADDRESS(&pinfo->dst, AT_STRINGZ, (int)strlen(ADDR_RCV)+1, ADDR_RCV); pinfo->p2p_dir = P2P_DIR_SENT; } /* there's no explicit statement in the spec saying that the protocol is big or little endian there's three cases: one byte values, symmetrical values or values that are explicitly marked as little endian for the sake of simplicity, we use little endian everywhere */ proto_tree_add_item(hdmi_tree, hf_hdmi_addr, tvb, offset, 1, ENC_LITTLE_ENDIAN); offset++; if (HDCP_ADDR8(addr)) { gint hdcp_len; tvbuff_t *hdcp_tvb; hdcp_len = tvb_reported_length_remaining(tvb, offset); hdcp_tvb = tvb_new_subset(tvb, offset, hdcp_len, hdcp_len); return call_dissector(hdcp_handle, hdcp_tvb, pinfo, hdmi_tree); } if (addr==ADDR8_EDID_WRITE) { col_append_sep_str(pinfo->cinfo, COL_INFO, NULL, "EDID request"); proto_tree_add_item(hdmi_tree, hf_hdmi_edid_offset, tvb, offset, 1, ENC_LITTLE_ENDIAN); offset++; return offset; } return dissect_hdmi_edid(tvb, offset, pinfo, hdmi_tree); } void proto_register_hdmi(void) { static hf_register_info hf[] = { { &hf_hdmi_addr, { "8bit I2C address", "hdmi.addr", FT_UINT8, BASE_HEX, VALS(hdmi_addr), 0, NULL, HFILL } }, { &hf_hdmi_edid_offset, { "Offset", "hdmi.edid.offset", FT_UINT8, BASE_HEX, NULL, 0, NULL, HFILL } }, { &hf_hdmi_edid_hdr, { "EDID header", "hdmi.edid.hdr", FT_UINT64, BASE_HEX, NULL, 0, NULL, HFILL } }, { &hf_hdmi_edid_manf_id, { "Manufacturer ID", "hdmi.edid.manf_id", FT_STRING, STR_ASCII, NULL, 0, NULL, HFILL } }, { &hf_hdmi_edid_manf_prod_code, { "Manufacturer product code", "hdmi.edid.manf_prod_code", FT_UINT16, BASE_HEX, NULL, 0, NULL, HFILL } }, { &hf_hdmi_edid_manf_serial, { "Serial number", "hdmi.edid.serial_num", FT_UINT32, BASE_DEC, NULL, 0, NULL, HFILL } }, { &hf_hdmi_edid_manf_week, { "Week of manufacture", "hdmi.edid.manf_week", FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL } }, { &hf_hdmi_edid_mod_year, { "Model year", "hdmi.edid.model_year", FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL } }, { &hf_hdmi_edid_manf_year, { "Year of manufacture", "hdmi.edid.manf_year", FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL } } }; static gint *ett[] = { &ett_hdmi, &ett_hdmi_edid }; proto_hdmi = proto_register_protocol( "High-Definition Multimedia Interface", "HDMI", "hdmi"); proto_register_field_array(proto_hdmi, hf, array_length(hf)); proto_register_subtree_array(ett, array_length(ett)); new_register_dissector("hdmi", dissect_hdmi, proto_hdmi); } void proto_reg_handoff_hdmi(void) { hdcp_handle = find_dissector("hdcp"); } /* * Editor modelines - http://www.wireshark.org/tools/modelines.html * * Local variables: * c-basic-offset: 4 * tab-width: 8 * indent-tabs-mode: nil * End: * * vi: set shiftwidth=4 tabstop=8 expandtab: * :indentSize=4:tabSize=8:noTabs=true: */
jfzazo/wireshark-hwgen
src/epan/dissectors/packet-hdmi.c
C
gpl-2.0
10,017
/* * xplus4-main.c - Watcom main.c for xplus4 wrapper. * * Written by * Marco van den Heuvel <blackystardust68@yahoo.com> * * This file is part of VICE, the Versatile Commodore Emulator. * See README for copyright notice. * * 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. * * This program 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 this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA * 02111-1307 USA. * */ #include "main.c"
AreaScout/vice-gles2
src/arch/watcom-source-wrappers/xplus4-main.c
C
gpl-2.0
987
/*****************************************************************************/ /* */ /* Ittiam WPS SOFTWARE */ /* */ /* ITTIAM SYSTEMS PVT LTD, BANGALORE */ /* COPYRIGHT(C) 2011 */ /* */ /* This program is proprietary to Ittiam Systems Private Limited and */ /* is protected under Indian Copyright Law as an unpublished work. Its use */ /* and disclosure is limited by the terms and conditions of a license */ /* agreement. It may not be copied or otherwise reproduced or disclosed to */ /* persons outside the licensee's organization except in accordance with the*/ /* terms and conditions of such an agreement. All copies and */ /* reproductions shall be the property of Ittiam Systems Private Limited and*/ /* must bear this notice in its entirety. */ /* */ /*****************************************************************************/ /*****************************************************************************/ /* */ /* File Name : wps_key.c */ /* */ /* Description : This file contains the functions to generate the */ /* Authentication and Key Wrap Key */ /* */ /* List of Functions : wps_kdf */ /* wps_gen_keys */ /* */ /* Issues / Problems : None */ /* */ /* Revision History : */ /* */ /* DD MM YYYY Author(s) Changes */ /* 25 02 2011 Ittiam Draft */ /* */ /*****************************************************************************/ #ifdef INT_WPS_REG_SUPP /*****************************************************************************/ /* File Includes */ /*****************************************************************************/ #include "hmac_sha256.h" #include "dh_key.h" #include "wps_key.h" /*****************************************************************************/ /* Static Function Declarations */ /*****************************************************************************/ static void wps_kdf(UWORD8* inp_key, UWORD8* pers_str, UWORD8 pers_str_len, UWORD8* out_key, UWORD32 total_key_bytes); /*****************************************************************************/ /* */ /* Function Name : wps_kdf */ /* */ /* Description : This function implements the Key Derivation function */ /* as described in WPS standard version v.1.2.2 */ /* */ /* Inputs : 1) Input Key used for key hashing */ /* 2) Pointer to personalization string */ /* 3) Length of personalization string */ /* 4) Pointer to location where output key needs to be */ /* stored. The output key buffer should be long */ /* enough to store ((Total Output key bytes + SHA256 */ /* hash length -1)/ SHA256 hash length) of bytes i.e */ /* this module output bytes in multiple of SHA256 */ /* hash length. Calling function should take care of */ /* selecting appropriate number of bytes */ /* 5) Required length in bytes of the output key */ /* */ /* Globals : None */ /* */ /* Processing : This function implements the following algorithm */ /* kdf(key, personalization_string, total_key_bits) : */ /* result := "" */ /* iterations = (total_key_bits+prf_digest_size-1)/ */ /* prf_digest_size */ /* for i = 1 to iterations do */ /* result = result || prf(key, i || */ /* personalization_string || total_key_bits)*/ /* return result */ /* The function prf is the keyed hash HMAC-SHA-256 */ /* */ /* Outputs : None */ /* */ /* Returns : Key bits generating using KDF function */ /* */ /* Issues : None */ /* */ /* Revision History: */ /* */ /* DD MM YYYY Author(s) Changes */ /* 24 02 2010 Ittiam Draft */ /* */ /*****************************************************************************/ void wps_kdf(UWORD8* inp_key, UWORD8* pers_str, UWORD8 pers_str_len, UWORD8* out_key, UWORD32 total_key_bytes) { UWORD8 *msg[3]; UWORD8 iter_buff[4], total_key_bits_buff[4]; UWORD16 msg_len[3]; UWORD32 iter, max_iter; /* use iter as temporary variable to store total number of bits */ iter = total_key_bytes * 8; max_iter = (total_key_bytes + SHA_256_HASH_LEN - 1) / SHA_256_HASH_LEN; total_key_bits_buff[3] = (UWORD8)(iter); total_key_bits_buff[2] = (UWORD8)(iter >> 8); total_key_bits_buff[1] = (UWORD8)(iter >> 16); total_key_bits_buff[0] = (UWORD8)(iter >> 24); msg[0] = iter_buff; msg_len[0] = sizeof(iter_buff); msg[1] = pers_str; msg_len[1] = pers_str_len; msg[2] = total_key_bits_buff; msg_len[2] = sizeof(total_key_bits_buff); /*************************************************************************/ /* This function will generates bytes in multiples of SHA_256_HASH_LEN */ /* calling function to ensure that the out_key has enough space */ /*************************************************************************/ for (iter = 1; iter <= max_iter; ++iter) { iter_buff[3] = (UWORD8)(iter); iter_buff[2] = (UWORD8)(iter >> 8); iter_buff[1] = (UWORD8)(iter >> 16); iter_buff[0] = (UWORD8)(iter >> 24); hmac_sha256(inp_key, SHA_256_HASH_LEN, msg, msg_len,3, out_key); out_key += SHA_256_HASH_LEN; } } /*****************************************************************************/ /* */ /* Function Name : wps_gen_keys */ /* */ /* Description : This function generates Diffie-Hellman shared secret */ /* key. This key needs to be hashed before it can be used*/ /* */ /* Inputs : 1) Pointer Rxed Public Key (PKe or PKr buffer) */ /* 2) Pointer to Enrollee`s Nonce, N1 */ /* 3) POinter to Registrar`s Nonce, N2 */ /* 4) Pointer to Enrollee`s MAC Address */ /* 5) Pointer to WPS Authentication Key */ /* 6) Pointer to WPS Key Wrap Key */ /* 7) Pointer to DH Private key (A or B) */ /* */ /* Globals : None */ /* */ /* Processing : Using the received public key and local private key */ /* this functions generate the shared secret key = */ /* = (pubic key ^private Key) mod p) where g =2, p is */ /* predefined prime. It then converts the secret key in */ /* byte format. Public key, Private key, secret key and */ /* Prime are all of length WPS_DH_PRIME_LEN_WORD32. */ /* */ /* Outputs : Authentication Key and Key Wrap key */ /* */ /* Returns : SUCCESS/FAILURE */ /* */ /* Issues : None */ /* */ /* Revision History: */ /* */ /* DD MM YYYY Author(s) Changes */ /* 25 02 2011 Ittiam Draft */ /* */ /*****************************************************************************/ STATUS_T wps_gen_keys(UWORD8 *rx_pub_key, UWORD8 *enr_nonce, UWORD8 *reg_nonce, UWORD8 *enr_mac_addr, UWORD8 *auth_key, UWORD8 *key_wrap_key, long_num_struct_t *priv_key_ptr) { UWORD8 *msg[3]; UWORD16 msg_len[3]; const UWORD8 pers_str[] = "Wi-Fi Easy and Secure Key Derivation"; /*************************************************************************/ /* Generate pre-hash DH Key = (Public Key ^ Private Key) mod Prime */ /* DH key will be stored in byte format in place of Received Public Key */ /*************************************************************************/ if(FAILURE == wps_gen_ph_dh_key((UWORD32 *)rx_pub_key, priv_key_ptr)) { return FAILURE; } /*************************************************************************/ /* Generate DH Key = sha256(Pre-Hashed DH-Key) and store DH key in place */ /* of pre-hash DH key */ /*************************************************************************/ msg[0] = rx_pub_key; msg_len[0] = WPS_DH_PRIME_LEN_BYTE; sha256(msg, msg_len, 1, rx_pub_key); /*************************************************************************/ /* Generate KDK = HMAC-SHA256(DHKey) (N1 || EnrolleeMAC || N2). Store KDK*/ /* in place of DH key */ /*************************************************************************/ msg[0] = enr_nonce; msg[1] = enr_mac_addr; msg[2] = reg_nonce; msg_len[0] = WPS_NONCE_LEN; msg_len[1] = MAC_ADDRESS_LEN; msg_len[2] = WPS_NONCE_LEN; hmac_sha256(rx_pub_key, SHA_256_HASH_LEN, msg, msg_len, 3, rx_pub_key); /*************************************************************************/ /* Use key derivation function to generate AuthKey and Key Wrap key using*/ /* key derivation function key. */ /*************************************************************************/ wps_kdf(rx_pub_key, (UWORD8 *)pers_str, (UWORD8)(sizeof(pers_str) -1), (rx_pub_key + SHA_256_HASH_LEN), (WPS_AUTH_KEY_LEN + WPS_KEY_WRAP_KEY_LEN + WPS_EMSK_LEN)); /* Copy Auth Key to the WPS persistent memory */ memcpy(auth_key, rx_pub_key + SHA_256_HASH_LEN, WPS_AUTH_KEY_LEN); /* Copy Key Wrap Key to the WPS persistent memory */ memcpy(key_wrap_key, (rx_pub_key + SHA_256_HASH_LEN + WPS_AUTH_KEY_LEN), WPS_KEY_WRAP_KEY_LEN); return SUCCESS; } #endif /* INT_WPS_REG_SUPP */
voltagex/kernel-sprdb2g_gonk4.0_6821
drivers/net/wireless/trout/mac/src/Library/WPS/Protocols/wps_key.c
C
gpl-2.0
14,127
/* SPDX-License-Identifier: GPL-2.0-only */ #include <delay.h> #include <device/mmio.h> #include <console/console.h> #include <console/uart.h> #include <soc/addressmap.h> #include <soc/otp.h> /* * This is a driver for the eMemory EG004K32TQ028XW01 NeoFuse * One-Time-Programmable (OTP) memory used within the SiFive FU540. * It is documented in the FU540 manual here: * https://www.sifive.com/documentation/chips/freedom-u540-c000-manual/ */ struct sifive_otp_registers { u32 pa; /* Address input */ u32 paio; /* Program address input */ u32 pas; /* Program redundancy cell selection input */ u32 pce; /* OTP Macro enable input */ u32 pclk; /* Clock input */ u32 pdin; /* Write data input */ u32 pdout; /* Read data output */ u32 pdstb; /* Deep standby mode enable input (active low) */ u32 pprog; /* Program mode enable input */ u32 ptc; /* Test column enable input */ u32 ptm; /* Test mode enable input */ u32 ptm_rep;/* Repair function test mode enable input */ u32 ptr; /* Test row enable input */ u32 ptrim; /* Repair function enable input */ u32 pwe; /* Write enable input (defines program cycle) */ } __packed; /* * Read a 32 bit value addressed by its index from the OTP. * The FU540 stores 4096x32 bit (16KiB) values. * Index 0x00-0xff are reserved for SiFive internal use. (first 1KiB) */ u32 otp_read_word(u16 idx) { u32 w; if (idx >= 0x1000) die("otp: idx out of bounds"); struct sifive_otp_registers *regs = (void *)(FU540_OTP); // wake up from stand-by write32(&regs->pdstb, 0x01); // enable repair function write32(&regs->ptrim, 0x01); // enable input write32(&regs->pce, 0x01); // address to read write32(&regs->pa, idx); // cycle clock to read write32(&regs->pclk, 0x01); mdelay(1); write32(&regs->pclk, 0x00); mdelay(1); w = read32(&regs->pdout); // shut down write32(&regs->pce, 0x00); write32(&regs->ptrim, 0x00); write32(&regs->pdstb, 0x00); return w; } u32 otp_read_serial(void) { u32 serial = 0; u32 serial_n = 0; for (int i = 0xfe; i > 0; i -= 2) { serial = otp_read_word(i); serial_n = otp_read_word(i+1); if (serial == ~serial_n) break; } return serial; }
felixsinger/coreboot
src/soc/sifive/fu540/otp.c
C
gpl-2.0
2,193
/* -*- C -*- //C- ------------------------------------------------------------------- //C- DjView4 //C- Copyright (c) 2006 Leon Bottou //C- //C- This software is subject to, and may be distributed under, the //C- GNU General Public License, either version 2 of the license, //C- or (at your option) any later version. The license should have //C- accompanied the software or you may obtain a copy of the license //C- from the Free Software Foundation at http://www.fsf.org . //C- //C- This program is distributed in the hope that it will be useful, //C- but WITHOUT ANY WARRANTY; without even the implied warranty of //C- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //C- GNU General Public License for more details. //C- ------------------------------------------------------------------ */ /* The following code is derived from program "tiff2pdf" * whose copyright notice is reproduced below. * Changes were made to make it independent from the private * include file tiffiop.h. * * +-------------------------------------------------------------------- * | tiff2pdf - converts a TIFF image to a PDF document * | * | Copyright (c) 2003 Ross Finlayson * | * | Permission to use, copy, modify, distribute, and sell this software and * | its documentation for any purpose is hereby granted without fee, provided * | that (i) the above copyright notices and this permission notice appear in * | all copies of the software and related documentation, and (ii) the name of * | Ross Finlayson may not be used in any advertising or * | publicity relating to the software without the specific, prior written * | permission of Ross Finlayson. * | * | THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, * | EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * | WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * | * | IN NO EVENT SHALL ROSS FINLAYSON BE LIABLE FOR * | ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, * | OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, * | WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF * | LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * | OF THIS SOFTWARE. * +-------------------------------------------------------------------- */ #include "tiff2pdf.h" #if HAVE_TIFF2PDF #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <time.h> #if HAVE_UNISTD_H # include <unistd.h> #endif #ifndef NULL # define NULL ((void*)0) #endif #ifdef __GNUC__ # define unused __attribute__((unused)) #else # define unused /**/ #endif /* -------------------------------------------------- * Tiff2Pdf declarations * -------------------------------------------------- */ #define TIFF2PDF_MODULE "tiff2pdf" #define T2P_VERSION "d" /* This type is of PDF color spaces. */ typedef enum{ T2P_CS_BILEVEL=0x01, /* Bilevel, black and white */ T2P_CS_GRAY=0x02, /* Single channel */ T2P_CS_RGB=0x04, /* Three channel tristimulus RGB */ T2P_CS_CMYK=0x08, /* Four channel CMYK print inkset */ T2P_CS_LAB=0x10, /* Three channel L*a*b* color space */ T2P_CS_PALETTE=0x1000 /* One of the above with a color map */ , T2P_CS_CALGRAY=0x20 /* Calibrated single channel */ , T2P_CS_CALRGB=0x40 /* Calibrated three channel tristimulus RGB */ , T2P_CS_ICCBASED=0x80 /* ICC profile color specification */ } t2p_cs_t; /* This type is of PDF compression types. */ typedef enum{ T2P_COMPRESS_NONE=0x00 #ifdef CCITT_SUPPORT , T2P_COMPRESS_G4=0x01 #endif #if defined(JPEG_SUPPORT) || defined(OJPEG_SUPPORT) , T2P_COMPRESS_JPEG=0x02 #endif #ifdef ZIP_SUPPORT , T2P_COMPRESS_ZIP=0x04 #endif } t2p_compress_t; /* This type is whether TIFF image data can be used in PDF without transcoding. */ typedef enum{ T2P_TRANSCODE_RAW=0x01, /* The raw data from the input can be used without recompressing */ T2P_TRANSCODE_ENCODE=0x02 /* The data from the input is perhaps unencoded and reencoded */ } t2p_transcode_t; /* This type is of information about the data samples of the input image. */ typedef enum{ T2P_SAMPLE_NOTHING=0x0000, /* The unencoded samples are normal for the output colorspace */ T2P_SAMPLE_ABGR_TO_RGB=0x0001, /* The unencoded samples are the result of ReadRGBAImage */ T2P_SAMPLE_RGBA_TO_RGB=0x0002, /* The unencoded samples are contiguous RGBA */ T2P_SAMPLE_RGBAA_TO_RGB=0x0004, /* The unencoded samples are RGBA with premultiplied alpha */ T2P_SAMPLE_YCBCR_TO_RGB=0x0008, T2P_SAMPLE_YCBCR_TO_LAB=0x0010, T2P_SAMPLE_REALIZE_PALETTE=0x0020, /* The unencoded samples are indexes into the color map */ T2P_SAMPLE_SIGNED_TO_UNSIGNED=0x0040, /* The unencoded samples are signed instead of unsignd */ T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED=0x0040, /* The L*a*b* samples have a* and b* signed */ T2P_SAMPLE_PLANAR_SEPARATE_TO_CONTIG=0x0100 /* The unencoded samples are separate instead of contiguous */ } t2p_sample_t; /* This type is of error status of the T2P struct. */ typedef enum{ T2P_ERR_OK = 0, /* This is the value of t2p->t2p_error when there is no error */ T2P_ERR_ERROR = 1 /* This is the value of t2p->t2p_error when there was an error */ } t2p_err_t; /* This struct defines a logical page of a TIFF. */ typedef struct { tdir_t page_directory; uint32 page_number; ttile_t page_tilecount; uint32 page_extra; } T2P_PAGE; /* This struct defines a PDF rectangle's coordinates. */ typedef struct { float x1; float y1; float x2; float y2; float mat[9]; } T2P_BOX; /* This struct defines a tile of a PDF. */ typedef struct { T2P_BOX tile_box; } T2P_TILE; /* This struct defines information about the tiles on a PDF page. */ typedef struct { ttile_t tiles_tilecount; uint32 tiles_tilewidth; uint32 tiles_tilelength; uint32 tiles_tilecountx; uint32 tiles_tilecounty; uint32 tiles_edgetilewidth; uint32 tiles_edgetilelength; T2P_TILE* tiles_tiles; } T2P_TILES; /* This struct is the context of a function to generate PDF from a TIFF. */ typedef struct { t2p_err_t t2p_error; T2P_PAGE* tiff_pages; T2P_TILES* tiff_tiles; tdir_t tiff_pagecount; uint16 tiff_compression; uint16 tiff_photometric; uint16 tiff_fillorder; uint16 tiff_bitspersample; uint16 tiff_samplesperpixel; uint16 tiff_planar; uint32 tiff_width; uint32 tiff_length; float tiff_xres; float tiff_yres; uint16 tiff_orientation; toff_t tiff_dataoffset; tsize_t tiff_datasize; TIFFReadWriteProc tiff_readproc; TIFFReadWriteProc tiff_writeproc; TIFFSeekProc tiff_seekproc; uint16 tiff_resunit; uint16 pdf_centimeters; uint16 pdf_overrideres; uint16 pdf_overridepagesize; float pdf_defaultxres; float pdf_defaultyres; float pdf_xres; float pdf_yres; float pdf_defaultpagewidth; float pdf_defaultpagelength; float pdf_pagewidth; float pdf_pagelength; float pdf_imagewidth; float pdf_imagelength; T2P_BOX pdf_mediabox; T2P_BOX pdf_imagebox; uint16 pdf_majorversion; uint16 pdf_minorversion; uint32 pdf_catalog; uint32 pdf_pages; uint32 pdf_info; uint32 pdf_palettecs; uint16 pdf_fitwindow; uint32 pdf_startxref; char* pdf_fileid; char* pdf_datetime; char* pdf_creator; char* pdf_author; char* pdf_title; char* pdf_subject; char* pdf_keywords; t2p_cs_t pdf_colorspace; uint16 pdf_colorspace_invert; uint16 pdf_switchdecode; uint16 pdf_palettesize; unsigned char* pdf_palette; int pdf_labrange[4]; t2p_compress_t pdf_defaultcompression; uint16 pdf_defaultcompressionquality; t2p_compress_t pdf_compression; uint16 pdf_compressionquality; uint16 pdf_nopassthrough; t2p_transcode_t pdf_transcode; t2p_sample_t pdf_sample; uint32* pdf_xrefoffsets; uint32 pdf_xrefcount; tdir_t pdf_page; #ifdef OJPEG_SUPPORT tdata_t pdf_ojpegdata; uint32 pdf_ojpegdatalength; uint32 pdf_ojpegiflength; #endif float tiff_whitechromaticities[2]; float tiff_primarychromaticities[6]; float tiff_referenceblackwhite[2]; float* tiff_transferfunction[3]; int pdf_image_interpolate; /* 0 (default) : do not interpolate, 1 : interpolate */ uint16 tiff_transferfunctioncount; uint32 pdf_icccs; uint32 tiff_iccprofilelength; tdata_t tiff_iccprofile; /* LB additional fields */ FILE *outputfile; int outputdisable; tsize_t outputwritten; } T2P; /* These functions are called by main. */ static int tiff2pdf_match_paper_size(float*, float*, char*); /* These functions are used to generate a PDF from a TIFF. */ static T2P* t2p_init(void); static void t2p_validate(T2P*); static tsize_t t2p_write_pdf(T2P*, TIFF*, TIFF*); static void t2p_free(T2P*); static void t2p_read_tiff_init(T2P*, TIFF*); static int t2p_cmp_t2p_page(const void*, const void*); static void t2p_read_tiff_data(T2P*, TIFF*); static void t2p_read_tiff_size(T2P*, TIFF*); static void t2p_read_tiff_size_tile(T2P*, TIFF*, ttile_t); static int t2p_tile_is_right_edge(T2P_TILES, ttile_t); static int t2p_tile_is_bottom_edge(T2P_TILES, ttile_t); static tsize_t t2p_readwrite_pdf_image(T2P*, TIFF*, TIFF*); static tsize_t t2p_readwrite_pdf_image_tile(T2P*, TIFF*, TIFF*, ttile_t); #ifdef OJPEG_SUPPORT static int t2p_process_ojpeg_tables(T2P*, TIFF*); #endif #ifdef JPEG_SUPPORT static int t2p_process_jpeg_strip(unsigned char*, tsize_t*, unsigned char*, tsize_t*, tstrip_t, uint32); #endif static void t2p_tile_collapse_left(tdata_t, tsize_t, uint32, uint32, uint32); static void t2p_write_advance_directory(T2P*, TIFF*); static tsize_t t2p_sample_planar_separate_to_contig(T2P*, unsigned char*, unsigned char*, tsize_t); static tsize_t t2p_sample_realize_palette(T2P*, unsigned char*); static tsize_t t2p_sample_abgr_to_rgb(tdata_t, uint32); static tsize_t t2p_sample_rgba_to_rgb(tdata_t, uint32); static tsize_t t2p_sample_rgbaa_to_rgb(tdata_t, uint32); static tsize_t t2p_sample_lab_signed_to_unsigned(tdata_t, uint32); static tsize_t t2p_write_pdf_header(T2P*, TIFF*); static tsize_t t2p_write_pdf_obj_start(uint32, TIFF*); static tsize_t t2p_write_pdf_obj_end(TIFF*); static tsize_t t2p_write_pdf_string(char*, TIFF*); static tsize_t t2p_write_pdf_stream(tdata_t, tsize_t, TIFF*); static tsize_t t2p_write_pdf_stream_start(TIFF*); static tsize_t t2p_write_pdf_stream_end(TIFF*); static tsize_t t2p_write_pdf_stream_dict(tsize_t, uint32, TIFF*); static tsize_t t2p_write_pdf_stream_dict_start(TIFF*); static tsize_t t2p_write_pdf_stream_dict_end(TIFF*); static tsize_t t2p_write_pdf_stream_length(tsize_t, TIFF*); static tsize_t t2p_write_pdf_catalog(T2P*, TIFF*); static tsize_t t2p_write_pdf_info(T2P*, TIFF*, TIFF*); static void t2p_pdf_currenttime(T2P*); static void t2p_pdf_tifftime(T2P*, TIFF*); static tsize_t t2p_write_pdf_pages(T2P*, TIFF*); static tsize_t t2p_write_pdf_page(uint32, T2P*, TIFF*); static void t2p_compose_pdf_page(T2P*); static void t2p_compose_pdf_page_orient(T2P_BOX*, uint16); static void t2p_compose_pdf_page_orient_flip(T2P_BOX*, uint16); static tsize_t t2p_write_pdf_xobject_cs(T2P*, TIFF*); static tsize_t t2p_write_pdf_transfer(T2P*, TIFF*); static tsize_t t2p_write_pdf_transfer_dict(T2P*, TIFF*, uint16); static tsize_t t2p_write_pdf_transfer_stream(T2P*, TIFF*, uint16); static tsize_t t2p_write_pdf_xobject_calcs(T2P*, TIFF*); static tsize_t t2p_write_pdf_xobject_icccs(T2P*, TIFF*); static tsize_t t2p_write_pdf_xobject_icccs_dict(T2P*, TIFF*); static tsize_t t2p_write_pdf_xobject_icccs_stream(T2P*, TIFF*); static tsize_t t2p_write_pdf_xobject_decode(T2P*, TIFF*); static tsize_t t2p_write_pdf_xobject_stream_filter(ttile_t, T2P*, TIFF*); static tsize_t t2p_write_pdf_xreftable(T2P*, TIFF*); static tsize_t t2p_write_pdf_trailer(T2P*, TIFF*); /* -------------------------------------------------- * Replacement for tiffiop functions * -------------------------------------------------- */ static unused tsize_t t2pReadFile(TIFF *tif, tdata_t data, tsize_t size) { thandle_t client = TIFFClientdata(tif); TIFFReadWriteProc proc = TIFFGetReadProc(tif); if (proc) return proc(client, data, size); return -1; } static unused tsize_t t2pWriteFile(TIFF *tif, tdata_t data, tsize_t size) { thandle_t client = TIFFClientdata(tif); TIFFReadWriteProc proc = TIFFGetWriteProc(tif); if (proc) return proc(client, data, size); return -1; } static unused toff_t t2pSeekFile(TIFF *tif, toff_t offset, int whence) { thandle_t client = TIFFClientdata(tif); TIFFSeekProc proc = TIFFGetSeekProc(tif); if (proc) return proc(client, offset, whence); return -1; } #ifdef TIFFReadFile # undef TIFFReadFile #endif #ifndef TIFFReadFile # define TIFFReadFile t2pReadFile #endif #ifdef TIFFWriteFile # undef TIFFWriteFile #endif #ifndef TIFFWriteFile # define TIFFWriteFile t2pWriteFile #endif #ifdef TIFFSeekFile # undef TIFFSeekFile #endif #ifndef TIFFSeekFile # define TIFFSeekFile t2pSeekFile #endif static void t2p_disable(TIFF *tif) { T2P *t2p = (T2P*) TIFFClientdata(tif); t2p->outputdisable = 1; } static void t2p_enable(TIFF *tif) { T2P *t2p = (T2P*) TIFFClientdata(tif); t2p->outputdisable = 0; } /* -------------------------------------------------- * Procs for TIFFClientOpen * -------------------------------------------------- */ static tsize_t t2p_readproc(thandle_t unused handle, tdata_t unused data , tsize_t unused size) { return -1; } static tsize_t t2p_writeproc(thandle_t handle, tdata_t data, tsize_t size) { T2P *t2p = (T2P*) handle; if (t2p->outputdisable <= 0 && t2p->outputfile) { tsize_t written = fwrite(data, 1, size, t2p->outputfile); t2p->outputwritten += written; return written; } return size; } static toff_t t2p_seekproc(thandle_t handle, toff_t offset, int whence) { T2P *t2p = (T2P*) handle; if (t2p->outputdisable <= 0 && t2p->outputfile) return fseek(t2p->outputfile, offset, whence); return offset; } static int t2p_closeproc(thandle_t unused handle) { return 0; } static toff_t t2p_sizeproc(thandle_t unused handle) { return -1; } static int t2p_mapproc(thandle_t unused handle, tdata_t unused *data, toff_t unused *offset) { return -1; } static void t2p_unmapproc(thandle_t unused handle, tdata_t unused data, toff_t unused offset) { } /* -------------------------------------------------- * Ports * -------------------------------------------------- */ #ifdef WIN32 /* * Copyright (c) 1987, 1993, 1994 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #if 0 static char sccsid[] = "@(#)getopt.c 8.3 (Berkeley) 4/27/95"; __RCSID("$NetBSD: getopt.c,v 1.26 2003/08/07 16:43:40 agc Exp $"); #endif #include <stdio.h> #include <string.h> int opterr = 1, /* if error message should be printed */ optind = 1, /* index into parent argv vector */ optopt, /* character checked for validity */ optreset; /* reset getopt */ char *optarg; /* argument associated with option */ #define BADCH (int)'?' #define BADARG (int)':' #define EMSG "" /* * getopt -- * Parse argc/argv argument vector. */ int getopt(int argc, char * const argv[], const char *optstring) { static char *place = EMSG; /* option letter processing */ char *oli; /* option letter list index */ if (optreset || *place == 0) { /* update scanning pointer */ optreset = 0; place = argv[optind]; if (optind >= argc || *place++ != '-') { /* Argument is absent or is not an option */ place = EMSG; return (-1); } optopt = *place++; if (optopt == '-' && *place == 0) { /* "--" => end of options */ ++optind; place = EMSG; return (-1); } if (optopt == 0) { /* Solitary '-', treat as a '-' option if the program (eg su) is looking for it. */ place = EMSG; if (strchr(optstring, '-') == NULL) return -1; optopt = '-'; } } else optopt = *place++; /* See if option letter is one the caller wanted... */ if (optopt == ':' || (oli = strchr(optstring, optopt)) == NULL) { if (*place == 0) ++optind; if (opterr && *optstring != ':') (void)fprintf(stderr, "unknown option -- %c\n", optopt); return (BADCH); } /* Does this option need an argument? */ if (oli[1] != ':') { /* don't need argument */ optarg = NULL; if (*place == 0) ++optind; } else { /* Option-argument is either the rest of this argument or the entire next argument. */ if (*place) optarg = place; else if (argc > ++optind) optarg = argv[optind]; else { /* option-argument absent */ place = EMSG; if (*optstring == ':') return (BADARG); if (opterr) (void)fprintf(stderr, "option requires an argument -- %c\n", optopt); return (BADCH); } place = EMSG; ++optind; } return (optopt); /* return option letter */ } #endif /* -------------------------------------------------- * Main function * -------------------------------------------------- */ /* This is the main function. The program converts one TIFF file to one PDF file, including multiple page TIFF files, tiled TIFF files, black and white. grayscale, and color TIFF files that contain data of TIFF photometric interpretations of bilevel, grayscale, RGB, YCbCr, CMYK separation, and ICC L*a*b* as supported by libtiff and PDF. If you have multiple TIFF files to convert into one PDF file then use tiffcp or other program to concatenate the files into a multiple page TIFF file. If the input TIFF file is of huge dimensions (greater than 10000 pixels height or width) convert the input image to a tiled TIFF if it is not already. The standard output is standard output. Set the output file name with the "-o output.pdf" option. All black and white files are compressed into a single strip CCITT G4 Fax compressed PDF, unless tiled, where tiled black and white images are compressed into tiled CCITT G4 Fax compressed PDF, libtiff CCITT support is assumed. Color and grayscale data can be compressed using either JPEG compression, ITU-T T.81, or Zip/Deflate LZ77 compression, per PNG 1.2 and RFC 1951. Set the compression type using the -j or -z options. JPEG compression support requires that libtiff be configured with JPEG support, and Zip/Deflate compression support requires that libtiff is configured with Zip support, in tiffconf.h. Use only one or the other of -j and -z. The -q option sets the image compression quality, that is 1-100 with libjpeg JPEG compression and one of 1, 10, 11, 12, 13, 14, or 15 for PNG group compression predictor methods, add 100, 200, ..., 900 to set zlib compression quality 1-9. PNG Group differencing predictor methods are not currently implemented. If the input TIFF contains single strip CCITT G4 Fax compressed information, then that is written to the PDF file without transcoding, unless the options of no compression and no passthrough are set, -d and -n. If the input TIFF contains JPEG or single strip Zip/Deflate compressed information, and they are configured, then that is written to the PDF file without transcoding, unless the options of no compression and no passthrough are set. The default page size upon which the TIFF image is placed is determined by the resolution and extent of the image data. Default values for the TIFF image resolution can be set using the -x and -y options. The page size can be set using the -p option for paper size, or -w and -l for paper width and length, then each page of the TIFF image is centered on its page. The distance unit for default resolution and page width and length can be set by the -u option, the default unit is inch. Various items of the output document information can be set with the -e, -c, -a, -t, -s, and -k tags. Setting the argument of the option to "" for these tags causes the relevant document information field to be not written. Some of the document information values otherwise get their information from the input TIFF image, the software, author, document name, and image description. The output PDF file conforms to the PDF 1.1 specification or PDF 1.2 if using Zip/Deflate compression. The Portable Document Format (PDF) specification is copyrighted by Adobe Systems, Incorporated. Todos derechos reservados. Here is a listing of the usage example and the options to the tiff2pdf program that is part of the libtiff distribution. Options followed by a colon have a required argument. usage: tiff2pdf [options] input.tif options: -o: output to file name -j compress with JPEG (requires libjpeg configured with libtiff) -z compress with Zip/Deflate (requires zlib configured with libtiff) -q: compression quality -n no compressed data passthrough -d do not compress (decompress) -i invert colors -u: set distance unit, 'i' for inch, 'm' for centimeter -x: set x resolution default -y: set y resolution default -w: width in units -l: length in units -r: 'd' for resolution default, 'o' for resolution override -p: paper size, eg "letter", "legal", "A4" -f set PDF "Fit Window" user preference -b set PDF "Interpolate" user preference -e: date, overrides image or current date/time default, YYYYMMDDHHMMSS -c: creator, overrides image software default -a: author, overrides image artist default -t: title, overrides image document name default -s: subject, overrides image image description default -k: keywords -h usage examples: tiff2pdf -o output.pdf input.tiff The above example would generate the file output.pdf from input.tiff. tiff2pdf input.tiff The above example would generate PDF output from input.tiff and write it to standard output. tiff2pdf -j -p letter -o output.pdf input.tiff The above example would generate the file output.pdf from input.tiff, putting the image pages on a letter sized page, compressing the output with JPEG. Please report bugs through: http://bugzilla.remotesensing.org/buglist.cgi?product=libtiff See also libtiff.3t, tiffcp. */ int tiff2pdf(TIFF *input, FILE *outputfile, int argc, const char **argv) { extern char *optarg; const char *outfilename = "<null>"; T2P *t2p = NULL; TIFF *output = NULL; int c; /* T2P */ t2p = t2p_init(); if (t2p == NULL){ TIFFError(TIFF2PDF_MODULE, "Can't initialize context"); goto fail; } /* Options */ while (argv && (c = getopt(argc, (char**)argv, "o:q:u:x:y:w:l:r:p:e:c:a:t:s:k:jzndifbh")) != -1) { switch (c) { case 'o': outfilename = optarg; break; #ifdef JPEG_SUPPORT case 'j': t2p->pdf_defaultcompression=T2P_COMPRESS_JPEG; break; #endif #ifdef ZIP_SUPPORT case 'z': t2p->pdf_defaultcompression=T2P_COMPRESS_ZIP; break; #endif case 'q': t2p->pdf_defaultcompressionquality=atoi(optarg); break; case 'n': t2p->pdf_nopassthrough=1; break; case 'd': t2p->pdf_defaultcompression=T2P_COMPRESS_NONE; break; case 'u': if(optarg[0]=='m'){ t2p->pdf_centimeters=1; } break; case 'x': t2p->pdf_defaultxres = (float)atof(optarg) / (t2p->pdf_centimeters?2.54F:1.0F); break; case 'y': t2p->pdf_defaultyres = (float)atof(optarg) / (t2p->pdf_centimeters?2.54F:1.0F); break; case 'w': t2p->pdf_overridepagesize=1; t2p->pdf_defaultpagewidth = ((float)atof(optarg) * 72.0F) / (t2p->pdf_centimeters?2.54F:1.0F); break; case 'l': t2p->pdf_overridepagesize=1; t2p->pdf_defaultpagelength = ((float)atof(optarg) * 72.0F) / (t2p->pdf_centimeters?2.54F:1.0F); break; case 'r': if(optarg[0]=='o'){ t2p->pdf_overrideres=1; } break; case 'p': if(tiff2pdf_match_paper_size(&(t2p->pdf_defaultpagewidth), &(t2p->pdf_defaultpagelength), optarg)){ t2p->pdf_overridepagesize=1; } else { TIFFWarning(TIFF2PDF_MODULE, "Unknown paper size %s, ignoring option", optarg); } break; case 'i': t2p->pdf_colorspace_invert=1; break; case 'f': t2p->pdf_fitwindow=1; break; case 'e': t2p->pdf_datetime = (char*)_TIFFmalloc(17); if(t2p->pdf_datetime){ if(strlen(optarg)==0){ t2p->pdf_datetime[0]=0; } else { if(strlen(optarg)>14){optarg[14]=0;} t2p->pdf_datetime[0]='D'; t2p->pdf_datetime[1]=':'; strcpy(&(t2p->pdf_datetime[2]), optarg); } } break; case 'c': t2p->pdf_creator = (char *)_TIFFmalloc(strlen(optarg) + 1); if(t2p->pdf_creator){ strcpy(t2p->pdf_creator, optarg); t2p->pdf_creator[strlen(optarg)]=0; } break; case 'a': t2p->pdf_author = (char *)_TIFFmalloc(strlen(optarg) + 1); if(t2p->pdf_author){ strcpy(t2p->pdf_author, optarg); t2p->pdf_author[strlen(optarg)]=0; } break; case 't': t2p->pdf_title= (char*)_TIFFmalloc(strlen(optarg)+1); if(t2p->pdf_title){ strcpy(t2p->pdf_title, optarg); t2p->pdf_title[strlen(optarg)]=0; } break; case 's': t2p->pdf_subject= (char*)_TIFFmalloc(strlen(optarg)+1); if(t2p->pdf_subject){ strcpy(t2p->pdf_subject, optarg); t2p->pdf_subject[strlen(optarg)]=0; } break; case 'k': t2p->pdf_keywords= (char*)_TIFFmalloc(strlen(optarg)+1); if(t2p->pdf_keywords){ strcpy(t2p->pdf_keywords, optarg); t2p->pdf_keywords[strlen(optarg)]=0; } break; case 'b': t2p->pdf_image_interpolate = 1; break; } } /* Output */ t2p->outputdisable = 0; t2p->outputfile = outputfile; output = TIFFClientOpen(outfilename, "w", (thandle_t) t2p, t2p_readproc, t2p_writeproc, t2p_seekproc, t2p_closeproc, t2p_sizeproc, t2p_mapproc, t2p_unmapproc ); if (output == NULL){ TIFFError(TIFF2PDF_MODULE, "Can't initialize output descriptor"); goto fail; } /* Validate */ t2p_validate(t2p); TIFFSeekFile(output, (toff_t) 0, SEEK_SET); /* Write */ t2p_write_pdf(t2p, input, output); if(t2p->t2p_error != 0){ TIFFError(TIFF2PDF_MODULE, "An error occurred creating output PDF file"); goto fail; } if (output != NULL) TIFFClose(output); if (t2p != NULL) t2p_free(t2p); return(EXIT_SUCCESS); fail: if (output != NULL) TIFFClose(output); if (t2p != NULL) t2p_free(t2p); return(EXIT_FAILURE); } static int tiff2pdf_match_paper_size(float* width, float* length, char* papersize) { int i=0; int len=0; const char* sizes[]={ "LETTER", "A4", "LEGAL", "EXECUTIVE", "LETTER", "LEGAL", "LEDGER", "TABLOID", "A", "B", "C", "D", "E", "F", "G", "H", "J", "K", "A10", "A9", "A8", "A7", "A6", "A5", "A4", "A3", "A2", "A1", "A0", "2A0", "4A0", "2A", "4A", "B10", "B9", "B8", "B7", "B6", "B5", "B4", "B3", "B2", "B1", "B0", "JISB10", "JISB9", "JISB8", "JISB7", "JISB6", "JISB5", "JISB4", "JISB3", "JISB2", "JISB1", "JISB0", "C10", "C9", "C8", "C7", "C6", "C5", "C4", "C3", "C2", "C1", "C0", "RA2", "RA1", "RA0", "SRA4", "SRA3", "SRA2", "SRA1", "SRA0", "A3EXTRA", "A4EXTRA", "STATEMENT", "FOLIO", "QUARTO", NULL } ; const int widths[]={ 612, 595, 612, 522, 612,612,792,792, 612,792,1224,1584,2448,2016,792,2016,2448,2880, 74,105,147,210,298,420,595,842,1191,1684,2384,3370,4768,3370,4768, 88,125,176,249,354,499,709,1001,1417,2004,2835, 91,128,181,258,363,516,729,1032,1460,2064,2920, 79,113,162,230,323,459,649,918,1298,1298,2599, 1219,1729,2438,638,907,1276,1814,2551, 914,667, 396, 612, 609, 0 }; const int lengths[]={ 792,842,1008, 756,792,1008,1224,1224, 792,1224,1584,2448,3168,2880,6480,10296,12672,10296, 105,147,210,298,420,595,842,1191,1684,2384,3370,4768,6741,4768,6741, 125,176,249,354,499,709,1001,1417,2004,2835,4008, 128,181,258,363,516,729,1032,1460,2064,2920,4127, 113,162,230,323,459,649,918,1298,1837,1837,3677, 1729,2438,3458,907,1276,1814,2551,3628, 1262,914, 612, 936, 780, 0 }; len=strlen(papersize); for(i=0;i<len;i++){ papersize[i]=toupper(papersize[i]); } for(i=0;sizes[i]!=NULL; i++){ if (strcmp( (const char*)papersize, sizes[i])==0){ *width=(float)widths[i]; *length=(float)lengths[i]; return(1); } } return(0); } /* -------------------------------------------------- * Tiff2Pdf proper with minor changes * -------------------------------------------------- */ /* This function allocates and initializes a T2P context struct pointer. */ static T2P* t2p_init() { T2P* t2p = (T2P*) _TIFFmalloc(sizeof(T2P)); if(t2p==NULL){ TIFFError( TIFF2PDF_MODULE, "Can't allocate %u bytes of memory for t2p_init", (int)sizeof(T2P)); return( (T2P*) NULL ); } _TIFFmemset(t2p, 0x00, sizeof(T2P)); t2p->pdf_majorversion=1; t2p->pdf_minorversion=1; t2p->pdf_defaultxres=300.0; t2p->pdf_defaultyres=300.0; t2p->pdf_defaultpagewidth=612.0; t2p->pdf_defaultpagelength=792.0; t2p->pdf_xrefcount=3; /* Catalog, Info, Pages */ t2p->outputfile = NULL; t2p->outputdisable = 0; t2p->outputwritten = 0; return(t2p); } /* This function frees a T2P context struct pointer and any allocated data fields of it. */ static void t2p_free(T2P* t2p){ int i=0; if(t2p != NULL){ if(t2p->pdf_xrefoffsets != NULL){ _TIFFfree( (tdata_t) t2p->pdf_xrefoffsets); } if(t2p->tiff_pages != NULL){ _TIFFfree( (tdata_t) t2p->tiff_pages); } for(i=0;i<t2p->tiff_pagecount;i++){ if(t2p->tiff_tiles[i].tiles_tiles != NULL){ _TIFFfree( (tdata_t) t2p->tiff_tiles[i].tiles_tiles); } } if(t2p->tiff_tiles != NULL){ _TIFFfree( (tdata_t) t2p->tiff_tiles); } if(t2p->pdf_palette != NULL){ _TIFFfree( (tdata_t) t2p->pdf_palette); } if(t2p->pdf_fileid != NULL){ _TIFFfree( (tdata_t) t2p->pdf_fileid); } if(t2p->pdf_datetime != NULL){ _TIFFfree( (tdata_t) t2p->pdf_datetime); } if(t2p->pdf_creator != NULL){ _TIFFfree( (tdata_t) t2p->pdf_creator); } if(t2p->pdf_author != NULL){ _TIFFfree( (tdata_t) t2p->pdf_author); } if(t2p->pdf_title != NULL){ _TIFFfree( (tdata_t) t2p->pdf_title); } if(t2p->pdf_subject != NULL){ _TIFFfree( (tdata_t) t2p->pdf_subject); } if(t2p->pdf_keywords != NULL){ _TIFFfree( (tdata_t) t2p->pdf_keywords); } #ifdef OJPEG_SUPPORT if(t2p->pdf_ojpegdata != NULL){ _TIFFfree( (tdata_t) t2p->pdf_ojpegdata); } #endif _TIFFfree( (tdata_t) t2p ); } return; } /* This function validates the values of a T2P context struct pointer before calling t2p_write_pdf with it. */ static void t2p_validate(T2P* t2p){ #ifdef JPEG_SUPPORT if(t2p->pdf_defaultcompression==T2P_COMPRESS_JPEG){ if(t2p->pdf_defaultcompressionquality<100 || t2p->pdf_defaultcompressionquality<1){ t2p->pdf_defaultcompressionquality=0; } } #endif #ifdef ZIP_SUPPORT if(t2p->pdf_defaultcompression==T2P_COMPRESS_ZIP){ switch (t2p->pdf_defaultcompressionquality){ case 1: case 10: case 11: case 12: case 13: case 14: case 15: case 101: case 110: case 111: case 112: case 113: case 114: case 115: case 201: case 210: case 211: case 212: case 213: case 214: case 215: case 301: case 310: case 311: case 312: case 313: case 314: case 315: case 401: case 410: case 411: case 412: case 413: case 414: case 415: case 501: case 510: case 511: case 512: case 513: case 514: case 515: case 601: case 610: case 611: case 612: case 613: case 614: case 615: case 701: case 710: case 711: case 712: case 713: case 714: case 715: case 801: case 810: case 811: case 812: case 813: case 814: case 815: case 901: case 910: case 911: case 912: case 913: case 914: case 915: break; default: t2p->pdf_defaultcompressionquality=0; } if(t2p->pdf_defaultcompressionquality%100 !=0){ TIFFError( TIFF2PDF_MODULE, "PNG Group predictor differencing not implemented, assuming compression quality %u", t2p->pdf_defaultcompressionquality); } t2p->pdf_defaultcompressionquality%=100; if(t2p->pdf_minorversion<2){t2p->pdf_minorversion=2;} } #endif (void)0; return; } /* This function scans the input TIFF file for pages. It attempts to determine which IFD's of the TIFF file contain image document pages. For each, it gathers some information that has to do with the output of the PDF document as a whole. */ static void t2p_read_tiff_init(T2P* t2p, TIFF* input){ tdir_t directorycount=0; tdir_t i=0; uint16 pagen=0; uint16 paged=0; uint16 xuint16=0; directorycount=TIFFNumberOfDirectories(input); t2p->tiff_pages = (T2P_PAGE*) _TIFFmalloc(directorycount * sizeof(T2P_PAGE)); if(t2p->tiff_pages==NULL){ TIFFError( TIFF2PDF_MODULE, "Can't allocate %u bytes of memory for tiff_pages array, %s", directorycount * (int)sizeof(T2P_PAGE), TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } _TIFFmemset( t2p->tiff_pages, 0x00, directorycount * sizeof(T2P_PAGE)); t2p->tiff_tiles = (T2P_TILES*) _TIFFmalloc(directorycount * sizeof(T2P_TILES)); if(t2p->tiff_tiles==NULL){ TIFFError( TIFF2PDF_MODULE, "Can't allocate %u bytes of memory for tiff_tiles array, %s", directorycount * (int)sizeof(T2P_TILES), TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } _TIFFmemset( t2p->tiff_tiles, 0x00, directorycount * sizeof(T2P_TILES)); for(i=0;i<directorycount;i++){ uint32 subfiletype = 0; if(!TIFFSetDirectory(input, i)){ TIFFError( TIFF2PDF_MODULE, "Can't set directory %u of input file %s", i, TIFFFileName(input)); return; } if(TIFFGetField(input, TIFFTAG_PAGENUMBER, &pagen, &paged)){ if((pagen>paged) && (paged != 0)){ t2p->tiff_pages[t2p->tiff_pagecount].page_number = paged; } else { t2p->tiff_pages[t2p->tiff_pagecount].page_number = pagen; } goto ispage2; } if(TIFFGetField(input, TIFFTAG_SUBFILETYPE, &subfiletype)){ if ( ((subfiletype & FILETYPE_PAGE) != 0) || (subfiletype == 0)){ goto ispage; } else { goto isnotpage; } } if(TIFFGetField(input, TIFFTAG_OSUBFILETYPE, &subfiletype)){ if ((subfiletype == OFILETYPE_IMAGE) || (subfiletype == OFILETYPE_PAGE) || (subfiletype == 0) ){ goto ispage; } else { goto isnotpage; } } ispage: t2p->tiff_pages[t2p->tiff_pagecount].page_number=t2p->tiff_pagecount; ispage2: t2p->tiff_pages[t2p->tiff_pagecount].page_directory=i; if(TIFFIsTiled(input)){ t2p->tiff_pages[t2p->tiff_pagecount].page_tilecount = TIFFNumberOfTiles(input); } t2p->tiff_pagecount++; isnotpage: (void)0; } qsort((void*) t2p->tiff_pages, t2p->tiff_pagecount, sizeof(T2P_PAGE), t2p_cmp_t2p_page); for(i=0;i<t2p->tiff_pagecount;i++){ t2p->pdf_xrefcount += 5; TIFFSetDirectory(input, t2p->tiff_pages[i].page_directory ); if((TIFFGetField(input, TIFFTAG_PHOTOMETRIC, &xuint16) && (xuint16==PHOTOMETRIC_PALETTE)) || TIFFGetField(input, TIFFTAG_INDEXED, &xuint16)) { t2p->tiff_pages[i].page_extra++; t2p->pdf_xrefcount++; } #ifdef ZIP_SUPPORT if (TIFFGetField(input, TIFFTAG_COMPRESSION, &xuint16)) { if( (xuint16== COMPRESSION_DEFLATE || xuint16== COMPRESSION_ADOBE_DEFLATE) && ((t2p->tiff_pages[i].page_tilecount != 0) || TIFFNumberOfStrips(input)==1) && (t2p->pdf_nopassthrough==0) ){ if(t2p->pdf_minorversion<2){t2p->pdf_minorversion=2;} } } #endif if (TIFFGetField(input, TIFFTAG_TRANSFERFUNCTION, &(t2p->tiff_transferfunction[0]), &(t2p->tiff_transferfunction[1]), &(t2p->tiff_transferfunction[2]))) { if(t2p->tiff_transferfunction[1] != t2p->tiff_transferfunction[0]) { t2p->tiff_transferfunctioncount = 3; t2p->tiff_pages[i].page_extra += 4; t2p->pdf_xrefcount += 4; } else { t2p->tiff_transferfunctioncount = 1; t2p->tiff_pages[i].page_extra += 2; t2p->pdf_xrefcount += 2; } if(t2p->pdf_minorversion < 2) t2p->pdf_minorversion = 2; } else { t2p->tiff_transferfunctioncount=0; } if( TIFFGetField( input, TIFFTAG_ICCPROFILE, &(t2p->tiff_iccprofilelength), &(t2p->tiff_iccprofile)) != 0){ t2p->tiff_pages[i].page_extra++; t2p->pdf_xrefcount++; if(t2p->pdf_minorversion<3){t2p->pdf_minorversion=3;} } t2p->tiff_tiles[i].tiles_tilecount= t2p->tiff_pages[i].page_tilecount; if( (TIFFGetField(input, TIFFTAG_PLANARCONFIG, &xuint16) != 0) && (xuint16 == PLANARCONFIG_SEPARATE ) ){ TIFFGetField(input, TIFFTAG_SAMPLESPERPIXEL, &xuint16); t2p->tiff_tiles[i].tiles_tilecount/= xuint16; } if( t2p->tiff_tiles[i].tiles_tilecount > 0){ t2p->pdf_xrefcount += (t2p->tiff_tiles[i].tiles_tilecount -1)*2; TIFFGetField(input, TIFFTAG_TILEWIDTH, &( t2p->tiff_tiles[i].tiles_tilewidth) ); TIFFGetField(input, TIFFTAG_TILELENGTH, &( t2p->tiff_tiles[i].tiles_tilelength) ); t2p->tiff_tiles[i].tiles_tiles = (T2P_TILE*) _TIFFmalloc( t2p->tiff_tiles[i].tiles_tilecount * sizeof(T2P_TILE) ); if( t2p->tiff_tiles[i].tiles_tiles == NULL){ TIFFError( TIFF2PDF_MODULE, "Can't allocate %u bytes of memory for t2p_read_tiff_init, %s", t2p->tiff_tiles[i].tiles_tilecount * (int)sizeof(T2P_TILE), TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } } } return; } /* This function is used by qsort to sort a T2P_PAGE* array of page structures by page number. */ static int t2p_cmp_t2p_page(const void* e1, const void* e2){ return( ((T2P_PAGE*)e1)->page_number - ((T2P_PAGE*)e2)->page_number ); } /* This function sets the input directory to the directory of a given page and determines information about the image. It checks the image characteristics to determine if it is possible to convert the image data into a page of PDF output, setting values of the T2P struct for this page. It determines what color space is used in the output PDF to represent the image. It determines if the image can be converted as raw data without requiring transcoding of the image data. */ static void t2p_read_tiff_data(T2P* t2p, TIFF* input){ int i=0; uint16* r; uint16* g; uint16* b; uint16* a; uint16 xuint16; uint16* xuint16p; float* xfloatp; t2p->pdf_transcode = T2P_TRANSCODE_ENCODE; t2p->pdf_sample = T2P_SAMPLE_NOTHING; t2p->pdf_switchdecode = t2p->pdf_colorspace_invert; TIFFSetDirectory(input, t2p->tiff_pages[t2p->pdf_page].page_directory); TIFFGetField(input, TIFFTAG_IMAGEWIDTH, &(t2p->tiff_width)); if(t2p->tiff_width == 0){ TIFFError( TIFF2PDF_MODULE, "No support for %s with zero width", TIFFFileName(input) ); t2p->t2p_error = T2P_ERR_ERROR; return; } TIFFGetField(input, TIFFTAG_IMAGELENGTH, &(t2p->tiff_length)); if(t2p->tiff_length == 0){ TIFFError( TIFF2PDF_MODULE, "No support for %s with zero length", TIFFFileName(input) ); t2p->t2p_error = T2P_ERR_ERROR; return; } if(TIFFGetField(input, TIFFTAG_COMPRESSION, &(t2p->tiff_compression)) == 0){ TIFFError( TIFF2PDF_MODULE, "No support for %s with no compression tag", TIFFFileName(input) ); t2p->t2p_error = T2P_ERR_ERROR; return; } if( TIFFIsCODECConfigured(t2p->tiff_compression) == 0){ TIFFError( TIFF2PDF_MODULE, "No support for %s with compression type %u: not configured", TIFFFileName(input), t2p->tiff_compression ); t2p->t2p_error = T2P_ERR_ERROR; return; } TIFFGetFieldDefaulted(input, TIFFTAG_BITSPERSAMPLE, &(t2p->tiff_bitspersample)); switch(t2p->tiff_bitspersample){ case 1: case 2: case 4: case 8: break; case 0: TIFFWarning( TIFF2PDF_MODULE, "Image %s has 0 bits per sample, assuming 1", TIFFFileName(input)); t2p->tiff_bitspersample=1; break; default: TIFFError( TIFF2PDF_MODULE, "No support for %s with %u bits per sample", TIFFFileName(input), t2p->tiff_bitspersample); t2p->t2p_error = T2P_ERR_ERROR; return; } TIFFGetFieldDefaulted(input, TIFFTAG_SAMPLESPERPIXEL, &(t2p->tiff_samplesperpixel)); if(t2p->tiff_samplesperpixel>4){ TIFFError( TIFF2PDF_MODULE, "No support for %s with %u samples per pixel", TIFFFileName(input), t2p->tiff_samplesperpixel); t2p->t2p_error = T2P_ERR_ERROR; return; } if(t2p->tiff_samplesperpixel==0){ TIFFWarning( TIFF2PDF_MODULE, "Image %s has 0 samples per pixel, assuming 1", TIFFFileName(input)); t2p->tiff_samplesperpixel=1; } if(TIFFGetField(input, TIFFTAG_SAMPLEFORMAT, &xuint16) != 0 ){ switch(xuint16){ case 0: case 1: case 4: break; default: TIFFError( TIFF2PDF_MODULE, "No support for %s with sample format %u", TIFFFileName(input), xuint16); t2p->t2p_error = T2P_ERR_ERROR; return; break; } } TIFFGetFieldDefaulted(input, TIFFTAG_FILLORDER, &(t2p->tiff_fillorder)); if(TIFFGetField(input, TIFFTAG_PHOTOMETRIC, &(t2p->tiff_photometric)) == 0){ TIFFError( TIFF2PDF_MODULE, "No support for %s with no photometric interpretation tag", TIFFFileName(input) ); t2p->t2p_error = T2P_ERR_ERROR; return; } switch(t2p->tiff_photometric){ case PHOTOMETRIC_MINISWHITE: case PHOTOMETRIC_MINISBLACK: if (t2p->tiff_bitspersample==1){ t2p->pdf_colorspace=T2P_CS_BILEVEL; if(t2p->tiff_photometric==PHOTOMETRIC_MINISWHITE){ t2p->pdf_switchdecode ^= 1; } } else { t2p->pdf_colorspace=T2P_CS_GRAY; if(t2p->tiff_photometric==PHOTOMETRIC_MINISWHITE){ t2p->pdf_switchdecode ^= 1; } } break; case PHOTOMETRIC_RGB: t2p->pdf_colorspace=T2P_CS_RGB; if(t2p->tiff_samplesperpixel == 3){ break; } if(TIFFGetField(input, TIFFTAG_INDEXED, &xuint16)){ if(xuint16==1) goto photometric_palette; } if(t2p->tiff_samplesperpixel > 3) { if(t2p->tiff_samplesperpixel == 4) { t2p->pdf_colorspace = T2P_CS_RGB; if(TIFFGetField(input, TIFFTAG_EXTRASAMPLES, &xuint16, &xuint16p) && xuint16 == 1) { if(xuint16p[0] == EXTRASAMPLE_ASSOCALPHA){ t2p->pdf_sample=T2P_SAMPLE_RGBAA_TO_RGB; break; } if(xuint16p[0] == EXTRASAMPLE_UNASSALPHA){ t2p->pdf_sample=T2P_SAMPLE_RGBA_TO_RGB; break; } TIFFWarning( TIFF2PDF_MODULE, "RGB image %s has 4 samples per pixel, assuming RGBA", TIFFFileName(input)); break; } t2p->pdf_colorspace=T2P_CS_CMYK; t2p->pdf_switchdecode ^= 1; TIFFWarning( TIFF2PDF_MODULE, "RGB image %s has 4 samples per pixel, assuming inverse CMYK", TIFFFileName(input)); break; } else { TIFFError( TIFF2PDF_MODULE, "No support for RGB image %s with %u samples per pixel", TIFFFileName(input), t2p->tiff_samplesperpixel); t2p->t2p_error = T2P_ERR_ERROR; break; } } else { TIFFError( TIFF2PDF_MODULE, "No support for RGB image %s with %u samples per pixel", TIFFFileName(input), t2p->tiff_samplesperpixel); t2p->t2p_error = T2P_ERR_ERROR; break; } case PHOTOMETRIC_PALETTE: photometric_palette: if(t2p->tiff_samplesperpixel!=1){ TIFFError( TIFF2PDF_MODULE, "No support for palettized image %s with not one sample per pixel", TIFFFileName(input) ); t2p->t2p_error = T2P_ERR_ERROR; return; } t2p->pdf_colorspace=T2P_CS_RGB | T2P_CS_PALETTE; t2p->pdf_palettesize=0x0001<<t2p->tiff_bitspersample; if(!TIFFGetField(input, TIFFTAG_COLORMAP, &r, &g, &b)){ TIFFError( TIFF2PDF_MODULE, "Palettized image %s has no color map", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } if(t2p->pdf_palette != NULL){ _TIFFfree(t2p->pdf_palette); t2p->pdf_palette=NULL; } t2p->pdf_palette = (unsigned char*) _TIFFmalloc(t2p->pdf_palettesize*3); if(t2p->pdf_palette==NULL){ TIFFError( TIFF2PDF_MODULE, "Can't allocate %u bytes of memory for t2p_read_tiff_image, %s", t2p->pdf_palettesize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } for(i=0;i<t2p->pdf_palettesize;i++){ t2p->pdf_palette[(i*3)] = (unsigned char) (r[i]>>8); t2p->pdf_palette[(i*3)+1]= (unsigned char) (g[i]>>8); t2p->pdf_palette[(i*3)+2]= (unsigned char) (b[i]>>8); } t2p->pdf_palettesize *= 3; break; case PHOTOMETRIC_SEPARATED: if(TIFFGetField(input, TIFFTAG_INDEXED, &xuint16)){ if(xuint16==1){ goto photometric_palette_cmyk; } } if( TIFFGetField(input, TIFFTAG_INKSET, &xuint16) ){ if(xuint16 != INKSET_CMYK){ TIFFError( TIFF2PDF_MODULE, "No support for %s because its inkset is not CMYK", TIFFFileName(input) ); t2p->t2p_error = T2P_ERR_ERROR; return; } } if(t2p->tiff_samplesperpixel==4){ t2p->pdf_colorspace=T2P_CS_CMYK; } else { TIFFError( TIFF2PDF_MODULE, "No support for %s because it has %u samples per pixel", TIFFFileName(input), t2p->tiff_samplesperpixel); t2p->t2p_error = T2P_ERR_ERROR; return; } break; photometric_palette_cmyk: if(t2p->tiff_samplesperpixel!=1){ TIFFError( TIFF2PDF_MODULE, "No support for palettized CMYK image %s with not one sample per pixel", TIFFFileName(input) ); t2p->t2p_error = T2P_ERR_ERROR; return; } t2p->pdf_colorspace=T2P_CS_CMYK | T2P_CS_PALETTE; t2p->pdf_palettesize=0x0001<<t2p->tiff_bitspersample; if(!TIFFGetField(input, TIFFTAG_COLORMAP, &r, &g, &b, &a)){ TIFFError( TIFF2PDF_MODULE, "Palettized image %s has no color map", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } if(t2p->pdf_palette != NULL){ _TIFFfree(t2p->pdf_palette); t2p->pdf_palette=NULL; } t2p->pdf_palette = (unsigned char*) _TIFFmalloc(t2p->pdf_palettesize*4); if(t2p->pdf_palette==NULL){ TIFFError( TIFF2PDF_MODULE, "Can't allocate %u bytes of memory for t2p_read_tiff_image, %s", t2p->pdf_palettesize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } for(i=0;i<t2p->pdf_palettesize;i++){ t2p->pdf_palette[(i*4)] = (unsigned char) (r[i]>>8); t2p->pdf_palette[(i*4)+1]= (unsigned char) (g[i]>>8); t2p->pdf_palette[(i*4)+2]= (unsigned char) (b[i]>>8); t2p->pdf_palette[(i*4)+2]= (unsigned char) (a[i]>>8); } t2p->pdf_palettesize *= 4; break; case PHOTOMETRIC_YCBCR: t2p->pdf_colorspace=T2P_CS_RGB; if(t2p->tiff_samplesperpixel==1){ t2p->pdf_colorspace=T2P_CS_GRAY; t2p->tiff_photometric=PHOTOMETRIC_MINISBLACK; break; } t2p->pdf_sample=T2P_SAMPLE_YCBCR_TO_RGB; #ifdef JPEG_SUPPORT if(t2p->pdf_defaultcompression==T2P_COMPRESS_JPEG){ t2p->pdf_sample=T2P_SAMPLE_NOTHING; } #endif break; case PHOTOMETRIC_CIELAB: t2p->pdf_labrange[0]= -127; t2p->pdf_labrange[1]= 127; t2p->pdf_labrange[2]= -127; t2p->pdf_labrange[3]= 127; t2p->pdf_sample=T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED; t2p->pdf_colorspace=T2P_CS_LAB; break; case PHOTOMETRIC_ICCLAB: t2p->pdf_labrange[0]= 0; t2p->pdf_labrange[1]= 255; t2p->pdf_labrange[2]= 0; t2p->pdf_labrange[3]= 255; t2p->pdf_colorspace=T2P_CS_LAB; break; case PHOTOMETRIC_ITULAB: t2p->pdf_labrange[0]=-85; t2p->pdf_labrange[1]=85; t2p->pdf_labrange[2]=-75; t2p->pdf_labrange[3]=124; t2p->pdf_sample=T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED; t2p->pdf_colorspace=T2P_CS_LAB; break; case PHOTOMETRIC_LOGL: case PHOTOMETRIC_LOGLUV: TIFFError( TIFF2PDF_MODULE, "No support for %s with photometric interpretation LogL/LogLuv", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; default: TIFFError( TIFF2PDF_MODULE, "No support for %s with photometric interpretation %u", TIFFFileName(input), t2p->tiff_photometric); t2p->t2p_error = T2P_ERR_ERROR; return; } if(TIFFGetField(input, TIFFTAG_PLANARCONFIG, &(t2p->tiff_planar))){ switch(t2p->tiff_planar){ case 0: TIFFWarning( TIFF2PDF_MODULE, "Image %s has planar configuration 0, assuming 1", TIFFFileName(input)); t2p->tiff_planar=PLANARCONFIG_CONTIG; case PLANARCONFIG_CONTIG: break; case PLANARCONFIG_SEPARATE: t2p->pdf_sample=T2P_SAMPLE_PLANAR_SEPARATE_TO_CONTIG; if(t2p->tiff_bitspersample!=8){ TIFFError( TIFF2PDF_MODULE, "No support for %s with separated planar configuration and %u bits per sample", TIFFFileName(input), t2p->tiff_bitspersample); t2p->t2p_error = T2P_ERR_ERROR; return; } break; default: TIFFError( TIFF2PDF_MODULE, "No support for %s with planar configuration %u", TIFFFileName(input), t2p->tiff_planar); t2p->t2p_error = T2P_ERR_ERROR; return; } } TIFFGetFieldDefaulted(input, TIFFTAG_ORIENTATION, &(t2p->tiff_orientation)); if(t2p->tiff_orientation>8){ TIFFWarning(TIFF2PDF_MODULE, "Image %s has orientation %u, assuming 0", TIFFFileName(input), t2p->tiff_orientation); t2p->tiff_orientation=0; } if(TIFFGetField(input, TIFFTAG_XRESOLUTION, &(t2p->tiff_xres) ) == 0){ t2p->tiff_xres=0.0; } if(TIFFGetField(input, TIFFTAG_YRESOLUTION, &(t2p->tiff_yres) ) == 0){ t2p->tiff_yres=0.0; } TIFFGetFieldDefaulted(input, TIFFTAG_RESOLUTIONUNIT, &(t2p->tiff_resunit) ); if(t2p->tiff_resunit==RESUNIT_CENTIMETER){ t2p->tiff_xres*=2.54F; t2p->tiff_yres*=2.54F; } else if (t2p->tiff_resunit!=RESUNIT_INCH && t2p->pdf_centimeters!=0){ t2p->tiff_xres*=2.54F; t2p->tiff_yres*=2.54F; } t2p_compose_pdf_page(t2p); t2p->pdf_transcode = T2P_TRANSCODE_ENCODE; if(t2p->pdf_nopassthrough==0){ #ifdef CCITT_SUPPORT if(t2p->tiff_compression==COMPRESSION_CCITTFAX4 ){ if(TIFFIsTiled(input) || (TIFFNumberOfStrips(input)==1) ){ t2p->pdf_transcode = T2P_TRANSCODE_RAW; t2p->pdf_compression=T2P_COMPRESS_G4; } } #endif #ifdef ZIP_SUPPORT if(t2p->tiff_compression== COMPRESSION_ADOBE_DEFLATE || t2p->tiff_compression==COMPRESSION_DEFLATE){ if(TIFFIsTiled(input) || (TIFFNumberOfStrips(input)==1) ){ t2p->pdf_transcode = T2P_TRANSCODE_RAW; t2p->pdf_compression=T2P_COMPRESS_ZIP; } } #endif #ifdef OJPEG_SUPPORT if(t2p->tiff_compression==COMPRESSION_OJPEG){ t2p->pdf_transcode = T2P_TRANSCODE_RAW; t2p->pdf_compression=T2P_COMPRESS_JPEG; t2p_process_ojpeg_tables(t2p, input); } #endif #ifdef JPEG_SUPPORT if(t2p->tiff_compression==COMPRESSION_JPEG){ t2p->pdf_transcode = T2P_TRANSCODE_RAW; t2p->pdf_compression=T2P_COMPRESS_JPEG; } #endif (void)0; } if(t2p->pdf_transcode!=T2P_TRANSCODE_RAW){ t2p->pdf_compression = t2p->pdf_defaultcompression; } #ifdef JPEG_SUPPORT if(t2p->pdf_defaultcompression==T2P_COMPRESS_JPEG){ if(t2p->pdf_colorspace & T2P_CS_PALETTE){ t2p->pdf_sample|=T2P_SAMPLE_REALIZE_PALETTE; t2p->pdf_colorspace ^= T2P_CS_PALETTE; t2p->tiff_pages[t2p->pdf_page].page_extra--; } } if(t2p->tiff_compression==COMPRESSION_JPEG){ if(t2p->tiff_planar==PLANARCONFIG_SEPARATE){ TIFFError( TIFF2PDF_MODULE, "No support for %s with JPEG compression and separated planar configuration", TIFFFileName(input)); t2p->t2p_error=T2P_ERR_ERROR; return; } } #endif #ifdef OJPEG_SUPPORT if(t2p->tiff_compression==COMPRESSION_OJPEG){ if(t2p->tiff_planar==PLANARCONFIG_SEPARATE){ TIFFError( TIFF2PDF_MODULE, "No support for %s with OJPEG compression and separated planar configuration", TIFFFileName(input)); t2p->t2p_error=T2P_ERR_ERROR; return; } } #endif if(t2p->pdf_sample & T2P_SAMPLE_REALIZE_PALETTE){ if(t2p->pdf_colorspace & T2P_CS_CMYK){ t2p->tiff_samplesperpixel=4; t2p->tiff_photometric=PHOTOMETRIC_SEPARATED; } else { t2p->tiff_samplesperpixel=3; t2p->tiff_photometric=PHOTOMETRIC_RGB; } } if (TIFFGetField(input, TIFFTAG_TRANSFERFUNCTION, &(t2p->tiff_transferfunction[0]), &(t2p->tiff_transferfunction[1]), &(t2p->tiff_transferfunction[2]))) { if(t2p->tiff_transferfunction[1] != t2p->tiff_transferfunction[0]) { t2p->tiff_transferfunctioncount=3; } else { t2p->tiff_transferfunctioncount=1; } } else { t2p->tiff_transferfunctioncount=0; } if(TIFFGetField(input, TIFFTAG_WHITEPOINT, &xfloatp)!=0){ t2p->tiff_whitechromaticities[0]=xfloatp[0]; t2p->tiff_whitechromaticities[1]=xfloatp[1]; if(t2p->pdf_colorspace & T2P_CS_GRAY){ t2p->pdf_colorspace |= T2P_CS_CALGRAY; } if(t2p->pdf_colorspace & T2P_CS_RGB){ t2p->pdf_colorspace |= T2P_CS_CALRGB; } } if(TIFFGetField(input, TIFFTAG_PRIMARYCHROMATICITIES, &xfloatp)!=0){ t2p->tiff_primarychromaticities[0]=xfloatp[0]; t2p->tiff_primarychromaticities[1]=xfloatp[1]; t2p->tiff_primarychromaticities[2]=xfloatp[2]; t2p->tiff_primarychromaticities[3]=xfloatp[3]; t2p->tiff_primarychromaticities[4]=xfloatp[4]; t2p->tiff_primarychromaticities[5]=xfloatp[5]; if(t2p->pdf_colorspace & T2P_CS_RGB){ t2p->pdf_colorspace |= T2P_CS_CALRGB; } } if(t2p->pdf_colorspace & T2P_CS_LAB){ if(TIFFGetField(input, TIFFTAG_WHITEPOINT, &xfloatp) != 0){ t2p->tiff_whitechromaticities[0]=xfloatp[0]; t2p->tiff_whitechromaticities[1]=xfloatp[1]; } else { t2p->tiff_whitechromaticities[0]=0.3457F; /* 0.3127F; */ t2p->tiff_whitechromaticities[1]=0.3585F; /* 0.3290F; */ } } if(TIFFGetField(input, TIFFTAG_ICCPROFILE, &(t2p->tiff_iccprofilelength), &(t2p->tiff_iccprofile))!=0){ t2p->pdf_colorspace |= T2P_CS_ICCBASED; } else { t2p->tiff_iccprofilelength=0; t2p->tiff_iccprofile=NULL; } #ifdef CCITT_SUPPORT if( t2p->tiff_bitspersample==1 && t2p->tiff_samplesperpixel==1){ t2p->pdf_compression = T2P_COMPRESS_G4; } #endif return; } /* This function returns the necessary size of a data buffer to contain the raw or uncompressed image data from the input TIFF for a page. */ static void t2p_read_tiff_size(T2P* t2p, TIFF* input){ uint32* sbc=NULL; #if defined(JPEG_SUPPORT) || defined (OJPEG_SUPPORT) unsigned char* jpt=NULL; uint32 xuint32=0; tstrip_t i=0; tstrip_t stripcount=0; #endif #ifdef OJPEG_SUPPORT tsize_t k = 0; #endif if(t2p->pdf_transcode == T2P_TRANSCODE_RAW){ #ifdef CCITT_SUPPORT if(t2p->pdf_compression == T2P_COMPRESS_G4 ){ TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc); t2p->tiff_datasize=sbc[0]; return; } #endif #ifdef ZIP_SUPPORT if(t2p->pdf_compression == T2P_COMPRESS_ZIP){ TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc); t2p->tiff_datasize=sbc[0]; return; } #endif #ifdef OJPEG_SUPPORT if(t2p->tiff_compression == COMPRESSION_OJPEG){ if(!TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc)){ TIFFError(TIFF2PDF_MODULE, "Input file %s missing field: TIFFTAG_STRIPBYTECOUNTS", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } stripcount=TIFFNumberOfStrips(input); for(i=0;i<stripcount;i++){ k += sbc[i]; } if(TIFFGetField(input, TIFFTAG_JPEGIFOFFSET, &(t2p->tiff_dataoffset))){ if(t2p->tiff_dataoffset != 0){ if(TIFFGetField(input, TIFFTAG_JPEGIFBYTECOUNT, &(t2p->tiff_datasize))!=0){ if(t2p->tiff_datasize < k) { t2p->pdf_ojpegiflength=t2p->tiff_datasize; t2p->tiff_datasize+=k; t2p->tiff_datasize+=6; t2p->tiff_datasize+=2*stripcount; TIFFWarning(TIFF2PDF_MODULE, "Input file %s has short JPEG interchange file byte count", TIFFFileName(input)); return; } return; }else { TIFFError(TIFF2PDF_MODULE, "Input file %s missing field: TIFFTAG_JPEGIFBYTECOUNT", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } } } t2p->tiff_datasize+=k; t2p->tiff_datasize+=2*stripcount; t2p->tiff_datasize+=2048; return; } #endif #ifdef JPEG_SUPPORT if(t2p->tiff_compression == COMPRESSION_JPEG){ t2p->tiff_datasize = 2048; /* safety margin (actually used!) */ if(TIFFGetField(input, TIFFTAG_JPEGTABLES, &xuint32, &jpt) != 0 ){ if(xuint32>4){ t2p->tiff_datasize+= xuint32; t2p->tiff_datasize -=2; /* don't use EOI of header */ } } else { t2p->tiff_datasize=2; /* SOI for first strip */ } stripcount=TIFFNumberOfStrips(input); if(!TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc)){ TIFFError(TIFF2PDF_MODULE, "Input file %s missing field: TIFFTAG_STRIPBYTECOUNTS", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return; } for(i=0;i<stripcount;i++){ t2p->tiff_datasize += sbc[i]; t2p->tiff_datasize -=4; /* don't use SOI or EOI of strip */ } t2p->tiff_datasize +=2; /* use EOI of last strip */ return; } #endif (void) 0; } t2p->tiff_datasize=TIFFScanlineSize(input) * t2p->tiff_length; if(t2p->tiff_planar==PLANARCONFIG_SEPARATE){ t2p->tiff_datasize*= t2p->tiff_samplesperpixel; } return; } /* This function returns the necessary size of a data buffer to contain the raw or uncompressed image data from the input TIFF for a tile of a page. */ static void t2p_read_tiff_size_tile(T2P* t2p, TIFF* input, ttile_t tile){ uint32* tbc = NULL; uint16 edge=0; #ifdef JPEG_SUPPORT uint32 xuint32=0; unsigned char* jpt; #endif edge |= t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile); edge |= t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile); if(t2p->pdf_transcode==T2P_TRANSCODE_RAW){ if(edge #if defined(JPEG_SUPPORT) || defined(OJPEG_SUPPORT) && !(t2p->pdf_compression==T2P_COMPRESS_JPEG) #endif ){ t2p->tiff_datasize=TIFFTileSize(input); return; } else { TIFFGetField(input, TIFFTAG_TILEBYTECOUNTS, &tbc); t2p->tiff_datasize=tbc[tile]; #ifdef OJPEG_SUPPORT if(t2p->tiff_compression==COMPRESSION_OJPEG){ t2p->tiff_datasize+=2048; return; } #endif #ifdef JPEG_SUPPORT if(t2p->tiff_compression==COMPRESSION_JPEG){ if(TIFFGetField(input, TIFFTAG_JPEGTABLES, &xuint32, &jpt)!=0){ if(xuint32>4){ t2p->tiff_datasize+=xuint32; t2p->tiff_datasize-=4; /* don't use EOI of header or SOI of tile */ } } } #endif return; } } t2p->tiff_datasize=TIFFTileSize(input); if(t2p->tiff_planar==PLANARCONFIG_SEPARATE){ t2p->tiff_datasize*= t2p->tiff_samplesperpixel; } return; } /* This functions returns a non-zero value when the tile is on the right edge and does not have full imaged tile width. */ static int t2p_tile_is_right_edge(T2P_TILES tiles, ttile_t tile){ if( ((tile+1) % tiles.tiles_tilecountx == 0) && (tiles.tiles_edgetilewidth != 0) ){ return(1); } else { return(0); } return(0); } /* This functions returns a non-zero value when the tile is on the bottom edge and does not have full imaged tile length. */ static int t2p_tile_is_bottom_edge(T2P_TILES tiles, ttile_t tile){ if( ((tile+1) > (tiles.tiles_tilecount-tiles.tiles_tilecountx) ) && (tiles.tiles_edgetilelength != 0) ){ return(1); } else { return(0); } return(0); } /* This function reads the raster image data from the input TIFF for an image and writes the data to the output PDF XObject image dictionary stream. It returns the amount written or zero on error. */ static tsize_t t2p_readwrite_pdf_image(T2P* t2p, TIFF* input, TIFF* output){ tsize_t written=0; unsigned char* buffer=NULL; unsigned char* samplebuffer=NULL; tsize_t bufferoffset=0; tsize_t samplebufferoffset=0; tsize_t read=0; tstrip_t i=0; tstrip_t j=0; tstrip_t stripcount=0; tsize_t stripsize=0; tsize_t sepstripcount=0; tsize_t sepstripsize=0; #ifdef OJPEG_SUPPORT toff_t inputoffset=0; uint16 h_samp=1; uint16 v_samp=1; uint16 ri=1; uint32 rows=0; #endif #ifdef JPEG_SUPPORT unsigned char* jpt; uint32 xuint32=0; uint16 xuint16_1=0; uint16 xuint16_2=0; float* xfloatp; uint32* sbc; unsigned char* stripbuffer; tsize_t striplength=0; uint32 max_striplength=0; #endif if(t2p->pdf_transcode == T2P_TRANSCODE_RAW){ #ifdef CCITT_SUPPORT if(t2p->pdf_compression == T2P_COMPRESS_G4){ buffer= (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s", t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } TIFFReadRawStrip(input, 0, (tdata_t) buffer, t2p->tiff_datasize); if (t2p->tiff_fillorder==FILLORDER_LSB2MSB){ /* make sure is lsb-to-msb bit-endianness fill order */ TIFFReverseBits(buffer, t2p->tiff_datasize); } TIFFWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize); _TIFFfree(buffer); return(t2p->tiff_datasize); } #endif #ifdef ZIP_SUPPORT if(t2p->pdf_compression == T2P_COMPRESS_ZIP){ buffer= (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); memset(buffer, 0, t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s", t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } TIFFReadRawStrip(input, 0, (tdata_t) buffer, t2p->tiff_datasize); if (t2p->tiff_fillorder==FILLORDER_LSB2MSB){ TIFFReverseBits(buffer, t2p->tiff_datasize); } TIFFWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize); _TIFFfree(buffer); return(t2p->tiff_datasize); } #endif #ifdef OJPEG_SUPPORT if(t2p->tiff_compression == COMPRESSION_OJPEG){ if(t2p->tiff_dataoffset != 0){ buffer= (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); memset(buffer, 0, t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s", t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } if(t2p->pdf_ojpegiflength==0){ inputoffset=TIFFSeekFile(input, 0, SEEK_CUR); TIFFSeekFile(input, t2p->tiff_dataoffset, SEEK_SET); TIFFReadFile(input, (tdata_t) buffer, t2p->tiff_datasize); TIFFSeekFile(input, inputoffset, SEEK_SET); TIFFWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize); _TIFFfree(buffer); return(t2p->tiff_datasize); } else { inputoffset=TIFFSeekFile(input, 0, SEEK_CUR); TIFFSeekFile(input, t2p->tiff_dataoffset, SEEK_SET); bufferoffset=TIFFReadFile(input, (tdata_t) buffer, t2p->pdf_ojpegiflength); t2p->pdf_ojpegiflength=0; TIFFSeekFile(input, inputoffset, SEEK_SET); TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &h_samp, &v_samp); buffer[bufferoffset++]= 0xff; buffer[bufferoffset++]= 0xdd; buffer[bufferoffset++]= 0x00; buffer[bufferoffset++]= 0x04; h_samp*=8; v_samp*=8; ri=(t2p->tiff_width+h_samp-1) / h_samp; TIFFGetField(input, TIFFTAG_ROWSPERSTRIP, &rows); ri*=(rows+v_samp-1)/v_samp; buffer[bufferoffset++]= (ri>>8) & 0xff; buffer[bufferoffset++]= ri & 0xff; stripcount=TIFFNumberOfStrips(input); for(i=0;i<stripcount;i++){ if(i != 0 ){ buffer[bufferoffset++]=0xff; buffer[bufferoffset++]=(0xd0 | ((i-1)%8)); } bufferoffset+=TIFFReadRawStrip(input, i, (tdata_t) &(((unsigned char*)buffer)[bufferoffset]), -1); } TIFFWriteFile(output, (tdata_t) buffer, bufferoffset); _TIFFfree(buffer); return(bufferoffset); } } else { if(! t2p->pdf_ojpegdata){ TIFFError(TIFF2PDF_MODULE, "No support for OJPEG image %s with bad tables", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } buffer=(unsigned char*) _TIFFmalloc(t2p->tiff_datasize); memset(buffer, 0, t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s", t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } _TIFFmemcpy(buffer, t2p->pdf_ojpegdata, t2p->pdf_ojpegdatalength); bufferoffset=t2p->pdf_ojpegdatalength; stripcount=TIFFNumberOfStrips(input); for(i=0;i<stripcount;i++){ if(i != 0){ buffer[bufferoffset++]=0xff; buffer[bufferoffset++]=(0xd0 | ((i-1)%8)); } bufferoffset+=TIFFReadRawStrip(input, i, (tdata_t) &(((unsigned char*)buffer)[bufferoffset]), -1); } if( ! ( (buffer[bufferoffset-1]==0xd9) && (buffer[bufferoffset-2]==0xff) ) ){ buffer[bufferoffset++]=0xff; buffer[bufferoffset++]=0xd9; } TIFFWriteFile(output, (tdata_t) buffer, bufferoffset); _TIFFfree(buffer); return(bufferoffset); TIFFError(TIFF2PDF_MODULE, "No support for OJPEG image %s with no JPEG File Interchange offset", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } return(t2p->tiff_datasize); } #endif #ifdef JPEG_SUPPORT if(t2p->tiff_compression == COMPRESSION_JPEG){ buffer= (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); memset(buffer, 0, t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s", t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } if(TIFFGetField(input, TIFFTAG_JPEGTABLES, &xuint32, &jpt) != 0){ if(xuint32>4){ _TIFFmemcpy(buffer, jpt, xuint32); bufferoffset+=xuint32-2; } } stripcount=TIFFNumberOfStrips(input); TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc); for(i=0;i<stripcount;i++){ if(sbc[i]>max_striplength) max_striplength=sbc[i]; } stripbuffer=(unsigned char*) _TIFFmalloc(max_striplength); if(stripbuffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s", max_striplength, TIFFFileName(input)); _TIFFfree(buffer); t2p->t2p_error = T2P_ERR_ERROR; return(0); } for(i=0;i<stripcount;i++){ striplength=TIFFReadRawStrip(input, i, (tdata_t) stripbuffer, -1); if(!t2p_process_jpeg_strip( stripbuffer, &striplength, buffer, &bufferoffset, i, t2p->tiff_length)){ TIFFError(TIFF2PDF_MODULE, "Can't process JPEG data in input file %s", TIFFFileName(input)); _TIFFfree(stripbuffer); _TIFFfree(buffer); t2p->t2p_error = T2P_ERR_ERROR; return(0); } } buffer[bufferoffset++]=0xff; buffer[bufferoffset++]=0xd9; TIFFWriteFile(output, (tdata_t) buffer, bufferoffset); _TIFFfree(stripbuffer); _TIFFfree(buffer); return(bufferoffset); } #endif (void)0; } if(t2p->pdf_sample==T2P_SAMPLE_NOTHING){ buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); memset(buffer, 0, t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s", t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } stripsize=TIFFStripSize(input); stripcount=TIFFNumberOfStrips(input); for(i=0;i<stripcount;i++){ read = TIFFReadEncodedStrip(input, i, (tdata_t) &buffer[bufferoffset], stripsize); if(read==-1){ TIFFError(TIFF2PDF_MODULE, "Error on decoding strip %u of %s", i, TIFFFileName(input)); _TIFFfree(buffer); t2p->t2p_error=T2P_ERR_ERROR; return(0); } bufferoffset+=read; } } else { if(t2p->pdf_sample & T2P_SAMPLE_PLANAR_SEPARATE_TO_CONTIG){ sepstripsize=TIFFStripSize(input); sepstripcount=TIFFNumberOfStrips(input); stripsize=sepstripsize*t2p->tiff_samplesperpixel; stripcount=sepstripcount/t2p->tiff_samplesperpixel; buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); memset(buffer, 0, t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s", t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } samplebuffer = (unsigned char*) _TIFFmalloc(stripsize); if(samplebuffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s", t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } for(i=0;i<stripcount;i++){ samplebufferoffset=0; for(j=0;j<t2p->tiff_samplesperpixel;j++){ read = TIFFReadEncodedStrip(input, i + j*stripcount, (tdata_t) &(samplebuffer[samplebufferoffset]), sepstripsize); if(read==-1){ TIFFError(TIFF2PDF_MODULE, "Error on decoding strip %u of %s", i + j*stripcount, TIFFFileName(input)); _TIFFfree(buffer); t2p->t2p_error=T2P_ERR_ERROR; return(0); } samplebufferoffset+=read; } t2p_sample_planar_separate_to_contig( t2p, &(buffer[bufferoffset]), samplebuffer, samplebufferoffset); bufferoffset+=samplebufferoffset; } _TIFFfree(samplebuffer); goto dataready; } buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); memset(buffer, 0, t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s", t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } stripsize=TIFFStripSize(input); stripcount=TIFFNumberOfStrips(input); for(i=0;i<stripcount;i++){ read = TIFFReadEncodedStrip(input, i, (tdata_t) &buffer[bufferoffset], stripsize); if(read==-1){ TIFFError(TIFF2PDF_MODULE, "Error on decoding strip %u of %s", i, TIFFFileName(input)); _TIFFfree(samplebuffer); _TIFFfree(buffer); t2p->t2p_error=T2P_ERR_ERROR; return(0); } bufferoffset+=read; } if(t2p->pdf_sample & T2P_SAMPLE_REALIZE_PALETTE){ samplebuffer=(unsigned char*)_TIFFrealloc( (tdata_t) buffer, t2p->tiff_datasize * t2p->tiff_samplesperpixel); if(samplebuffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s", t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; _TIFFfree(buffer); } else { buffer=samplebuffer; t2p->tiff_datasize *= t2p->tiff_samplesperpixel; } t2p_sample_realize_palette(t2p, buffer); } if(t2p->pdf_sample & T2P_SAMPLE_RGBA_TO_RGB){ t2p->tiff_datasize=t2p_sample_rgba_to_rgb( (tdata_t)buffer, t2p->tiff_width*t2p->tiff_length); } if(t2p->pdf_sample & T2P_SAMPLE_RGBAA_TO_RGB){ t2p->tiff_datasize=t2p_sample_rgbaa_to_rgb( (tdata_t)buffer, t2p->tiff_width*t2p->tiff_length); } if(t2p->pdf_sample & T2P_SAMPLE_YCBCR_TO_RGB){ samplebuffer=(unsigned char*)_TIFFrealloc( (tdata_t)buffer, t2p->tiff_width*t2p->tiff_length*4); if(samplebuffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %u bytes of memory for t2p_readwrite_pdf_image, %s", t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; _TIFFfree(buffer); return(0); } else { buffer=samplebuffer; } if(!TIFFReadRGBAImageOriented( input, t2p->tiff_width, t2p->tiff_length, (uint32*)buffer, ORIENTATION_TOPLEFT, 0)){ TIFFError(TIFF2PDF_MODULE, "Can't use TIFFReadRGBAImageOriented to extract RGB image from %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } t2p->tiff_datasize=t2p_sample_abgr_to_rgb( (tdata_t) buffer, t2p->tiff_width*t2p->tiff_length); } if(t2p->pdf_sample & T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED){ t2p->tiff_datasize=t2p_sample_lab_signed_to_unsigned( (tdata_t)buffer, t2p->tiff_width*t2p->tiff_length); } } dataready: t2p_disable(output); TIFFSetField(output, TIFFTAG_PHOTOMETRIC, t2p->tiff_photometric); TIFFSetField(output, TIFFTAG_BITSPERSAMPLE, t2p->tiff_bitspersample); TIFFSetField(output, TIFFTAG_SAMPLESPERPIXEL, t2p->tiff_samplesperpixel); TIFFSetField(output, TIFFTAG_IMAGEWIDTH, t2p->tiff_width); TIFFSetField(output, TIFFTAG_IMAGELENGTH, t2p->tiff_length); TIFFSetField(output, TIFFTAG_ROWSPERSTRIP, t2p->tiff_length); TIFFSetField(output, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG); TIFFSetField(output, TIFFTAG_FILLORDER, FILLORDER_MSB2LSB); switch(t2p->pdf_compression){ case T2P_COMPRESS_NONE: TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_NONE); break; #ifdef CCITT_SUPPORT case T2P_COMPRESS_G4: TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_CCITTFAX4); break; #endif #ifdef JPEG_SUPPORT case T2P_COMPRESS_JPEG: if(t2p->tiff_photometric==PHOTOMETRIC_YCBCR){ if(TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &xuint16_1, &xuint16_2)!=0){ if(xuint16_1 != 0 && xuint16_2 != 0){ TIFFSetField(output, TIFFTAG_YCBCRSUBSAMPLING, xuint16_1, xuint16_2); } } if(TIFFGetField(input, TIFFTAG_REFERENCEBLACKWHITE, &xfloatp)!=0){ TIFFSetField(output, TIFFTAG_REFERENCEBLACKWHITE, xfloatp); } } if(TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_JPEG)==0){ TIFFError(TIFF2PDF_MODULE, "Unable to use JPEG compression for input %s and output %s", TIFFFileName(input), TIFFFileName(output)); _TIFFfree(buffer); t2p->t2p_error = T2P_ERR_ERROR; return(0); } TIFFSetField(output, TIFFTAG_JPEGTABLESMODE, 0); if(t2p->pdf_colorspace & (T2P_CS_RGB | T2P_CS_LAB)){ TIFFSetField(output, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR); if(t2p->tiff_photometric != PHOTOMETRIC_YCBCR){ TIFFSetField(output, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB); } else { TIFFSetField(output, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RAW); } } if(t2p->pdf_colorspace & T2P_CS_GRAY){ (void)0; } if(t2p->pdf_colorspace & T2P_CS_CMYK){ (void)0; } if(t2p->pdf_defaultcompressionquality != 0){ TIFFSetField(output, TIFFTAG_JPEGQUALITY, t2p->pdf_defaultcompressionquality); } break; #endif #ifdef ZIP_SUPPORT case T2P_COMPRESS_ZIP: TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_DEFLATE); if(t2p->pdf_defaultcompressionquality%100 != 0){ TIFFSetField(output, TIFFTAG_PREDICTOR, t2p->pdf_defaultcompressionquality % 100); } if(t2p->pdf_defaultcompressionquality/100 != 0){ TIFFSetField(output, TIFFTAG_ZIPQUALITY, (t2p->pdf_defaultcompressionquality / 100)); } break; #endif default: break; } t2p_enable(output); t2p->outputwritten = 0; #ifdef JPEG_SUPPORT if(t2p->pdf_compression==T2P_COMPRESS_JPEG && t2p->tiff_photometric==PHOTOMETRIC_YCBCR){ bufferoffset=TIFFWriteEncodedStrip(output, (tstrip_t)0, buffer,stripsize*stripcount); } else #endif bufferoffset=TIFFWriteEncodedStrip(output, (tstrip_t)0, buffer, t2p->tiff_datasize); if(buffer != NULL){ _TIFFfree(buffer); buffer=NULL; } if(bufferoffset==(tsize_t)-1){ TIFFError(TIFF2PDF_MODULE, "Error writing encoded strip to output PDF %s", TIFFFileName(output)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } written= t2p->outputwritten; return(written); } /* This function reads the raster image data from the input TIFF for an image tile and writes the data to the output PDF XObject image dictionary stream for the tile. It returns the amount written or zero on error. */ static tsize_t t2p_readwrite_pdf_image_tile(T2P* t2p, TIFF* input, TIFF* output, ttile_t tile){ uint16 edge=0; tsize_t written=0; unsigned char* buffer=NULL; tsize_t bufferoffset=0; unsigned char* samplebuffer=NULL; tsize_t samplebufferoffset=0; tsize_t read=0; uint16 i=0; ttile_t tilecount=0; ttile_t septilecount=0; tsize_t septilesize=0; #ifdef JPEG_SUPPORT unsigned char* jpt; uint16 xuint16_1=0; uint16 xuint16_2=0; float* xfloatp; uint32 xuint32=0; #endif edge |= t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile); edge |= t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile); if( (t2p->pdf_transcode == T2P_TRANSCODE_RAW) && ((edge == 0) #if defined(JPEG_SUPPORT) || defined(OJPEG_SUPPORT) || (t2p->pdf_compression == T2P_COMPRESS_JPEG) #endif ) ){ #ifdef CCITT_SUPPORT if(t2p->pdf_compression == T2P_COMPRESS_G4){ buffer= (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %u bytes of memory " "for t2p_readwrite_pdf_image_tile, %s", t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } TIFFReadRawTile(input, tile, (tdata_t) buffer, t2p->tiff_datasize); if (t2p->tiff_fillorder==FILLORDER_LSB2MSB){ TIFFReverseBits(buffer, t2p->tiff_datasize); } TIFFWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize); _TIFFfree(buffer); return(t2p->tiff_datasize); } #endif #ifdef ZIP_SUPPORT if(t2p->pdf_compression == T2P_COMPRESS_ZIP){ buffer= (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %u bytes of memory " "for t2p_readwrite_pdf_image_tile, %s", t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } TIFFReadRawTile(input, tile, (tdata_t) buffer, t2p->tiff_datasize); if (t2p->tiff_fillorder==FILLORDER_LSB2MSB){ TIFFReverseBits(buffer, t2p->tiff_datasize); } TIFFWriteFile(output, (tdata_t) buffer, t2p->tiff_datasize); _TIFFfree(buffer); return(t2p->tiff_datasize); } #endif #ifdef OJPEG_SUPPORT if(t2p->tiff_compression == COMPRESSION_OJPEG){ if(! t2p->pdf_ojpegdata){ TIFFError(TIFF2PDF_MODULE, "No support for OJPEG image %s with " "bad tables", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } buffer=(unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %u bytes of memory " "for t2p_readwrite_pdf_image, %s", t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } _TIFFmemcpy(buffer, t2p->pdf_ojpegdata, t2p->pdf_ojpegdatalength); if(edge!=0){ if(t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile)){ buffer[7]= (t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength >> 8) & 0xff; buffer[8]= (t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength ) & 0xff; } if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile)){ buffer[9]= (t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth >> 8) & 0xff; buffer[10]= (t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth ) & 0xff; } } bufferoffset=t2p->pdf_ojpegdatalength; bufferoffset+=TIFFReadRawTile(input, tile, (tdata_t) &(((unsigned char*)buffer)[bufferoffset]), -1); ((unsigned char*)buffer)[bufferoffset++]=0xff; ((unsigned char*)buffer)[bufferoffset++]=0xd9; TIFFWriteFile(output, (tdata_t) buffer, bufferoffset); _TIFFfree(buffer); return(bufferoffset); } #endif #ifdef JPEG_SUPPORT if(t2p->tiff_compression == COMPRESSION_JPEG){ unsigned char table_end[2]; buffer= (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %u bytes of memory " "for t2p_readwrite_pdf_image_tile, %s", t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } if(TIFFGetField(input, TIFFTAG_JPEGTABLES, &xuint16_1, &jpt) != 0) { if(xuint16_1 > 0){ _TIFFmemcpy(buffer, jpt, xuint16_1); bufferoffset += xuint16_1 - 2; table_end[0] = buffer[bufferoffset-2]; table_end[1] = buffer[bufferoffset-1]; } if(xuint16_1 > 0) { xuint32 = bufferoffset; bufferoffset += TIFFReadRawTile( input, tile, (tdata_t) &(((unsigned char*)buffer)[bufferoffset-2]), -1); buffer[xuint32-2]=table_end[0]; buffer[xuint32-1]=table_end[1]; } else { bufferoffset += TIFFReadRawTile( input, tile, (tdata_t) &(((unsigned char*)buffer)[bufferoffset]), -1); } } TIFFWriteFile(output, (tdata_t) buffer, bufferoffset); _TIFFfree(buffer); return(bufferoffset); } #endif (void)0; } if(t2p->pdf_sample==T2P_SAMPLE_NOTHING){ buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %u bytes of memory for " "t2p_readwrite_pdf_image_tile, %s", t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } read = TIFFReadEncodedTile( input, tile, (tdata_t) &buffer[bufferoffset], t2p->tiff_datasize); if(read==-1){ TIFFError(TIFF2PDF_MODULE, "Error on decoding tile %u of %s", tile, TIFFFileName(input)); _TIFFfree(buffer); t2p->t2p_error=T2P_ERR_ERROR; return(0); } } else { if(t2p->pdf_sample == T2P_SAMPLE_PLANAR_SEPARATE_TO_CONTIG){ septilesize=TIFFTileSize(input); septilecount=TIFFNumberOfTiles(input); tilecount=septilecount/t2p->tiff_samplesperpixel; buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %u bytes of memory " "for t2p_readwrite_pdf_image_tile, %s", t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } samplebuffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(samplebuffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %u bytes of memory " "for t2p_readwrite_pdf_image_tile, %s", t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } samplebufferoffset=0; for(i=0;i<t2p->tiff_samplesperpixel;i++){ read = TIFFReadEncodedTile(input, tile + i*tilecount, (tdata_t) &(samplebuffer[samplebufferoffset]), septilesize); if(read==-1){ TIFFError(TIFF2PDF_MODULE, "Error on decoding tile %u of %s", tile + i*tilecount, TIFFFileName(input)); _TIFFfree(samplebuffer); _TIFFfree(buffer); t2p->t2p_error=T2P_ERR_ERROR; return(0); } samplebufferoffset+=read; } t2p_sample_planar_separate_to_contig( t2p, &(buffer[bufferoffset]), samplebuffer, samplebufferoffset); bufferoffset+=samplebufferoffset; _TIFFfree(samplebuffer); } if(buffer==NULL){ buffer = (unsigned char*) _TIFFmalloc(t2p->tiff_datasize); if(buffer==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %u bytes of memory " "for t2p_readwrite_pdf_image_tile, %s", t2p->tiff_datasize, TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } read = TIFFReadEncodedTile( input, tile, (tdata_t) &buffer[bufferoffset], t2p->tiff_datasize); if(read==-1){ TIFFError(TIFF2PDF_MODULE, "Error on decoding tile %u of %s", tile, TIFFFileName(input)); _TIFFfree(buffer); t2p->t2p_error=T2P_ERR_ERROR; return(0); } } if(t2p->pdf_sample & T2P_SAMPLE_RGBA_TO_RGB){ t2p->tiff_datasize=t2p_sample_rgba_to_rgb( (tdata_t)buffer, t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth *t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength); } if(t2p->pdf_sample & T2P_SAMPLE_RGBAA_TO_RGB){ t2p->tiff_datasize=t2p_sample_rgbaa_to_rgb( (tdata_t)buffer, t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth *t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength); } if(t2p->pdf_sample & T2P_SAMPLE_YCBCR_TO_RGB){ TIFFError(TIFF2PDF_MODULE, "No support for YCbCr to RGB in tile for %s", TIFFFileName(input)); _TIFFfree(buffer); t2p->t2p_error = T2P_ERR_ERROR; return(0); } if(t2p->pdf_sample & T2P_SAMPLE_LAB_SIGNED_TO_UNSIGNED){ t2p->tiff_datasize=t2p_sample_lab_signed_to_unsigned( (tdata_t)buffer, t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth *t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength); } } if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile) != 0){ t2p_tile_collapse_left( buffer, TIFFTileRowSize(input), t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth, t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth, t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength); } t2p_disable(output); TIFFSetField(output, TIFFTAG_PHOTOMETRIC, t2p->tiff_photometric); TIFFSetField(output, TIFFTAG_BITSPERSAMPLE, t2p->tiff_bitspersample); TIFFSetField(output, TIFFTAG_SAMPLESPERPIXEL, t2p->tiff_samplesperpixel); if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile) == 0){ TIFFSetField( output, TIFFTAG_IMAGEWIDTH, t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth); } else { TIFFSetField( output, TIFFTAG_IMAGEWIDTH, t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth); } if(t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile) == 0){ TIFFSetField( output, TIFFTAG_IMAGELENGTH, t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength); TIFFSetField( output, TIFFTAG_ROWSPERSTRIP, t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength); } else { TIFFSetField( output, TIFFTAG_IMAGELENGTH, t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength); TIFFSetField( output, TIFFTAG_ROWSPERSTRIP, t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength); } TIFFSetField(output, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG); TIFFSetField(output, TIFFTAG_FILLORDER, FILLORDER_MSB2LSB); switch(t2p->pdf_compression){ case T2P_COMPRESS_NONE: TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_NONE); break; #ifdef CCITT_SUPPORT case T2P_COMPRESS_G4: TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_CCITTFAX4); break; #endif #ifdef JPEG_SUPPORT case T2P_COMPRESS_JPEG: if(t2p->tiff_photometric==PHOTOMETRIC_YCBCR){ if(TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &xuint16_1, &xuint16_2)!=0){ if(xuint16_1 != 0 && xuint16_2 != 0){ TIFFSetField(output, TIFFTAG_YCBCRSUBSAMPLING, xuint16_1, xuint16_2); } } if(TIFFGetField(input, TIFFTAG_REFERENCEBLACKWHITE, &xfloatp)!=0){ TIFFSetField(output, TIFFTAG_REFERENCEBLACKWHITE, xfloatp); } } TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_JPEG); TIFFSetField(output, TIFFTAG_JPEGTABLESMODE, 0); /* JPEGTABLESMODE_NONE */ if(t2p->pdf_colorspace & (T2P_CS_RGB | T2P_CS_LAB)){ TIFFSetField(output, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR); if(t2p->tiff_photometric != PHOTOMETRIC_YCBCR){ TIFFSetField(output, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB); } else { TIFFSetField(output, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RAW); } } if(t2p->pdf_colorspace & T2P_CS_GRAY){ (void)0; } if(t2p->pdf_colorspace & T2P_CS_CMYK){ (void)0; } if(t2p->pdf_defaultcompressionquality != 0){ TIFFSetField(output, TIFFTAG_JPEGQUALITY, t2p->pdf_defaultcompressionquality); } break; #endif #ifdef ZIP_SUPPORT case T2P_COMPRESS_ZIP: TIFFSetField(output, TIFFTAG_COMPRESSION, COMPRESSION_DEFLATE); if(t2p->pdf_defaultcompressionquality%100 != 0){ TIFFSetField(output, TIFFTAG_PREDICTOR, t2p->pdf_defaultcompressionquality % 100); } if(t2p->pdf_defaultcompressionquality/100 != 0){ TIFFSetField(output, TIFFTAG_ZIPQUALITY, (t2p->pdf_defaultcompressionquality / 100)); } break; #endif default: break; } t2p_enable(output); t2p->outputwritten = 0; bufferoffset=TIFFWriteEncodedStrip(output, (tstrip_t) 0, buffer, TIFFStripSize(output)); if(buffer != NULL){ _TIFFfree(buffer); buffer=NULL; } if(bufferoffset==-1){ TIFFError(TIFF2PDF_MODULE, "Error writing encoded tile to output PDF %s", TIFFFileName(output)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } written= t2p->outputwritten; return(written); } #ifdef OJPEG_SUPPORT static int t2p_process_ojpeg_tables(T2P* t2p, TIFF* input){ uint16 proc=0; void* q; uint32 q_length=0; void* dc; uint32 dc_length=0; void* ac; uint32 ac_length=0; uint16* lp; uint16* pt; uint16 h_samp=1; uint16 v_samp=1; unsigned char* ojpegdata; uint16 table_count; uint32 offset_table; uint32 offset_ms_l; uint32 code_count; uint32 i=0; uint32 dest=0; uint16 ri=0; uint32 rows=0; if(!TIFFGetField(input, TIFFTAG_JPEGPROC, &proc)){ TIFFError(TIFF2PDF_MODULE, "Missing JPEGProc field in OJPEG image %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } if(proc!=JPEGPROC_BASELINE && proc!=JPEGPROC_LOSSLESS){ TIFFError(TIFF2PDF_MODULE, "Bad JPEGProc field in OJPEG image %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } if(!TIFFGetField(input, TIFFTAG_JPEGQTABLES, &q_length, &q)){ TIFFError(TIFF2PDF_MODULE, "Missing JPEGQTables field in OJPEG image %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } if(q_length < (64U * t2p->tiff_samplesperpixel)){ TIFFError(TIFF2PDF_MODULE, "Bad JPEGQTables field in OJPEG image %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } if(!TIFFGetField(input, TIFFTAG_JPEGDCTABLES, &dc_length, &dc)){ TIFFError(TIFF2PDF_MODULE, "Missing JPEGDCTables field in OJPEG image %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } if(proc==JPEGPROC_BASELINE){ if(!TIFFGetField(input, TIFFTAG_JPEGACTABLES, &ac_length, &ac)){ TIFFError(TIFF2PDF_MODULE, "Missing JPEGACTables field in OJPEG image %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } } else { if(!TIFFGetField(input, TIFFTAG_JPEGLOSSLESSPREDICTORS, &lp)){ TIFFError(TIFF2PDF_MODULE, "Missing JPEGLosslessPredictors field in OJPEG image %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } if(!TIFFGetField(input, TIFFTAG_JPEGPOINTTRANSFORM, &pt)){ TIFFError(TIFF2PDF_MODULE, "Missing JPEGPointTransform field in OJPEG image %s", TIFFFileName(input)); t2p->t2p_error = T2P_ERR_ERROR; return(0); } } if(!TIFFGetField(input, TIFFTAG_YCBCRSUBSAMPLING, &h_samp, &v_samp)){ h_samp=1; v_samp=1; } if(t2p->pdf_ojpegdata != NULL){ _TIFFfree(t2p->pdf_ojpegdata); t2p->pdf_ojpegdata=NULL; } t2p->pdf_ojpegdata = _TIFFmalloc(2048); if(t2p->pdf_ojpegdata == NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %u bytes of memory for t2p_process_ojpeg_tables, %s", 2048, TIFFFileName(input)); return(0); } _TIFFmemset(t2p->pdf_ojpegdata, 0x00, 2048); t2p->pdf_ojpegdatalength = 0; table_count=t2p->tiff_samplesperpixel; if(proc==JPEGPROC_BASELINE){ if(table_count>2) table_count=2; } ojpegdata=(unsigned char*)t2p->pdf_ojpegdata; ojpegdata[t2p->pdf_ojpegdatalength++]=0xff; ojpegdata[t2p->pdf_ojpegdatalength++]=0xd8; ojpegdata[t2p->pdf_ojpegdatalength++]=0xff; if(proc==JPEGPROC_BASELINE){ ojpegdata[t2p->pdf_ojpegdatalength++]=0xc0; } else { ojpegdata[t2p->pdf_ojpegdatalength++]=0xc3; } ojpegdata[t2p->pdf_ojpegdatalength++]=0x00; ojpegdata[t2p->pdf_ojpegdatalength++]=(8 + 3*t2p->tiff_samplesperpixel); ojpegdata[t2p->pdf_ojpegdatalength++]=(t2p->tiff_bitspersample & 0xff); if(TIFFIsTiled(input)){ ojpegdata[t2p->pdf_ojpegdatalength++]= (t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength >> 8) & 0xff; ojpegdata[t2p->pdf_ojpegdatalength++]= (t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength ) & 0xff; ojpegdata[t2p->pdf_ojpegdatalength++]= (t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth >> 8) & 0xff; ojpegdata[t2p->pdf_ojpegdatalength++]= (t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth ) & 0xff; } else { ojpegdata[t2p->pdf_ojpegdatalength++]= (t2p->tiff_length >> 8) & 0xff; ojpegdata[t2p->pdf_ojpegdatalength++]= (t2p->tiff_length ) & 0xff; ojpegdata[t2p->pdf_ojpegdatalength++]= (t2p->tiff_width >> 8) & 0xff; ojpegdata[t2p->pdf_ojpegdatalength++]= (t2p->tiff_width ) & 0xff; } ojpegdata[t2p->pdf_ojpegdatalength++]=(t2p->tiff_samplesperpixel & 0xff); for(i=0;i<t2p->tiff_samplesperpixel;i++){ ojpegdata[t2p->pdf_ojpegdatalength++]=i; if(i==0){ ojpegdata[t2p->pdf_ojpegdatalength] |= h_samp<<4 & 0xf0;; ojpegdata[t2p->pdf_ojpegdatalength++] |= v_samp & 0x0f; } else { ojpegdata[t2p->pdf_ojpegdatalength++]= 0x11; } ojpegdata[t2p->pdf_ojpegdatalength++]=i; } for(dest=0;dest<t2p->tiff_samplesperpixel;dest++){ ojpegdata[t2p->pdf_ojpegdatalength++]=0xff; ojpegdata[t2p->pdf_ojpegdatalength++]=0xdb; ojpegdata[t2p->pdf_ojpegdatalength++]=0x00; ojpegdata[t2p->pdf_ojpegdatalength++]=0x43; ojpegdata[t2p->pdf_ojpegdatalength++]=dest; _TIFFmemcpy( &(ojpegdata[t2p->pdf_ojpegdatalength++]), &(((unsigned char*)q)[64*dest]), 64); t2p->pdf_ojpegdatalength+=64; } offset_table=0; for(dest=0;dest<table_count;dest++){ ojpegdata[t2p->pdf_ojpegdatalength++]=0xff; ojpegdata[t2p->pdf_ojpegdatalength++]=0xc4; offset_ms_l=t2p->pdf_ojpegdatalength; t2p->pdf_ojpegdatalength+=2; ojpegdata[t2p->pdf_ojpegdatalength++]=dest & 0x0f; _TIFFmemcpy( &(ojpegdata[t2p->pdf_ojpegdatalength]), &(((unsigned char*)dc)[offset_table]), 16); code_count=0; offset_table+=16; for(i=0;i<16;i++){ code_count+=ojpegdata[t2p->pdf_ojpegdatalength++]; } ojpegdata[offset_ms_l]=((19+code_count)>>8) & 0xff; ojpegdata[offset_ms_l+1]=(19+code_count) & 0xff; _TIFFmemcpy( &(ojpegdata[t2p->pdf_ojpegdatalength]), &(((unsigned char*)dc)[offset_table]), code_count); offset_table+=code_count; t2p->pdf_ojpegdatalength+=code_count; } if(proc==JPEGPROC_BASELINE){ offset_table=0; for(dest=0;dest<table_count;dest++){ ojpegdata[t2p->pdf_ojpegdatalength++]=0xff; ojpegdata[t2p->pdf_ojpegdatalength++]=0xc4; offset_ms_l=t2p->pdf_ojpegdatalength; t2p->pdf_ojpegdatalength+=2; ojpegdata[t2p->pdf_ojpegdatalength] |= 0x10; ojpegdata[t2p->pdf_ojpegdatalength++] |=dest & 0x0f; _TIFFmemcpy( &(ojpegdata[t2p->pdf_ojpegdatalength]), &(((unsigned char*)ac)[offset_table]), 16); code_count=0; offset_table+=16; for(i=0;i<16;i++){ code_count+=ojpegdata[t2p->pdf_ojpegdatalength++]; } ojpegdata[offset_ms_l]=((19+code_count)>>8) & 0xff; ojpegdata[offset_ms_l+1]=(19+code_count) & 0xff; _TIFFmemcpy( &(ojpegdata[t2p->pdf_ojpegdatalength]), &(((unsigned char*)ac)[offset_table]), code_count); offset_table+=code_count; t2p->pdf_ojpegdatalength+=code_count; } } if(TIFFNumberOfStrips(input)>1){ ojpegdata[t2p->pdf_ojpegdatalength++]=0xff; ojpegdata[t2p->pdf_ojpegdatalength++]=0xdd; ojpegdata[t2p->pdf_ojpegdatalength++]=0x00; ojpegdata[t2p->pdf_ojpegdatalength++]=0x04; h_samp*=8; v_samp*=8; ri=(t2p->tiff_width+h_samp-1) / h_samp; TIFFGetField(input, TIFFTAG_ROWSPERSTRIP, &rows); ri*=(rows+v_samp-1)/v_samp; ojpegdata[t2p->pdf_ojpegdatalength++]= (ri>>8) & 0xff; ojpegdata[t2p->pdf_ojpegdatalength++]= ri & 0xff; } ojpegdata[t2p->pdf_ojpegdatalength++]=0xff; ojpegdata[t2p->pdf_ojpegdatalength++]=0xda; ojpegdata[t2p->pdf_ojpegdatalength++]=0x00; ojpegdata[t2p->pdf_ojpegdatalength++]=(6 + 2*t2p->tiff_samplesperpixel); ojpegdata[t2p->pdf_ojpegdatalength++]=t2p->tiff_samplesperpixel & 0xff; for(i=0;i<t2p->tiff_samplesperpixel;i++){ ojpegdata[t2p->pdf_ojpegdatalength++]= i & 0xff; if(proc==JPEGPROC_BASELINE){ ojpegdata[t2p->pdf_ojpegdatalength] |= ( ( (i>(table_count-1U)) ? (table_count-1U) : i) << 4U) & 0xf0; ojpegdata[t2p->pdf_ojpegdatalength++] |= ( (i>(table_count-1U)) ? (table_count-1U) : i) & 0x0f; } else { ojpegdata[t2p->pdf_ojpegdatalength++] = (i << 4) & 0xf0; } } if(proc==JPEGPROC_BASELINE){ t2p->pdf_ojpegdatalength++; ojpegdata[t2p->pdf_ojpegdatalength++]=0x3f; t2p->pdf_ojpegdatalength++; } else { ojpegdata[t2p->pdf_ojpegdatalength++]= (lp[0] & 0xff); t2p->pdf_ojpegdatalength++; ojpegdata[t2p->pdf_ojpegdatalength++]= (pt[0] & 0x0f); } return(1); } #endif #ifdef JPEG_SUPPORT static int t2p_process_jpeg_strip( unsigned char* strip, tsize_t* striplength, unsigned char* buffer, tsize_t* bufferoffset, tstrip_t no, uint32 height){ tsize_t i=0; uint16 ri =0; uint16 v_samp=1; uint16 h_samp=1; int j=0; i++; while(i<(*striplength)){ switch( strip[i] ){ case 0xd8: i+=2; break; case 0xc0: case 0xc1: case 0xc3: case 0xc9: case 0xca: if(no==0){ _TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), strip[i+2]+2); for(j=0;j<buffer[*bufferoffset+9];j++){ if( (buffer[*bufferoffset+11+(2*j)]>>4) > h_samp) h_samp = (buffer[*bufferoffset+11+(2*j)]>>4); if( (buffer[*bufferoffset+11+(2*j)] & 0x0f) > v_samp) v_samp = (buffer[*bufferoffset+11+(2*j)] & 0x0f); } v_samp*=8; h_samp*=8; ri=((( ((uint16)(buffer[*bufferoffset+5])<<8) | (uint16)(buffer[*bufferoffset+6]) )+v_samp-1)/ v_samp); ri*=((( ((uint16)(buffer[*bufferoffset+7])<<8) | (uint16)(buffer[*bufferoffset+8]) )+h_samp-1)/ h_samp); buffer[*bufferoffset+5]= (unsigned char) ((height>>8) & 0xff); buffer[*bufferoffset+6]= (unsigned char) (height & 0xff); *bufferoffset+=strip[i+2]+2; i+=strip[i+2]+2; buffer[(*bufferoffset)++]=0xff; buffer[(*bufferoffset)++]=0xdd; buffer[(*bufferoffset)++]=0x00; buffer[(*bufferoffset)++]=0x04; buffer[(*bufferoffset)++]=(ri >> 8) & 0xff; buffer[(*bufferoffset)++]= ri & 0xff; } else { i+=strip[i+2]+2; } break; case 0xc4: case 0xdb: _TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), strip[i+2]+2); *bufferoffset+=strip[i+2]+2; i+=strip[i+2]+2; break; case 0xda: if(no==0){ _TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), strip[i+2]+2); *bufferoffset+=strip[i+2]+2; i+=strip[i+2]+2; } else { buffer[(*bufferoffset)++]=0xff; buffer[(*bufferoffset)++]= (unsigned char)(0xd0 | ((no-1)%8)); i+=strip[i+2]+2; } _TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), (*striplength)-i-1); *bufferoffset+=(*striplength)-i-1; return(1); default: i+=strip[i+2]+2; } } return(0); } #endif /* This functions converts a tilewidth x tilelength buffer of samples into an edgetilewidth x tilelength buffer of samples. */ static void t2p_tile_collapse_left( tdata_t buffer, tsize_t scanwidth, uint32 tilewidth, uint32 edgetilewidth, uint32 tilelength){ uint32 i=0; tsize_t edgescanwidth=0; edgescanwidth = (scanwidth * edgetilewidth + (tilewidth - 1))/ tilewidth; for(i=i;i<tilelength;i++){ _TIFFmemcpy( &(((char*)buffer)[edgescanwidth*i]), &(((char*)buffer)[scanwidth*i]), edgescanwidth); } return; } /* This function calls TIFFWriteDirectory on the output after blanking its output by replacing the read, write, and seek procedures with empty implementations, then it replaces the original implementations. */ static void t2p_write_advance_directory(T2P* t2p, TIFF* output){ t2p_disable(output); if(!TIFFWriteDirectory(output)){ TIFFError(TIFF2PDF_MODULE, "Error writing virtual directory to output PDF %s", TIFFFileName(output)); t2p->t2p_error = T2P_ERR_ERROR; return; } t2p_enable(output); return; } static tsize_t t2p_sample_planar_separate_to_contig(T2P* t2p, unsigned char* buffer, unsigned char* samplebuffer, tsize_t samplebuffersize){ tsize_t stride=0; tsize_t i=0; tsize_t j=0; stride=samplebuffersize/t2p->tiff_samplesperpixel; for(i=0;i<stride;i++){ for(j=0;j<t2p->tiff_samplesperpixel;j++){ buffer[i*t2p->tiff_samplesperpixel + j] = samplebuffer[i + j*stride]; } } return(samplebuffersize); } static tsize_t t2p_sample_realize_palette(T2P* t2p, unsigned char* buffer){ uint32 sample_count=0; uint16 component_count=0; uint32 palette_offset=0; uint32 sample_offset=0; uint32 i=0; uint32 j=0; sample_count=t2p->tiff_width*t2p->tiff_length; component_count=t2p->tiff_samplesperpixel; for(i=sample_count;i>0;i--){ palette_offset=buffer[i-1] * component_count; sample_offset= (i-1) * component_count; for(j=0;j<component_count;j++){ buffer[sample_offset+j]=t2p->pdf_palette[palette_offset+j]; } } return(0); } /* This functions converts in place a buffer of ABGR interleaved data into RGB interleaved data, discarding A. */ static tsize_t t2p_sample_abgr_to_rgb(tdata_t data, uint32 samplecount) { uint32 i=0; uint32 sample=0; for(i=0;i<samplecount;i++){ sample=((uint32*)data)[i]; ((char*)data)[i*3]= (char) (sample & 0xff); ((char*)data)[i*3+1]= (char) ((sample>>8) & 0xff); ((char*)data)[i*3+2]= (char) ((sample>>16) & 0xff); } return(i*3); } /* * This functions converts in place a buffer of RGBA interleaved data * into RGB interleaved data, discarding A. */ static tsize_t t2p_sample_rgbaa_to_rgb(tdata_t data, uint32 samplecount) { uint32 i; for(i = 0; i < samplecount; i++) memcpy((uint8*)data + i * 3, (uint8*)data + i * 4, 3); return(i * 3); } /* * This functions converts in place a buffer of RGBA interleaved data * into RGB interleaved data, adding 255-A to each component sample. */ static tsize_t t2p_sample_rgba_to_rgb(tdata_t data, uint32 samplecount) { uint32 i = 0; uint32 sample = 0; uint8 alpha = 0; for (i = 0; i < samplecount; i++) { sample=((uint32*)data)[i]; alpha=(uint8)((255 - (sample & 0xff))); ((uint8 *)data)[i * 3] = (uint8) ((sample >> 24) & 0xff) + alpha; ((uint8 *)data)[i * 3 + 1] = (uint8) ((sample >> 16) & 0xff) + alpha; ((uint8 *)data)[i * 3 + 2] = (uint8) ((sample >> 8) & 0xff) + alpha; } return (i * 3); } /* This function converts the a and b samples of Lab data from signed to unsigned. */ static tsize_t t2p_sample_lab_signed_to_unsigned(tdata_t buffer, uint32 samplecount){ uint32 i=0; for(i=0;i<samplecount;i++){ if( (((unsigned char*)buffer)[(i*3)+1] & 0x80) !=0){ ((unsigned char*)buffer)[(i*3)+1] = (unsigned char)(0x80 + ((char*)buffer)[(i*3)+1]); } else { ((unsigned char*)buffer)[(i*3)+1] |= 0x80; } if( (((unsigned char*)buffer)[(i*3)+2] & 0x80) !=0){ ((unsigned char*)buffer)[(i*3)+2] = (unsigned char)(0x80 + ((char*)buffer)[(i*3)+2]); } else { ((unsigned char*)buffer)[(i*3)+2] |= 0x80; } } return(samplecount*3); } /* This function writes the PDF header to output. */ static tsize_t t2p_write_pdf_header(T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[16]; int buflen=0; buflen=sprintf(buffer, "%%PDF-%u.%u ", t2p->pdf_majorversion&0xff, t2p->pdf_minorversion&0xff); written += TIFFWriteFile(output, (tdata_t) buffer, buflen); written += TIFFWriteFile(output, (tdata_t)"\r%\342\343\317\323\r\n", 8); return(written); } /* This function writes the beginning of a PDF object to output. */ static tsize_t t2p_write_pdf_obj_start(uint32 number, TIFF* output){ tsize_t written=0; char buffer[16]; int buflen=0; buflen=sprintf(buffer, "%lu", (unsigned long)number); written += TIFFWriteFile(output, (tdata_t) buffer, buflen ); written += TIFFWriteFile(output, (tdata_t) " 0 obj\r", 7); return(written); } /* This function writes the end of a PDF object to output. */ static tsize_t t2p_write_pdf_obj_end(TIFF* output){ tsize_t written=0; written += TIFFWriteFile(output, (tdata_t) "endobj\r", 7); return(written); } /* This function writes a PDF string object to output. */ static tsize_t t2p_write_pdf_string(char* pdfstr, TIFF* output){ tsize_t written=0; uint32 i=0; char buffer[5]; uint32 len=0; len=strlen(pdfstr); written += TIFFWriteFile(output, (tdata_t) "(", 1); for (i=0;i<len;i++){ if((pdfstr[i]&0x80) || (pdfstr[i]==127) || (pdfstr[i]<32)){ sprintf(buffer, "\\%.3o", pdfstr[i]); written += TIFFWriteFile(output, (tdata_t) buffer, 4); } else { switch (pdfstr[i]){ case 0x08: written += TIFFWriteFile(output, (tdata_t) "\\b", 2); break; case 0x09: written += TIFFWriteFile(output, (tdata_t) "\\t", 2); break; case 0x0A: written += TIFFWriteFile(output, (tdata_t) "\\n", 2); break; case 0x0C: written += TIFFWriteFile(output, (tdata_t) "\\f", 2); break; case 0x0D: written += TIFFWriteFile(output, (tdata_t) "\\r", 2); break; case 0x28: written += TIFFWriteFile(output, (tdata_t) "\\(", 2); break; case 0x29: written += TIFFWriteFile(output, (tdata_t) "\\)", 2); break; case 0x5C: written += TIFFWriteFile(output, (tdata_t) "\\\\", 2); break; default: written += TIFFWriteFile(output, (tdata_t) &pdfstr[i], 1); } } } written += TIFFWriteFile(output, (tdata_t) ") ", 1); return(written); } /* This function writes a buffer of data to output. */ static tsize_t t2p_write_pdf_stream(tdata_t buffer, tsize_t len, TIFF* output){ tsize_t written=0; written += TIFFWriteFile(output, (tdata_t) buffer, len); return(written); } /* This functions writes the beginning of a PDF stream to output. */ static tsize_t t2p_write_pdf_stream_start(TIFF* output){ tsize_t written=0; written += TIFFWriteFile(output, (tdata_t) "stream\r\n", 8); return(written); } /* This function writes the end of a PDF stream to output. */ static tsize_t t2p_write_pdf_stream_end(TIFF* output){ tsize_t written=0; written += TIFFWriteFile(output, (tdata_t) "\rendstream\r", 11); return(written); } /* This function writes a stream dictionary for a PDF stream to output. */ static tsize_t t2p_write_pdf_stream_dict(tsize_t len, uint32 number, TIFF* output){ tsize_t written=0; char buffer[16]; int buflen=0; written += TIFFWriteFile(output, (tdata_t) "/Length ", 8); if(len!=0){ written += t2p_write_pdf_stream_length(len, output); } else { buflen=sprintf(buffer, "%lu", (unsigned long)number); written += TIFFWriteFile(output, (tdata_t) buffer, buflen); written += TIFFWriteFile(output, (tdata_t) " 0 R \r", 6); } return(written); } /* This functions writes the beginning of a PDF stream dictionary to output. */ static tsize_t t2p_write_pdf_stream_dict_start(TIFF* output){ tsize_t written=0; written += TIFFWriteFile(output, (tdata_t) "<< \r", 4); return(written); } /* This function writes the end of a PDF stream dictionary to output. */ static tsize_t t2p_write_pdf_stream_dict_end(TIFF* output){ tsize_t written=0; written += TIFFWriteFile(output, (tdata_t) " >>\r", 4); return(written); } /* This function writes a number to output. */ static tsize_t t2p_write_pdf_stream_length(tsize_t len, TIFF* output){ tsize_t written=0; char buffer[16]; int buflen=0; buflen=sprintf(buffer, "%lu", (unsigned long)len); written += TIFFWriteFile(output, (tdata_t) buffer, buflen); written += TIFFWriteFile(output, (tdata_t) "\r", 1); return(written); } /* This function writes the PDF Catalog structure to output. */ static tsize_t t2p_write_pdf_catalog(T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[16]; int buflen=0; written += TIFFWriteFile(output, (tdata_t)"<< \r/Type /Catalog \r/Pages ", 27); buflen=sprintf(buffer, "%lu", (unsigned long)t2p->pdf_pages); written += TIFFWriteFile(output, (tdata_t) buffer, buflen ); written += TIFFWriteFile(output, (tdata_t) " 0 R \r", 6); if(t2p->pdf_fitwindow){ written += TIFFWriteFile(output, (tdata_t) "/ViewerPreferences <</FitWindow true>>\r", 39); } written += TIFFWriteFile(output, (tdata_t)">>\r", 3); return(written); } /* This function writes the PDF Info structure to output. */ static tsize_t t2p_write_pdf_info(T2P* t2p, TIFF* input, TIFF* output){ tsize_t written=0; char* info; char buffer[512]; if(t2p->pdf_datetime==NULL){ t2p_pdf_tifftime(t2p, input); } if(strlen(t2p->pdf_datetime) > 0){ written += TIFFWriteFile(output, (tdata_t) "<< \r/CreationDate ", 18); written += t2p_write_pdf_string(t2p->pdf_datetime, output); written += TIFFWriteFile(output, (tdata_t) "\r/ModDate ", 10); written += t2p_write_pdf_string(t2p->pdf_datetime, output); } written += TIFFWriteFile(output, (tdata_t) "\r/Producer ", 11); _TIFFmemset((tdata_t)buffer, 0x00, 512); sprintf(buffer, "libtiff / tiff2pdf - %d / %s", TIFFLIB_VERSION, T2P_VERSION); written += t2p_write_pdf_string(buffer, output); written += TIFFWriteFile(output, (tdata_t) "\r", 1); if(t2p->pdf_creator != NULL){ if(strlen(t2p->pdf_creator)>0){ if(strlen(t2p->pdf_creator)>511){t2p->pdf_creator[512]=(char)0;} written += TIFFWriteFile(output, (tdata_t) "/Creator ", 9); written += t2p_write_pdf_string(t2p->pdf_creator, output); written += TIFFWriteFile(output, (tdata_t) "\r", 1); } } else{ if( TIFFGetField(input, TIFFTAG_SOFTWARE, &info) != 0){ if(strlen(info)>511){info[512]=(char)0;} written += TIFFWriteFile(output, (tdata_t) "/Creator ", 9); written += t2p_write_pdf_string(info, output); written += TIFFWriteFile(output, (tdata_t) "\r", 1); } } if(t2p->pdf_author != NULL){ if(strlen(t2p->pdf_author)>0){ if(strlen(t2p->pdf_author)>511){t2p->pdf_author[512]=(char)0;} written += TIFFWriteFile(output, (tdata_t) "/Author ", 8); written += t2p_write_pdf_string(t2p->pdf_author, output); written += TIFFWriteFile(output, (tdata_t) "\r", 1); } } else{ if( TIFFGetField(input, TIFFTAG_ARTIST, &info) != 0){ if(strlen(info)>511){info[512]=(char)0;} written += TIFFWriteFile(output, (tdata_t) "/Author ", 8); written += t2p_write_pdf_string(info, output); written += TIFFWriteFile(output, (tdata_t) "\r", 1); } else if ( TIFFGetField(input, TIFFTAG_COPYRIGHT, &info) != 0){ if(strlen(info)>511){info[512]=(char)0;} written += TIFFWriteFile(output, (tdata_t) "/Author ", 8); written += t2p_write_pdf_string(info, output); written += TIFFWriteFile(output, (tdata_t) "\r", 1); } } if(t2p->pdf_title != NULL){ if(strlen(t2p->pdf_title)>0){ if(strlen(t2p->pdf_title)>511){t2p->pdf_title[512]=(char)0;} written += TIFFWriteFile(output, (tdata_t) "/Title ", 7); written += t2p_write_pdf_string(t2p->pdf_title, output); written += TIFFWriteFile(output, (tdata_t) "\r", 1); } } else{ if( TIFFGetField(input, TIFFTAG_DOCUMENTNAME, &info) != 0){ if(strlen(info)>511){info[512]=(char)0;} written += TIFFWriteFile(output, (tdata_t) "/Title ", 7); written += t2p_write_pdf_string(info, output); written += TIFFWriteFile(output, (tdata_t) "\r", 1); } } if(t2p->pdf_subject != NULL){ if(strlen(t2p->pdf_subject)>0){ if(strlen(t2p->pdf_subject)>511){t2p->pdf_subject[512]=(char)0;} written += TIFFWriteFile(output, (tdata_t) "/Subject ", 9); written += t2p_write_pdf_string(t2p->pdf_subject, output); written += TIFFWriteFile(output, (tdata_t) "\r", 1); } } else{ if( TIFFGetField(input, TIFFTAG_IMAGEDESCRIPTION, &info) != 0){ if(strlen(info)>511){info[512]=(char)0;} written += TIFFWriteFile(output, (tdata_t) "/Subject ", 9); written += t2p_write_pdf_string(info, output); written += TIFFWriteFile(output, (tdata_t) "\r", 1); } } if(t2p->pdf_keywords != NULL){ if(strlen(t2p->pdf_keywords)>0){ if(strlen(t2p->pdf_keywords)>511){t2p->pdf_keywords[512]=(char)0;} written += TIFFWriteFile(output, (tdata_t) "/Keywords ", 10); written += t2p_write_pdf_string(t2p->pdf_keywords, output); written += TIFFWriteFile(output, (tdata_t) "\r", 1); } } written += TIFFWriteFile(output, (tdata_t) ">> \r", 4); return(written); } /* This function fills a string of a T2P struct with the current time as a PDF date string, it is called by t2p_pdf_tifftime. */ static void t2p_pdf_currenttime(T2P* t2p){ struct tm* currenttime; time_t timenow; timenow=time(0); currenttime=localtime(&timenow); sprintf(t2p->pdf_datetime, "D:%.4d%.2d%.2d%.2d%.2d%.2d", (currenttime->tm_year+1900) % 65536, (currenttime->tm_mon+1) % 256, (currenttime->tm_mday) % 256, (currenttime->tm_hour) % 256, (currenttime->tm_min) % 256, (currenttime->tm_sec) % 256); return; } /* This function fills a string of a T2P struct with the date and time of a TIFF file if it exists or the current time as a PDF date string. */ static void t2p_pdf_tifftime(T2P* t2p, TIFF* input){ char* datetime; t2p->pdf_datetime= (char*) _TIFFmalloc(19); if(t2p->pdf_datetime==NULL){ TIFFError(TIFF2PDF_MODULE, "Can't allocate %u bytes of memory for t2p_pdf_tiff_time", 17); t2p->t2p_error = T2P_ERR_ERROR; return; } t2p->pdf_datetime[16]=0; if( TIFFGetField(input, TIFFTAG_DATETIME, &datetime) != 0 && (strlen(datetime) >= 19) ){ t2p->pdf_datetime[0]='D'; t2p->pdf_datetime[1]=':'; t2p->pdf_datetime[2]=datetime[0]; t2p->pdf_datetime[3]=datetime[1]; t2p->pdf_datetime[4]=datetime[2]; t2p->pdf_datetime[5]=datetime[3]; t2p->pdf_datetime[6]=datetime[5]; t2p->pdf_datetime[7]=datetime[6]; t2p->pdf_datetime[8]=datetime[8]; t2p->pdf_datetime[9]=datetime[9]; t2p->pdf_datetime[10]=datetime[11]; t2p->pdf_datetime[11]=datetime[12]; t2p->pdf_datetime[12]=datetime[14]; t2p->pdf_datetime[13]=datetime[15]; t2p->pdf_datetime[14]=datetime[17]; t2p->pdf_datetime[15]=datetime[18]; } else { t2p_pdf_currenttime(t2p); } return; } /* This function writes a PDF Pages Tree structure to output. */ static tsize_t t2p_write_pdf_pages(T2P* t2p, TIFF* output){ tsize_t written=0; tdir_t i=0; char buffer[16]; int buflen=0; int page=0; written += TIFFWriteFile(output, (tdata_t) "<< \r/Type /Pages \r/Kids [ ", 26); page = t2p->pdf_pages+1; for (i=0;i<t2p->tiff_pagecount;i++){ buflen=sprintf(buffer, "%d", page); written += TIFFWriteFile(output, (tdata_t) buffer, buflen); written += TIFFWriteFile(output, (tdata_t) " 0 R ", 5); if ( ((i+1)%8)==0 ) { written += TIFFWriteFile(output, (tdata_t) "\r", 1); } page +=3; page += t2p->tiff_pages[i].page_extra; if(t2p->tiff_pages[i].page_tilecount>0){ page += (2 * t2p->tiff_pages[i].page_tilecount); } else { page +=2; } } written += TIFFWriteFile(output, (tdata_t) "] \r/Count ", 10); _TIFFmemset(buffer, 0x00, 16); buflen=sprintf(buffer, "%d", t2p->tiff_pagecount); written += TIFFWriteFile(output, (tdata_t) buffer, buflen); written += TIFFWriteFile(output, (tdata_t) " \r>> \r", 6); return(written); } /* This function writes a PDF Page structure to output. */ static tsize_t t2p_write_pdf_page(uint32 object, T2P* t2p, TIFF* output){ unsigned int i=0; tsize_t written=0; char buffer[16]; int buflen=0; written += TIFFWriteFile(output, (tdata_t) "<<\r/Type /Page \r/Parent ", 24); buflen=sprintf(buffer, "%lu", (unsigned long)t2p->pdf_pages); written += TIFFWriteFile(output, (tdata_t) buffer, buflen); written += TIFFWriteFile(output, (tdata_t) " 0 R \r", 6); written += TIFFWriteFile(output, (tdata_t) "/MediaBox [", 11); buflen=sprintf(buffer, "%.4f",t2p->pdf_mediabox.x1); written += TIFFWriteFile(output, (tdata_t) buffer, buflen); written += TIFFWriteFile(output, (tdata_t) " ", 1); buflen=sprintf(buffer, "%.4f",t2p->pdf_mediabox.y1); written += TIFFWriteFile(output, (tdata_t) buffer, buflen); written += TIFFWriteFile(output, (tdata_t) " ", 1); buflen=sprintf(buffer, "%.4f",t2p->pdf_mediabox.x2); written += TIFFWriteFile(output, (tdata_t) buffer, buflen); written += TIFFWriteFile(output, (tdata_t) " ", 1); buflen=sprintf(buffer, "%.4f",t2p->pdf_mediabox.y2); written += TIFFWriteFile(output, (tdata_t) buffer, buflen); written += TIFFWriteFile(output, (tdata_t) "] \r", 3); written += TIFFWriteFile(output, (tdata_t) "/Contents ", 10); buflen=sprintf(buffer, "%lu", (unsigned long)(object + 1)); written += TIFFWriteFile(output, (tdata_t) buffer, buflen); written += TIFFWriteFile(output, (tdata_t) " 0 R \r", 6); written += TIFFWriteFile(output, (tdata_t) "/Resources << \r", 15); if( t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount != 0 ){ written += TIFFWriteFile(output, (tdata_t) "/XObject <<\r", 12); for(i=0;i<t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount;i++){ written += TIFFWriteFile(output, (tdata_t) "/Im", 3); buflen = sprintf(buffer, "%u", t2p->pdf_page+1); written += TIFFWriteFile(output, (tdata_t) buffer, buflen); written += TIFFWriteFile(output, (tdata_t) "_", 1); buflen = sprintf(buffer, "%u", i+1); written += TIFFWriteFile(output, (tdata_t) buffer, buflen); written += TIFFWriteFile(output, (tdata_t) " ", 1); buflen = sprintf( buffer, "%lu", (unsigned long)(object+3+(2*i)+t2p->tiff_pages[t2p->pdf_page].page_extra)); written += TIFFWriteFile(output, (tdata_t) buffer, buflen); written += TIFFWriteFile(output, (tdata_t) " 0 R ", 5); if(i%4==3){ written += TIFFWriteFile(output, (tdata_t) "\r", 1); } } written += TIFFWriteFile(output, (tdata_t) ">>\r", 3); } else { written += TIFFWriteFile(output, (tdata_t) "/XObject <<\r", 12); written += TIFFWriteFile(output, (tdata_t) "/Im", 3); buflen = sprintf(buffer, "%u", t2p->pdf_page+1); written += TIFFWriteFile(output, (tdata_t) buffer, buflen); written += TIFFWriteFile(output, (tdata_t) " ", 1); buflen = sprintf( buffer, "%lu", (unsigned long)(object+3+(2*i)+t2p->tiff_pages[t2p->pdf_page].page_extra)); written += TIFFWriteFile(output, (tdata_t) buffer, buflen); written += TIFFWriteFile(output, (tdata_t) " 0 R ", 5); written += TIFFWriteFile(output, (tdata_t) ">>\r", 3); } if(t2p->tiff_transferfunctioncount != 0) { written += TIFFWriteFile(output, (tdata_t) "/ExtGState <<", 13); TIFFWriteFile(output, (tdata_t) "/GS1 ", 5); buflen = sprintf( buffer, "%lu", (unsigned long)(object + 3)); written += TIFFWriteFile(output, (tdata_t) buffer, buflen); written += TIFFWriteFile(output, (tdata_t) " 0 R ", 5); written += TIFFWriteFile(output, (tdata_t) ">> \r", 4); } written += TIFFWriteFile(output, (tdata_t) "/ProcSet [ ", 11); if(t2p->pdf_colorspace == T2P_CS_BILEVEL || t2p->pdf_colorspace == T2P_CS_GRAY ){ written += TIFFWriteFile(output, (tdata_t) "/ImageB ", 8); } else { written += TIFFWriteFile(output, (tdata_t) "/ImageC ", 8); if(t2p->pdf_colorspace & T2P_CS_PALETTE){ written += TIFFWriteFile(output, (tdata_t) "/ImageI ", 8); } } written += TIFFWriteFile(output, (tdata_t) "]\r>>\r>>\r", 8); return(written); } /* This function composes the page size and image and tile locations on a page. */ static void t2p_compose_pdf_page(T2P* t2p){ uint32 i=0; uint32 i2=0; T2P_TILE* tiles=NULL; T2P_BOX* boxp=NULL; uint32 tilecountx=0; uint32 tilecounty=0; uint32 tilewidth=0; uint32 tilelength=0; int istiled=0; float f=0; t2p->pdf_xres = t2p->tiff_xres; t2p->pdf_yres = t2p->tiff_yres; if(t2p->pdf_overrideres){ t2p->pdf_xres = t2p->pdf_defaultxres; t2p->pdf_yres = t2p->pdf_defaultyres; } if(t2p->pdf_xres==0.0){ t2p->pdf_xres = t2p->pdf_defaultxres; } if(t2p->pdf_yres==0.0){ t2p->pdf_yres = t2p->pdf_defaultyres; } t2p->pdf_imagewidth=((float)(t2p->tiff_width)) *72.0F / t2p->pdf_xres; t2p->pdf_imagelength=((float)(t2p->tiff_length)) *72.0F / t2p->pdf_yres; if(t2p->pdf_overridepagesize != 0){ t2p->pdf_pagewidth = t2p->pdf_defaultpagewidth; t2p->pdf_pagelength = t2p->pdf_defaultpagelength; } else { t2p->pdf_pagewidth = t2p->pdf_imagewidth; t2p->pdf_pagelength = t2p->pdf_imagelength; } t2p->pdf_mediabox.x1=0.0; t2p->pdf_mediabox.y1=0.0; t2p->pdf_mediabox.x2=t2p->pdf_pagewidth; t2p->pdf_mediabox.y2=t2p->pdf_pagelength; t2p->pdf_imagebox.x1=0.0; t2p->pdf_imagebox.y1=0.0; t2p->pdf_imagebox.x2=t2p->pdf_imagewidth; t2p->pdf_imagebox.y2=t2p->pdf_imagelength; if(t2p->pdf_overridepagesize!=0){ t2p->pdf_imagebox.x1+=((t2p->pdf_pagewidth-t2p->pdf_imagewidth)/2.0F); t2p->pdf_imagebox.y1+=((t2p->pdf_pagelength-t2p->pdf_imagelength)/2.0F); t2p->pdf_imagebox.x2+=((t2p->pdf_pagewidth-t2p->pdf_imagewidth)/2.0F); t2p->pdf_imagebox.y2+=((t2p->pdf_pagelength-t2p->pdf_imagelength)/2.0F); } if(t2p->tiff_orientation > 4){ f=t2p->pdf_mediabox.x2; t2p->pdf_mediabox.x2=t2p->pdf_mediabox.y2; t2p->pdf_mediabox.y2=f; } istiled=((t2p->tiff_tiles[t2p->pdf_page]).tiles_tilecount==0) ? 0 : 1; if(istiled==0){ t2p_compose_pdf_page_orient(&(t2p->pdf_imagebox), t2p->tiff_orientation); return; } else { tilewidth=(t2p->tiff_tiles[t2p->pdf_page]).tiles_tilewidth; tilelength=(t2p->tiff_tiles[t2p->pdf_page]).tiles_tilelength; tilecountx=(t2p->tiff_width + tilewidth -1)/ tilewidth; (t2p->tiff_tiles[t2p->pdf_page]).tiles_tilecountx=tilecountx; tilecounty=(t2p->tiff_length + tilelength -1)/ tilelength; (t2p->tiff_tiles[t2p->pdf_page]).tiles_tilecounty=tilecounty; (t2p->tiff_tiles[t2p->pdf_page]).tiles_edgetilewidth= t2p->tiff_width % tilewidth; (t2p->tiff_tiles[t2p->pdf_page]).tiles_edgetilelength= t2p->tiff_length % tilelength; tiles=(t2p->tiff_tiles[t2p->pdf_page]).tiles_tiles; for(i2=0;i2<tilecounty-1;i2++){ for(i=0;i<tilecountx-1;i++){ boxp=&(tiles[i2*tilecountx+i].tile_box); boxp->x1 = t2p->pdf_imagebox.x1 + ((float)(t2p->pdf_imagewidth * i * tilewidth) / (float)t2p->tiff_width); boxp->x2 = t2p->pdf_imagebox.x1 + ((float)(t2p->pdf_imagewidth * (i+1) * tilewidth) / (float)t2p->tiff_width); boxp->y1 = t2p->pdf_imagebox.y2 - ((float)(t2p->pdf_imagelength * (i2+1) * tilelength) / (float)t2p->tiff_length); boxp->y2 = t2p->pdf_imagebox.y2 - ((float)(t2p->pdf_imagelength * i2 * tilelength) / (float)t2p->tiff_length); } boxp=&(tiles[i2*tilecountx+i].tile_box); boxp->x1 = t2p->pdf_imagebox.x1 + ((float)(t2p->pdf_imagewidth * i * tilewidth) / (float)t2p->tiff_width); boxp->x2 = t2p->pdf_imagebox.x2; boxp->y1 = t2p->pdf_imagebox.y2 - ((float)(t2p->pdf_imagelength * (i2+1) * tilelength) / (float)t2p->tiff_length); boxp->y2 = t2p->pdf_imagebox.y2 - ((float)(t2p->pdf_imagelength * i2 * tilelength) / (float)t2p->tiff_length); } for(i=0;i<tilecountx-1;i++){ boxp=&(tiles[i2*tilecountx+i].tile_box); boxp->x1 = t2p->pdf_imagebox.x1 + ((float)(t2p->pdf_imagewidth * i * tilewidth) / (float)t2p->tiff_width); boxp->x2 = t2p->pdf_imagebox.x1 + ((float)(t2p->pdf_imagewidth * (i+1) * tilewidth) / (float)t2p->tiff_width); boxp->y1 = t2p->pdf_imagebox.y1; boxp->y2 = t2p->pdf_imagebox.y2 - ((float)(t2p->pdf_imagelength * i2 * tilelength) / (float)t2p->tiff_length); } boxp=&(tiles[i2*tilecountx+i].tile_box); boxp->x1 = t2p->pdf_imagebox.x1 + ((float)(t2p->pdf_imagewidth * i * tilewidth) / (float)t2p->tiff_width); boxp->x2 = t2p->pdf_imagebox.x2; boxp->y1 = t2p->pdf_imagebox.y1; boxp->y2 = t2p->pdf_imagebox.y2 - ((float)(t2p->pdf_imagelength * i2 * tilelength) / (float)t2p->tiff_length); } if(t2p->tiff_orientation==0 || t2p->tiff_orientation==1){ for(i=0;i<(t2p->tiff_tiles[t2p->pdf_page]).tiles_tilecount;i++){ t2p_compose_pdf_page_orient( &(tiles[i].tile_box) , 0); } return; } for(i=0;i<(t2p->tiff_tiles[t2p->pdf_page]).tiles_tilecount;i++){ boxp=&(tiles[i].tile_box); boxp->x1 -= t2p->pdf_imagebox.x1; boxp->x2 -= t2p->pdf_imagebox.x1; boxp->y1 -= t2p->pdf_imagebox.y1; boxp->y2 -= t2p->pdf_imagebox.y1; if(t2p->tiff_orientation==2 || t2p->tiff_orientation==3){ boxp->x1 = t2p->pdf_imagebox.x2 - t2p->pdf_imagebox.x1 - boxp->x1; boxp->x2 = t2p->pdf_imagebox.x2 - t2p->pdf_imagebox.x1 - boxp->x2; } if(t2p->tiff_orientation==3 || t2p->tiff_orientation==4){ boxp->y1 = t2p->pdf_imagebox.y2 - t2p->pdf_imagebox.y1 - boxp->y1; boxp->y2 = t2p->pdf_imagebox.y2 - t2p->pdf_imagebox.y1 - boxp->y2; } if(t2p->tiff_orientation==8 || t2p->tiff_orientation==5){ boxp->y1 = t2p->pdf_imagebox.y2 - t2p->pdf_imagebox.y1 - boxp->y1; boxp->y2 = t2p->pdf_imagebox.y2 - t2p->pdf_imagebox.y1 - boxp->y2; } if(t2p->tiff_orientation==5 || t2p->tiff_orientation==6){ boxp->x1 = t2p->pdf_imagebox.x2 - t2p->pdf_imagebox.x1 - boxp->x1; boxp->x2 = t2p->pdf_imagebox.x2 - t2p->pdf_imagebox.x1 - boxp->x2; } if(t2p->tiff_orientation > 4){ f=boxp->x1; boxp->x1 = boxp->y1; boxp->y1 = f; f=boxp->x2; boxp->x2 = boxp->y2; boxp->y2 = f; t2p_compose_pdf_page_orient_flip(boxp, t2p->tiff_orientation); } else { t2p_compose_pdf_page_orient(boxp, t2p->tiff_orientation); } } return; } static void t2p_compose_pdf_page_orient(T2P_BOX* boxp, uint16 orientation){ float m1[9]; float f=0.0; if( boxp->x1 > boxp->x2){ f=boxp->x1; boxp->x1=boxp->x2; boxp->x2 = f; } if( boxp->y1 > boxp->y2){ f=boxp->y1; boxp->y1=boxp->y2; boxp->y2 = f; } boxp->mat[0]=m1[0]=boxp->x2-boxp->x1; boxp->mat[1]=m1[1]=0.0; boxp->mat[2]=m1[2]=0.0; boxp->mat[3]=m1[3]=0.0; boxp->mat[4]=m1[4]=boxp->y2-boxp->y1; boxp->mat[5]=m1[5]=0.0; boxp->mat[6]=m1[6]=boxp->x1; boxp->mat[7]=m1[7]=boxp->y1; boxp->mat[8]=m1[8]=1.0; switch(orientation){ case 0: case 1: break; case 2: boxp->mat[0]=0.0F-m1[0]; boxp->mat[6]+=m1[0]; break; case 3: boxp->mat[0]=0.0F-m1[0]; boxp->mat[4]=0.0F-m1[4]; boxp->mat[6]+=m1[0]; boxp->mat[7]+=m1[4]; break; case 4: boxp->mat[4]=0.0F-m1[4]; boxp->mat[7]+=m1[4]; break; case 5: boxp->mat[0]=0.0F; boxp->mat[1]=0.0F-m1[0]; boxp->mat[3]=0.0F-m1[4]; boxp->mat[4]=0.0F; boxp->mat[6]+=m1[4]; boxp->mat[7]+=m1[0]; break; case 6: boxp->mat[0]=0.0F; boxp->mat[1]=0.0F-m1[0]; boxp->mat[3]=m1[4]; boxp->mat[4]=0.0F; boxp->mat[7]+=m1[0]; break; case 7: boxp->mat[0]=0.0F; boxp->mat[1]=m1[0]; boxp->mat[3]=m1[4]; boxp->mat[4]=0.0F; break; case 8: boxp->mat[0]=0.0F; boxp->mat[1]=m1[0]; boxp->mat[3]=0.0F-m1[4]; boxp->mat[4]=0.0F; boxp->mat[6]+=m1[4]; break; } return; } static void t2p_compose_pdf_page_orient_flip(T2P_BOX* boxp, uint16 orientation){ float m1[9]; float f=0.0; if( boxp->x1 > boxp->x2){ f=boxp->x1; boxp->x1=boxp->x2; boxp->x2 = f; } if( boxp->y1 > boxp->y2){ f=boxp->y1; boxp->y1=boxp->y2; boxp->y2 = f; } boxp->mat[0]=m1[0]=boxp->x2-boxp->x1; boxp->mat[1]=m1[1]=0.0F; boxp->mat[2]=m1[2]=0.0F; boxp->mat[3]=m1[3]=0.0F; boxp->mat[4]=m1[4]=boxp->y2-boxp->y1; boxp->mat[5]=m1[5]=0.0F; boxp->mat[6]=m1[6]=boxp->x1; boxp->mat[7]=m1[7]=boxp->y1; boxp->mat[8]=m1[8]=1.0F; switch(orientation){ case 5: boxp->mat[0]=0.0F; boxp->mat[1]=0.0F-m1[4]; boxp->mat[3]=0.0F-m1[0]; boxp->mat[4]=0.0F; boxp->mat[6]+=m1[0]; boxp->mat[7]+=m1[4]; break; case 6: boxp->mat[0]=0.0F; boxp->mat[1]=0.0F-m1[4]; boxp->mat[3]=m1[0]; boxp->mat[4]=0.0F; boxp->mat[7]+=m1[4]; break; case 7: boxp->mat[0]=0.0F; boxp->mat[1]=m1[4]; boxp->mat[3]=m1[0]; boxp->mat[4]=0.0F; break; case 8: boxp->mat[0]=0.0F; boxp->mat[1]=m1[4]; boxp->mat[3]=0.0F-m1[0]; boxp->mat[4]=0.0F; boxp->mat[6]+=m1[0]; break; } return; } /* This function writes a PDF Contents stream to output. */ static tsize_t t2p_write_pdf_page_content_stream(T2P* t2p, TIFF* output){ tsize_t written=0; ttile_t i=0; char buffer[512]; int buflen=0; T2P_BOX box; if(t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount>0){ for(i=0;i<t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount; i++){ box=t2p->tiff_tiles[t2p->pdf_page].tiles_tiles[i].tile_box; buflen=sprintf(buffer, "q %s %.4f %.4f %.4f %.4f %.4f %.4f cm /Im%d_%ld Do Q\r", t2p->tiff_transferfunctioncount?"/GS1 gs ":"", box.mat[0], box.mat[1], box.mat[3], box.mat[4], box.mat[6], box.mat[7], t2p->pdf_page + 1, (long)(i + 1)); written += t2p_write_pdf_stream(buffer, buflen, output); } } else { box=t2p->pdf_imagebox; buflen=sprintf(buffer, "q %s %.4f %.4f %.4f %.4f %.4f %.4f cm /Im%d Do Q\r", t2p->tiff_transferfunctioncount?"/GS1 gs ":"", box.mat[0], box.mat[1], box.mat[3], box.mat[4], box.mat[6], box.mat[7], t2p->pdf_page+1); written += t2p_write_pdf_stream(buffer, buflen, output); } return(written); } /* This function writes a PDF Image XObject stream dictionary to output. */ static tsize_t t2p_write_pdf_xobject_stream_dict(ttile_t tile, T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[16]; int buflen=0; written += t2p_write_pdf_stream_dict(0, t2p->pdf_xrefcount+1, output); written += TIFFWriteFile(output, (tdata_t) "/Type /XObject \r/Subtype /Image \r/Name /Im", 42); buflen=sprintf(buffer, "%u", t2p->pdf_page+1); written += TIFFWriteFile(output, (tdata_t) buffer, buflen); if(tile != 0){ written += TIFFWriteFile(output, (tdata_t) "_", 1); buflen=sprintf(buffer, "%lu", (unsigned long)tile); written += TIFFWriteFile(output, (tdata_t) buffer, buflen); } written += TIFFWriteFile(output, (tdata_t) "\r/Width ", 8); _TIFFmemset((tdata_t)buffer, 0x00, 16); if(tile==0){ buflen=sprintf(buffer, "%lu", (unsigned long)t2p->tiff_width); } else { if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile-1)!=0){ buflen=sprintf( buffer, "%lu", (unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth); } else { buflen=sprintf( buffer, "%lu", (unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth); } } written += TIFFWriteFile(output, (tdata_t) buffer, buflen); written += TIFFWriteFile(output, (tdata_t) "\r/Height ", 9); _TIFFmemset((tdata_t)buffer, 0x00, 16); if(tile==0){ buflen=sprintf(buffer, "%lu", (unsigned long)t2p->tiff_length); } else { if(t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile-1)!=0){ buflen=sprintf( buffer, "%lu", (unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength); } else { buflen=sprintf( buffer, "%lu", (unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength); } } written += TIFFWriteFile(output, (tdata_t) buffer, buflen); written += TIFFWriteFile(output, (tdata_t) "\r/BitsPerComponent ", 19); _TIFFmemset((tdata_t)buffer, 0x00, 16); buflen=sprintf(buffer, "%u", t2p->tiff_bitspersample); written += TIFFWriteFile(output, (tdata_t) buffer, buflen); written += TIFFWriteFile(output, (tdata_t) "\r/ColorSpace ", 13); written += t2p_write_pdf_xobject_cs(t2p, output); if (t2p->pdf_image_interpolate) written += TIFFWriteFile(output, (tdata_t) "\r/Interpolate true", 18); if( (t2p->pdf_switchdecode != 0) #ifdef CCITT_SUPPORT && ! (t2p->pdf_colorspace == T2P_CS_BILEVEL && t2p->pdf_compression == T2P_COMPRESS_G4) #endif ){ written += t2p_write_pdf_xobject_decode(t2p, output); } written += t2p_write_pdf_xobject_stream_filter(tile, t2p, output); return(written); } /* * This function writes a PDF Image XObject Colorspace name to output. */ static tsize_t t2p_write_pdf_xobject_cs(T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[128]; int buflen=0; float X_W=1.0; float Y_W=1.0; float Z_W=1.0; if( (t2p->pdf_colorspace & T2P_CS_ICCBASED) != 0){ written += t2p_write_pdf_xobject_icccs(t2p, output); return(written); } if( (t2p->pdf_colorspace & T2P_CS_PALETTE) != 0){ written += TIFFWriteFile(output, (tdata_t) "[ /Indexed ", 11); t2p->pdf_colorspace ^= T2P_CS_PALETTE; written += t2p_write_pdf_xobject_cs(t2p, output); t2p->pdf_colorspace |= T2P_CS_PALETTE; buflen=sprintf(buffer, "%u", (0x0001 << t2p->tiff_bitspersample)-1 ); written += TIFFWriteFile(output, (tdata_t) buffer, buflen); written += TIFFWriteFile(output, (tdata_t) " ", 1); _TIFFmemset(buffer, 0x00, 16); buflen=sprintf(buffer, "%lu", (unsigned long)t2p->pdf_palettecs ); written += TIFFWriteFile(output, (tdata_t) buffer, buflen); written += TIFFWriteFile(output, (tdata_t) " 0 R ]\r", 7); return(written); } if(t2p->pdf_colorspace & T2P_CS_BILEVEL){ written += TIFFWriteFile(output, (tdata_t) "/DeviceGray \r", 13); } if(t2p->pdf_colorspace & T2P_CS_GRAY){ if(t2p->pdf_colorspace & T2P_CS_CALGRAY){ written += t2p_write_pdf_xobject_calcs(t2p, output); } else { written += TIFFWriteFile(output, (tdata_t) "/DeviceGray \r", 13); } } if(t2p->pdf_colorspace & T2P_CS_RGB){ if(t2p->pdf_colorspace & T2P_CS_CALRGB){ written += t2p_write_pdf_xobject_calcs(t2p, output); } else { written += TIFFWriteFile(output, (tdata_t) "/DeviceRGB \r", 12); } } if(t2p->pdf_colorspace & T2P_CS_CMYK){ written += TIFFWriteFile(output, (tdata_t) "/DeviceCMYK \r", 13); } if(t2p->pdf_colorspace & T2P_CS_LAB){ written += TIFFWriteFile(output, (tdata_t) "[/Lab << \r", 10); written += TIFFWriteFile(output, (tdata_t) "/WhitePoint ", 12); X_W = t2p->tiff_whitechromaticities[0]; Y_W = t2p->tiff_whitechromaticities[1]; Z_W = 1.0F - (X_W + Y_W); X_W /= Y_W; Z_W /= Y_W; Y_W = 1.0F; buflen=sprintf(buffer, "[%.4f %.4f %.4f] \r", X_W, Y_W, Z_W); written += TIFFWriteFile(output, (tdata_t) buffer, buflen); X_W = 0.3457F; /* 0.3127F; */ /* D50, commented D65 */ Y_W = 0.3585F; /* 0.3290F; */ Z_W = 1.0F - (X_W + Y_W); X_W /= Y_W; Z_W /= Y_W; Y_W = 1.0F; buflen=sprintf(buffer, "[%.4f %.4f %.4f] \r", X_W, Y_W, Z_W); written += TIFFWriteFile(output, (tdata_t) buffer, buflen); written += TIFFWriteFile(output, (tdata_t) "/Range ", 7); buflen=sprintf(buffer, "[%d %d %d %d] \r", t2p->pdf_labrange[0], t2p->pdf_labrange[1], t2p->pdf_labrange[2], t2p->pdf_labrange[3]); written += TIFFWriteFile(output, (tdata_t) buffer, buflen); written += TIFFWriteFile(output, (tdata_t) ">>] \r", 5); } return(written); } static tsize_t t2p_write_pdf_transfer(T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[16]; int buflen=0; written += TIFFWriteFile(output, (tdata_t) "<< /Type /ExtGState \r/TR ", 25); if(t2p->tiff_transferfunctioncount == 1){ buflen=sprintf(buffer, "%lu", (unsigned long)(t2p->pdf_xrefcount + 1)); written += TIFFWriteFile(output, (tdata_t) buffer, buflen); written += TIFFWriteFile(output, (tdata_t) " 0 R ", 5); } else { written += TIFFWriteFile(output, (tdata_t) "[ ", 2); buflen=sprintf(buffer, "%lu", (unsigned long)(t2p->pdf_xrefcount + 1)); written += TIFFWriteFile(output, (tdata_t) buffer, buflen); written += TIFFWriteFile(output, (tdata_t) " 0 R ", 5); buflen=sprintf(buffer, "%lu", (unsigned long)(t2p->pdf_xrefcount + 2)); written += TIFFWriteFile(output, (tdata_t) buffer, buflen); written += TIFFWriteFile(output, (tdata_t) " 0 R ", 5); buflen=sprintf(buffer, "%lu", (unsigned long)(t2p->pdf_xrefcount + 3)); written += TIFFWriteFile(output, (tdata_t) buffer, buflen); written += TIFFWriteFile(output, (tdata_t) " 0 R ", 5); written += TIFFWriteFile(output, (tdata_t) "/Identity ] ", 12); } written += TIFFWriteFile(output, (tdata_t) " >> \r", 5); return(written); } static tsize_t t2p_write_pdf_transfer_dict(T2P* t2p, TIFF* output, uint16 i){ tsize_t written=0; char buffer[32]; int buflen=0; (void)i; // XXX written += TIFFWriteFile(output, (tdata_t) "/FunctionType 0 \r", 17); written += TIFFWriteFile(output, (tdata_t) "/Domain [0.0 1.0] \r", 19); written += TIFFWriteFile(output, (tdata_t) "/Range [0.0 1.0] \r", 18); buflen=sprintf(buffer, "/Size [%u] \r", (1<<t2p->tiff_bitspersample)); written += TIFFWriteFile(output, (tdata_t) buffer, buflen); written += TIFFWriteFile(output, (tdata_t) "/BitsPerSample 16 \r", 19); written += t2p_write_pdf_stream_dict(1<<(t2p->tiff_bitspersample+1), 0, output); return(written); } static tsize_t t2p_write_pdf_transfer_stream(T2P* t2p, TIFF* output, uint16 i){ tsize_t written=0; written += t2p_write_pdf_stream( t2p->tiff_transferfunction[i], (1<<(t2p->tiff_bitspersample+1)), output); return(written); } /* This function writes a PDF Image XObject Colorspace array to output. */ static tsize_t t2p_write_pdf_xobject_calcs(T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[128]; int buflen=0; float X_W=0.0; float Y_W=0.0; float Z_W=0.0; float X_R=0.0; float Y_R=0.0; float Z_R=0.0; float X_G=0.0; float Y_G=0.0; float Z_G=0.0; float X_B=0.0; float Y_B=0.0; float Z_B=0.0; float x_w=0.0; float y_w=0.0; float z_w=0.0; float x_r=0.0; float y_r=0.0; float x_g=0.0; float y_g=0.0; float x_b=0.0; float y_b=0.0; float R=1.0; float G=1.0; float B=1.0; written += TIFFWriteFile(output, (tdata_t) "[", 1); if(t2p->pdf_colorspace & T2P_CS_CALGRAY){ written += TIFFWriteFile(output, (tdata_t) "/CalGray ", 9); X_W = t2p->tiff_whitechromaticities[0]; Y_W = t2p->tiff_whitechromaticities[1]; Z_W = 1.0F - (X_W + Y_W); X_W /= Y_W; Z_W /= Y_W; Y_W = 1.0F; } if(t2p->pdf_colorspace & T2P_CS_CALRGB){ written += TIFFWriteFile(output, (tdata_t) "/CalRGB ", 8); x_w = t2p->tiff_whitechromaticities[0]; y_w = t2p->tiff_whitechromaticities[1]; x_r = t2p->tiff_primarychromaticities[0]; y_r = t2p->tiff_primarychromaticities[1]; x_g = t2p->tiff_primarychromaticities[2]; y_g = t2p->tiff_primarychromaticities[3]; x_b = t2p->tiff_primarychromaticities[4]; y_b = t2p->tiff_primarychromaticities[5]; z_w = y_w * ((x_g - x_b)*y_r - (x_r-x_b)*y_g + (x_r-x_g)*y_b); Y_R = (y_r/R) * ((x_g-x_b)*y_w - (x_w-x_b)*y_g + (x_w-x_g)*y_b) / z_w; X_R = Y_R * x_r / y_r; Z_R = Y_R * (((1-x_r)/y_r)-1); Y_G = ((0.0F-(y_g))/G) * ((x_r-x_b)*y_w - (x_w-x_b)*y_r + (x_w-x_r)*y_b) / z_w; X_G = Y_G * x_g / y_g; Z_G = Y_G * (((1-x_g)/y_g)-1); Y_B = (y_b/B) * ((x_r-x_g)*y_w - (x_w-x_g)*y_r + (x_w-x_r)*y_g) / z_w; X_B = Y_B * x_b / y_b; Z_B = Y_B * (((1-x_b)/y_b)-1); X_W = (X_R * R) + (X_G * G) + (X_B * B); Y_W = (Y_R * R) + (Y_G * G) + (Y_B * B); Z_W = (Z_R * R) + (Z_G * G) + (Z_B * B); X_W /= Y_W; Z_W /= Y_W; Y_W = 1.0; } written += TIFFWriteFile(output, (tdata_t) "<< \r", 4); if(t2p->pdf_colorspace & T2P_CS_CALGRAY){ written += TIFFWriteFile(output, (tdata_t) "/WhitePoint ", 12); buflen=sprintf(buffer, "[%.4f %.4f %.4f] \r", X_W, Y_W, Z_W); written += TIFFWriteFile(output, (tdata_t) buffer, buflen); written += TIFFWriteFile(output, (tdata_t) "/Gamma 2.2 \r", 12); } if(t2p->pdf_colorspace & T2P_CS_CALRGB){ written += TIFFWriteFile(output, (tdata_t) "/WhitePoint ", 12); buflen=sprintf(buffer, "[%.4f %.4f %.4f] \r", X_W, Y_W, Z_W); written += TIFFWriteFile(output, (tdata_t) buffer, buflen); written += TIFFWriteFile(output, (tdata_t) "/Matrix ", 8); buflen=sprintf(buffer, "[%.4f %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.4f] \r", X_R, Y_R, Z_R, X_G, Y_G, Z_G, X_B, Y_B, Z_B); written += TIFFWriteFile(output, (tdata_t) buffer, buflen); written += TIFFWriteFile(output, (tdata_t) "/Gamma [2.2 2.2 2.2] \r", 22); } written += TIFFWriteFile(output, (tdata_t) ">>] \r", 5); return(written); } /* This function writes a PDF Image XObject Colorspace array to output. */ static tsize_t t2p_write_pdf_xobject_icccs(T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[16]; int buflen=0; written += TIFFWriteFile(output, (tdata_t) "[/ICCBased ", 11); buflen=sprintf(buffer, "%lu", (unsigned long)t2p->pdf_icccs); written += TIFFWriteFile(output, (tdata_t) buffer, buflen); written += TIFFWriteFile(output, (tdata_t) " 0 R] \r", 7); return(written); } static tsize_t t2p_write_pdf_xobject_icccs_dict(T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[16]; int buflen=0; written += TIFFWriteFile(output, (tdata_t) "/N ", 3); buflen=sprintf(buffer, "%u \r", t2p->tiff_samplesperpixel); written += TIFFWriteFile(output, (tdata_t) buffer, buflen); written += TIFFWriteFile(output, (tdata_t) "/Alternate ", 11); t2p->pdf_colorspace ^= T2P_CS_ICCBASED; written += t2p_write_pdf_xobject_cs(t2p, output); t2p->pdf_colorspace |= T2P_CS_ICCBASED; written += t2p_write_pdf_stream_dict(t2p->tiff_iccprofilelength, 0, output); return(written); } static tsize_t t2p_write_pdf_xobject_icccs_stream(T2P* t2p, TIFF* output){ tsize_t written=0; written += t2p_write_pdf_stream( (tdata_t) t2p->tiff_iccprofile, (tsize_t) t2p->tiff_iccprofilelength, output); return(written); } /* This function writes a palette stream for an indexed color space to output. */ static tsize_t t2p_write_pdf_xobject_palettecs_stream(T2P* t2p, TIFF* output){ tsize_t written=0; written += t2p_write_pdf_stream( (tdata_t) t2p->pdf_palette, (tsize_t) t2p->pdf_palettesize, output); return(written); } /* This function writes a PDF Image XObject Decode array to output. */ static tsize_t t2p_write_pdf_xobject_decode(T2P* t2p, TIFF* output){ tsize_t written=0; int i=0; written += TIFFWriteFile(output, (tdata_t) "/Decode [ ", 10); for (i=0;i<t2p->tiff_samplesperpixel;i++){ written += TIFFWriteFile(output, (tdata_t) "1 0 ", 4); } written += TIFFWriteFile(output, (tdata_t) "]\r", 2); return(written); } /* This function writes a PDF Image XObject stream filter name and parameters to output. */ static tsize_t t2p_write_pdf_xobject_stream_filter(ttile_t tile, T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[16]; int buflen=0; if(t2p->pdf_compression==T2P_COMPRESS_NONE){ return(written); } written += TIFFWriteFile(output, (tdata_t) "/Filter ", 8); switch(t2p->pdf_compression){ #ifdef CCITT_SUPPORT case T2P_COMPRESS_G4: written += TIFFWriteFile(output, (tdata_t) "/CCITTFaxDecode ", 16); written += TIFFWriteFile(output, (tdata_t) "/DecodeParms ", 13); written += TIFFWriteFile(output, (tdata_t) "<< /K -1 ", 9); if(tile==0){ written += TIFFWriteFile(output, (tdata_t) "/Columns ", 9); buflen=sprintf(buffer, "%lu", (unsigned long)t2p->tiff_width); written += TIFFWriteFile(output, (tdata_t) buffer, buflen); written += TIFFWriteFile(output, (tdata_t) " /Rows ", 7); buflen=sprintf(buffer, "%lu", (unsigned long)t2p->tiff_length); written += TIFFWriteFile(output, (tdata_t) buffer, buflen); } else { if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile-1)==0){ written += TIFFWriteFile(output, (tdata_t) "/Columns ", 9); buflen=sprintf( buffer, "%lu", (unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth); written += TIFFWriteFile(output, (tdata_t) buffer, buflen); } else { written += TIFFWriteFile(output, (tdata_t) "/Columns ", 9); buflen=sprintf( buffer, "%lu", (unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth); written += TIFFWriteFile(output, (tdata_t) buffer, buflen); } if(t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile-1)==0){ written += TIFFWriteFile(output, (tdata_t) " /Rows ", 7); buflen=sprintf( buffer, "%lu", (unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength); written += TIFFWriteFile(output, (tdata_t) buffer, buflen); } else { written += TIFFWriteFile(output, (tdata_t) " /Rows ", 7); buflen=sprintf( buffer, "%lu", (unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength); written += TIFFWriteFile(output, (tdata_t) buffer, buflen); } } if(t2p->pdf_switchdecode == 0){ written += TIFFWriteFile(output, (tdata_t) " /BlackIs1 true ", 16); } written += TIFFWriteFile(output, (tdata_t) ">>\r", 3); break; #endif #ifdef JPEG_SUPPORT case T2P_COMPRESS_JPEG: written += TIFFWriteFile(output, (tdata_t) "/DCTDecode ", 11); if(t2p->tiff_photometric != PHOTOMETRIC_YCBCR) { written += TIFFWriteFile(output, (tdata_t) "/DecodeParms ", 13); written += TIFFWriteFile(output, (tdata_t) "<< /ColorTransform 0 >>\r", 24); } break; #endif #ifdef ZIP_SUPPORT case T2P_COMPRESS_ZIP: written += TIFFWriteFile(output, (tdata_t) "/FlateDecode ", 13); if(t2p->pdf_compressionquality%100){ written += TIFFWriteFile(output, (tdata_t) "/DecodeParms ", 13); written += TIFFWriteFile(output, (tdata_t) "<< /Predictor ", 14); _TIFFmemset(buffer, 0x00, 16); buflen=sprintf(buffer, "%u", t2p->pdf_compressionquality%100); written += TIFFWriteFile(output, (tdata_t) buffer, buflen); written += TIFFWriteFile(output, (tdata_t) " /Columns ", 10); _TIFFmemset(buffer, 0x00, 16); buflen = sprintf(buffer, "%lu", (unsigned long)t2p->tiff_width); written += TIFFWriteFile(output, (tdata_t) buffer, buflen); written += TIFFWriteFile(output, (tdata_t) " /Colors ", 9); _TIFFmemset(buffer, 0x00, 16); buflen=sprintf(buffer, "%u", t2p->tiff_samplesperpixel); written += TIFFWriteFile(output, (tdata_t) buffer, buflen); written += TIFFWriteFile(output, (tdata_t) " /BitsPerComponent ", 19); _TIFFmemset(buffer, 0x00, 16); buflen=sprintf(buffer, "%u", t2p->tiff_bitspersample); written += TIFFWriteFile(output, (tdata_t) buffer, buflen); written += TIFFWriteFile(output, (tdata_t) ">>\r", 3); } break; #endif default: break; } return(written); } /* This function writes a PDF xref table to output. */ static tsize_t t2p_write_pdf_xreftable(T2P* t2p, TIFF* output){ tsize_t written=0; char buffer[21]; int buflen=0; uint32 i=0; written += TIFFWriteFile(output, (tdata_t) "xref\r0 ", 7); buflen=sprintf(buffer, "%lu", (unsigned long)(t2p->pdf_xrefcount + 1)); written += TIFFWriteFile(output, (tdata_t) buffer, buflen); written += TIFFWriteFile(output, (tdata_t) " \r0000000000 65535 f\r\n", 22); for (i=0;i<t2p->pdf_xrefcount;i++){ sprintf(buffer, "%.10lu 00000 n\r\n", (unsigned long)t2p->pdf_xrefoffsets[i]); written += TIFFWriteFile(output, (tdata_t) buffer, 20); } return(written); } /* * This function writes a PDF trailer to output. */ static tsize_t t2p_write_pdf_trailer(T2P* t2p, TIFF* output) { tsize_t written = 0; char buffer[32]; int buflen = 0; int ifileidbuf[4]; char *fileidbuf = (char*)ifileidbuf; int i = 0; ifileidbuf[0] = rand(); ifileidbuf[1] = rand(); ifileidbuf[2] = rand(); ifileidbuf[3] = rand(); t2p->pdf_fileid = (char*)_TIFFmalloc(33); if(t2p->pdf_fileid == NULL) { TIFFError( TIFF2PDF_MODULE, "Can't allocate %u bytes of memory for t2p_write_pdf_trailer", 33 ); t2p->t2p_error = T2P_ERR_ERROR; return(0); } _TIFFmemset(t2p->pdf_fileid, 0x00, 33); for (i=0; i<16; i++) sprintf(&(t2p->pdf_fileid[2*i]), "%.2hhX", fileidbuf[i]); written += TIFFWriteFile(output, (tdata_t) "trailer\r<<\r/Size ", 17); buflen = sprintf(buffer, "%lu", (unsigned long)(t2p->pdf_xrefcount+1)); written += TIFFWriteFile(output, (tdata_t) buffer, buflen); _TIFFmemset(buffer, 0x00, 32); written += TIFFWriteFile(output, (tdata_t) "\r/Root ", 7); buflen=sprintf(buffer, "%lu", (unsigned long)t2p->pdf_catalog); written += TIFFWriteFile(output, (tdata_t) buffer, buflen); _TIFFmemset(buffer, 0x00, 32); written += TIFFWriteFile(output, (tdata_t) " 0 R \r/Info ", 12); buflen=sprintf(buffer, "%lu", (unsigned long)t2p->pdf_info); written += TIFFWriteFile(output, (tdata_t) buffer, buflen); _TIFFmemset(buffer, 0x00, 32); written += TIFFWriteFile(output, (tdata_t) " 0 R \r/ID[<", 11); written += TIFFWriteFile(output, (tdata_t) t2p->pdf_fileid, 32); written += TIFFWriteFile(output, (tdata_t) "><", 2); written += TIFFWriteFile(output, (tdata_t) t2p->pdf_fileid, 32); written += TIFFWriteFile(output, (tdata_t) ">]\r>>\rstartxref\r", 16); buflen=sprintf(buffer, "%lu", (unsigned long)t2p->pdf_startxref); written += TIFFWriteFile(output, (tdata_t) buffer, buflen); _TIFFmemset(buffer, 0x00, 32); written += TIFFWriteFile(output, (tdata_t) "\r%%EOF\r", 7); return(written); } /* This function writes a PDF to a file given a pointer to a TIFF. The idea with using a TIFF* as output for a PDF file is that the file can be created with TIFFClientOpen for memory-mapped use within the TIFF library, and TIFFWriteEncodedStrip can be used to write compressed data to the output. The output is not actually a TIFF file, it is a PDF file. This function uses only TIFFWriteFile and TIFFWriteEncodedStrip to write to the output TIFF file. When libtiff would otherwise be writing data to the output file, the write procedure of the TIFF structure is replaced with an empty implementation. The first argument to the function is an initialized and validated T2P context struct pointer. The second argument to the function is the TIFF* that is the input that has been opened for reading and no other functions have been called upon it. The third argument to the function is the TIFF* that is the output that has been opened for writing. It has to be opened so that it hasn't written any data to the output. If the output is seekable then it's OK to seek to the beginning of the file. The function only writes to the output PDF and does not seek. See the example usage in the main() function. TIFF* output = TIFFOpen("output.pdf", "w"); assert(output != NULL); if(output->tif_seekproc != NULL){ TIFFSeekFile(output, (toff_t) 0, SEEK_SET); } This function returns the file size of the output PDF file. On error it returns zero and the t2p->t2p_error variable is set to T2P_ERR_ERROR. After this function completes, call t2p_free on t2p, TIFFClose on input, and TIFFClose on output. */ static tsize_t t2p_write_pdf(T2P* t2p, TIFF* input, TIFF* output){ tsize_t written=0; ttile_t i2=0; tsize_t streamlen=0; uint16 i=0; t2p_read_tiff_init(t2p, input); if(t2p->t2p_error!=T2P_ERR_OK){return(0);} t2p->pdf_xrefoffsets= (uint32*) _TIFFmalloc(t2p->pdf_xrefcount * sizeof(uint32) ); if(t2p->pdf_xrefoffsets==NULL){ TIFFError( TIFF2PDF_MODULE, "Can't allocate %lu bytes of memory for t2p_write_pdf", t2p->pdf_xrefcount * sizeof(uint32) ); return(written); } t2p->pdf_xrefcount=0; t2p->pdf_catalog=1; t2p->pdf_info=2; t2p->pdf_pages=3; written += t2p_write_pdf_header(t2p, output); t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; t2p->pdf_catalog=t2p->pdf_xrefcount; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_catalog(t2p, output); written += t2p_write_pdf_obj_end(output); t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; t2p->pdf_info=t2p->pdf_xrefcount; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_info(t2p, input, output); written += t2p_write_pdf_obj_end(output); t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; t2p->pdf_pages=t2p->pdf_xrefcount; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_pages(t2p, output); written += t2p_write_pdf_obj_end(output); for(t2p->pdf_page=0;t2p->pdf_page<t2p->tiff_pagecount;t2p->pdf_page++){ t2p_read_tiff_data(t2p, input); if(t2p->t2p_error!=T2P_ERR_OK){return(0);} t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_page(t2p->pdf_xrefcount, t2p, output); written += t2p_write_pdf_obj_end(output); t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_stream_dict_start(output); written += t2p_write_pdf_stream_dict(0, t2p->pdf_xrefcount+1, output); written += t2p_write_pdf_stream_dict_end(output); written += t2p_write_pdf_stream_start(output); streamlen=written; written += t2p_write_pdf_page_content_stream(t2p, output); streamlen=written-streamlen; written += t2p_write_pdf_stream_end(output); written += t2p_write_pdf_obj_end(output); t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_stream_length(streamlen, output); written += t2p_write_pdf_obj_end(output); if(t2p->tiff_transferfunctioncount != 0){ t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_transfer(t2p, output); written += t2p_write_pdf_obj_end(output); for(i=0; i < t2p->tiff_transferfunctioncount; i++){ t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_stream_dict_start(output); written += t2p_write_pdf_transfer_dict(t2p, output, i); written += t2p_write_pdf_stream_dict_end(output); written += t2p_write_pdf_stream_start(output); streamlen=written; written += t2p_write_pdf_transfer_stream(t2p, output, i); streamlen=written-streamlen; written += t2p_write_pdf_stream_end(output); written += t2p_write_pdf_obj_end(output); } } if( (t2p->pdf_colorspace & T2P_CS_PALETTE) != 0){ t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; t2p->pdf_palettecs=t2p->pdf_xrefcount; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_stream_dict_start(output); written += t2p_write_pdf_stream_dict(t2p->pdf_palettesize, 0, output); written += t2p_write_pdf_stream_dict_end(output); written += t2p_write_pdf_stream_start(output); streamlen=written; written += t2p_write_pdf_xobject_palettecs_stream(t2p, output); streamlen=written-streamlen; written += t2p_write_pdf_stream_end(output); written += t2p_write_pdf_obj_end(output); } if( (t2p->pdf_colorspace & T2P_CS_ICCBASED) != 0){ t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; t2p->pdf_icccs=t2p->pdf_xrefcount; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_stream_dict_start(output); written += t2p_write_pdf_xobject_icccs_dict(t2p, output); written += t2p_write_pdf_stream_dict_end(output); written += t2p_write_pdf_stream_start(output); streamlen=written; written += t2p_write_pdf_xobject_icccs_stream(t2p, output); streamlen=written-streamlen; written += t2p_write_pdf_stream_end(output); written += t2p_write_pdf_obj_end(output); } if(t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount !=0){ for(i2=0;i2<t2p->tiff_tiles[t2p->pdf_page].tiles_tilecount;i2++){ t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_stream_dict_start(output); written += t2p_write_pdf_xobject_stream_dict( i2+1, t2p, output); written += t2p_write_pdf_stream_dict_end(output); written += t2p_write_pdf_stream_start(output); streamlen=written; t2p_read_tiff_size_tile(t2p, input, i2); written += t2p_readwrite_pdf_image_tile(t2p, input, output, i2); t2p_write_advance_directory(t2p, output); if(t2p->t2p_error!=T2P_ERR_OK){return(0);} streamlen=written-streamlen; written += t2p_write_pdf_stream_end(output); written += t2p_write_pdf_obj_end(output); t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_stream_length(streamlen, output); written += t2p_write_pdf_obj_end(output); } } else { t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_stream_dict_start(output); written += t2p_write_pdf_xobject_stream_dict( 0, t2p, output); written += t2p_write_pdf_stream_dict_end(output); written += t2p_write_pdf_stream_start(output); streamlen=written; t2p_read_tiff_size(t2p, input); written += t2p_readwrite_pdf_image(t2p, input, output); t2p_write_advance_directory(t2p, output); if(t2p->t2p_error!=T2P_ERR_OK){return(0);} streamlen=written-streamlen; written += t2p_write_pdf_stream_end(output); written += t2p_write_pdf_obj_end(output); t2p->pdf_xrefoffsets[t2p->pdf_xrefcount++]=written; written += t2p_write_pdf_obj_start(t2p->pdf_xrefcount, output); written += t2p_write_pdf_stream_length(streamlen, output); written += t2p_write_pdf_obj_end(output); } } t2p->pdf_startxref=written; written += t2p_write_pdf_xreftable(t2p, output); written += t2p_write_pdf_trailer(t2p, output); t2p_disable(output); return(written); } #endif /* vim: set ts=8 sts=8 sw=8 noet: */
Stannislav/djvulibre-3.5.25
tools/tiff2pdf.c
C
gpl-2.0
159,904
/* * Copyright (c) 1999-2005 Petko Manolov (petkan@users.sourceforge.net) * * 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. * * ChangeLog: * .... Most of the time spent on reading sources & docs. * v0.2.x First official release for the Linux kernel. * v0.3.0 Beutified and structured, some bugs fixed. * v0.3.x URBifying bulk requests and bugfixing. First relatively * stable release. Still can touch device's registers only * from top-halves. * v0.4.0 Control messages remained unurbified are now URBs. * Now we can touch the HW at any time. * v0.4.9 Control urbs again use process context to wait. Argh... * Some long standing bugs (enable_net_traffic) fixed. * Also nasty trick about resubmiting control urb from * interrupt context used. Please let me know how it * behaves. Pegasus II support added since this version. * TODO: suppressing HCD warnings spewage on disconnect. * v0.4.13 Ethernet address is now set at probe(), not at open() * time as this seems to break dhcpd. * v0.5.0 branch to 2.5.x kernels * v0.5.1 ethtool support added * v0.5.5 rx socket buffers are in a pool and the their allocation * is out of the interrupt routine. */ #undef DEBUG #include <linux/sched.h> #include <linux/slab.h> #include <linux/init.h> #include <linux/delay.h> #include <linux/netdevice.h> #include <linux/etherdevice.h> #include <linux/ethtool.h> #include <linux/mii.h> #include <linux/usb.h> #include <linux/module.h> #include <asm/byteorder.h> #include <asm/uaccess.h> #include "pegasus.h" /* * Version Information */ #define DRIVER_VERSION "v0.6.12 (2005/01/13)" #define DRIVER_AUTHOR "Petko Manolov <petkan@users.sourceforge.net>" #define DRIVER_DESC "Pegasus/Pegasus II USB Ethernet driver" static const char driver_name[] = "pegasus"; #undef PEGASUS_WRITE_EEPROM #define BMSR_MEDIA (BMSR_10HALF | BMSR_10FULL | BMSR_100HALF | \ BMSR_100FULL | BMSR_ANEGCAPABLE) static int loopback = 0; static int mii_mode = 0; static struct usb_eth_dev usb_dev_id[] = { #define PEGASUS_DEV(pn, vid, pid, flags) \ {.name = pn, .vendor = vid, .device = pid, .private = flags}, #include "pegasus.h" #undef PEGASUS_DEV {NULL, 0, 0, 0} }; static struct usb_device_id pegasus_ids[] = { #define PEGASUS_DEV(pn, vid, pid, flags) \ {.match_flags = USB_DEVICE_ID_MATCH_DEVICE, .idVendor = vid, .idProduct = pid}, #include "pegasus.h" #undef PEGASUS_DEV {} }; MODULE_AUTHOR(DRIVER_AUTHOR); MODULE_DESCRIPTION(DRIVER_DESC); MODULE_LICENSE("GPL"); module_param(loopback, bool, 0); module_param(mii_mode, bool, 0); MODULE_PARM_DESC(loopback, "Enable MAC loopback mode (bit 0)"); MODULE_PARM_DESC(mii_mode, "Enable HomePNA mode (bit 0),default=MII mode = 0"); /* use ethtool to change the level for any given device */ static int msg_level = -1; module_param (msg_level, int, 0); MODULE_PARM_DESC (msg_level, "Override default message level"); MODULE_DEVICE_TABLE(usb, pegasus_ids); static int update_eth_regs_async(pegasus_t *); /* Aargh!!! I _really_ hate such tweaks */ static void ctrl_callback(struct urb *urb, struct pt_regs *regs) { pegasus_t *pegasus = urb->context; if (!pegasus) return; switch (urb->status) { case 0: if (pegasus->flags & ETH_REGS_CHANGE) { pegasus->flags &= ~ETH_REGS_CHANGE; pegasus->flags |= ETH_REGS_CHANGED; update_eth_regs_async(pegasus); return; } break; case -EINPROGRESS: return; case -ENOENT: break; default: if (netif_msg_drv(pegasus)) dev_err(&pegasus->intf->dev, "%s, status %d\n", __FUNCTION__, urb->status); } pegasus->flags &= ~ETH_REGS_CHANGED; wake_up(&pegasus->ctrl_wait); } static int get_registers(pegasus_t * pegasus, __u16 indx, __u16 size, void *data) { int ret; char *buffer; DECLARE_WAITQUEUE(wait, current); buffer = kmalloc(size, GFP_KERNEL); if (!buffer) { if (netif_msg_drv(pegasus)) dev_warn(&pegasus->intf->dev, "out of memory in %s\n", __FUNCTION__); return -ENOMEM; } add_wait_queue(&pegasus->ctrl_wait, &wait); set_current_state(TASK_UNINTERRUPTIBLE); while (pegasus->flags & ETH_REGS_CHANGED) schedule(); remove_wait_queue(&pegasus->ctrl_wait, &wait); set_current_state(TASK_RUNNING); pegasus->dr.bRequestType = PEGASUS_REQT_READ; pegasus->dr.bRequest = PEGASUS_REQ_GET_REGS; pegasus->dr.wValue = cpu_to_le16(0); pegasus->dr.wIndex = cpu_to_le16p(&indx); pegasus->dr.wLength = cpu_to_le16p(&size); pegasus->ctrl_urb->transfer_buffer_length = size; usb_fill_control_urb(pegasus->ctrl_urb, pegasus->usb, usb_rcvctrlpipe(pegasus->usb, 0), (char *) &pegasus->dr, buffer, size, ctrl_callback, pegasus); add_wait_queue(&pegasus->ctrl_wait, &wait); set_current_state(TASK_UNINTERRUPTIBLE); /* using ATOMIC, we'd never wake up if we slept */ if ((ret = usb_submit_urb(pegasus->ctrl_urb, GFP_ATOMIC))) { if (netif_msg_drv(pegasus)) dev_err(&pegasus->intf->dev, "%s, status %d\n", __FUNCTION__, ret); goto out; } schedule(); out: remove_wait_queue(&pegasus->ctrl_wait, &wait); memcpy(data, buffer, size); kfree(buffer); return ret; } static int set_registers(pegasus_t * pegasus, __u16 indx, __u16 size, void *data) { int ret; char *buffer; DECLARE_WAITQUEUE(wait, current); buffer = kmalloc(size, GFP_KERNEL); if (!buffer) { if (netif_msg_drv(pegasus)) dev_warn(&pegasus->intf->dev, "out of memory in %s\n", __FUNCTION__); return -ENOMEM; } memcpy(buffer, data, size); add_wait_queue(&pegasus->ctrl_wait, &wait); set_current_state(TASK_UNINTERRUPTIBLE); while (pegasus->flags & ETH_REGS_CHANGED) schedule(); remove_wait_queue(&pegasus->ctrl_wait, &wait); set_current_state(TASK_RUNNING); pegasus->dr.bRequestType = PEGASUS_REQT_WRITE; pegasus->dr.bRequest = PEGASUS_REQ_SET_REGS; pegasus->dr.wValue = cpu_to_le16(0); pegasus->dr.wIndex = cpu_to_le16p(&indx); pegasus->dr.wLength = cpu_to_le16p(&size); pegasus->ctrl_urb->transfer_buffer_length = size; usb_fill_control_urb(pegasus->ctrl_urb, pegasus->usb, usb_sndctrlpipe(pegasus->usb, 0), (char *) &pegasus->dr, buffer, size, ctrl_callback, pegasus); add_wait_queue(&pegasus->ctrl_wait, &wait); set_current_state(TASK_UNINTERRUPTIBLE); if ((ret = usb_submit_urb(pegasus->ctrl_urb, GFP_ATOMIC))) { if (netif_msg_drv(pegasus)) dev_err(&pegasus->intf->dev, "%s, status %d\n", __FUNCTION__, ret); goto out; } schedule(); out: remove_wait_queue(&pegasus->ctrl_wait, &wait); kfree(buffer); return ret; } static int set_register(pegasus_t * pegasus, __u16 indx, __u8 data) { int ret; char *tmp; DECLARE_WAITQUEUE(wait, current); tmp = kmalloc(1, GFP_KERNEL); if (!tmp) { if (netif_msg_drv(pegasus)) dev_warn(&pegasus->intf->dev, "out of memory in %s\n", __FUNCTION__); return -ENOMEM; } memcpy(tmp, &data, 1); add_wait_queue(&pegasus->ctrl_wait, &wait); set_current_state(TASK_UNINTERRUPTIBLE); while (pegasus->flags & ETH_REGS_CHANGED) schedule(); remove_wait_queue(&pegasus->ctrl_wait, &wait); set_current_state(TASK_RUNNING); pegasus->dr.bRequestType = PEGASUS_REQT_WRITE; pegasus->dr.bRequest = PEGASUS_REQ_SET_REG; pegasus->dr.wValue = cpu_to_le16(data); pegasus->dr.wIndex = cpu_to_le16p(&indx); pegasus->dr.wLength = cpu_to_le16(1); pegasus->ctrl_urb->transfer_buffer_length = 1; usb_fill_control_urb(pegasus->ctrl_urb, pegasus->usb, usb_sndctrlpipe(pegasus->usb, 0), (char *) &pegasus->dr, &tmp, 1, ctrl_callback, pegasus); add_wait_queue(&pegasus->ctrl_wait, &wait); set_current_state(TASK_UNINTERRUPTIBLE); if ((ret = usb_submit_urb(pegasus->ctrl_urb, GFP_ATOMIC))) { if (netif_msg_drv(pegasus)) dev_err(&pegasus->intf->dev, "%s, status %d\n", __FUNCTION__, ret); goto out; } schedule(); out: remove_wait_queue(&pegasus->ctrl_wait, &wait); kfree(tmp); return ret; } static int update_eth_regs_async(pegasus_t * pegasus) { int ret; pegasus->dr.bRequestType = PEGASUS_REQT_WRITE; pegasus->dr.bRequest = PEGASUS_REQ_SET_REGS; pegasus->dr.wValue = 0; pegasus->dr.wIndex = cpu_to_le16(EthCtrl0); pegasus->dr.wLength = cpu_to_le16(3); pegasus->ctrl_urb->transfer_buffer_length = 3; usb_fill_control_urb(pegasus->ctrl_urb, pegasus->usb, usb_sndctrlpipe(pegasus->usb, 0), (char *) &pegasus->dr, pegasus->eth_regs, 3, ctrl_callback, pegasus); if ((ret = usb_submit_urb(pegasus->ctrl_urb, GFP_ATOMIC))) if (netif_msg_drv(pegasus)) dev_err(&pegasus->intf->dev, "%s, status %d\n", __FUNCTION__, ret); return ret; } static int read_mii_word(pegasus_t * pegasus, __u8 phy, __u8 indx, __u16 * regd) { int i; __u8 data[4] = { phy, 0, 0, indx }; __le16 regdi; int ret; ret = set_register(pegasus, PhyCtrl, 0); ret = set_registers(pegasus, PhyAddr, sizeof (data), data); ret = set_register(pegasus, PhyCtrl, (indx | PHY_READ)); for (i = 0; i < REG_TIMEOUT; i++) { ret = get_registers(pegasus, PhyCtrl, 1, data); if (data[0] & PHY_DONE) break; } if (i < REG_TIMEOUT) { ret = get_registers(pegasus, PhyData, 2, &regdi); *regd = le16_to_cpu(regdi); return 1; } if (netif_msg_drv(pegasus)) dev_warn(&pegasus->intf->dev, "fail %s\n", __FUNCTION__); return 0; } static int mdio_read(struct net_device *dev, int phy_id, int loc) { pegasus_t *pegasus = (pegasus_t *) netdev_priv(dev); u16 res; read_mii_word(pegasus, phy_id, loc, &res); return (int)res; } static int write_mii_word(pegasus_t * pegasus, __u8 phy, __u8 indx, __u16 regd) { int i; __u8 data[4] = { phy, 0, 0, indx }; int ret; data[1] = (u8) regd; data[2] = (u8) (regd >> 8); ret = set_register(pegasus, PhyCtrl, 0); ret = set_registers(pegasus, PhyAddr, sizeof(data), data); ret = set_register(pegasus, PhyCtrl, (indx | PHY_WRITE)); for (i = 0; i < REG_TIMEOUT; i++) { ret = get_registers(pegasus, PhyCtrl, 1, data); if (data[0] & PHY_DONE) break; } if (i < REG_TIMEOUT) return 0; if (netif_msg_drv(pegasus)) dev_warn(&pegasus->intf->dev, "fail %s\n", __FUNCTION__); return 1; } static void mdio_write(struct net_device *dev, int phy_id, int loc, int val) { pegasus_t *pegasus = (pegasus_t *) netdev_priv(dev); write_mii_word(pegasus, phy_id, loc, val); } static int read_eprom_word(pegasus_t * pegasus, __u8 index, __u16 * retdata) { int i; __u8 tmp; __le16 retdatai; int ret; ret = set_register(pegasus, EpromCtrl, 0); ret = set_register(pegasus, EpromOffset, index); ret = set_register(pegasus, EpromCtrl, EPROM_READ); for (i = 0; i < REG_TIMEOUT; i++) { ret = get_registers(pegasus, EpromCtrl, 1, &tmp); if (tmp & EPROM_DONE) break; } if (i < REG_TIMEOUT) { ret = get_registers(pegasus, EpromData, 2, &retdatai); *retdata = le16_to_cpu(retdatai); return 0; } if (netif_msg_drv(pegasus)) dev_warn(&pegasus->intf->dev, "fail %s\n", __FUNCTION__); return -1; } #ifdef PEGASUS_WRITE_EEPROM static inline void enable_eprom_write(pegasus_t * pegasus) { __u8 tmp; int ret; ret = get_registers(pegasus, EthCtrl2, 1, &tmp); ret = set_register(pegasus, EthCtrl2, tmp | EPROM_WR_ENABLE); } static inline void disable_eprom_write(pegasus_t * pegasus) { __u8 tmp; int ret; ret = get_registers(pegasus, EthCtrl2, 1, &tmp); ret = set_register(pegasus, EpromCtrl, 0); ret = set_register(pegasus, EthCtrl2, tmp & ~EPROM_WR_ENABLE); } static int write_eprom_word(pegasus_t * pegasus, __u8 index, __u16 data) { int i; __u8 tmp, d[4] = { 0x3f, 0, 0, EPROM_WRITE }; int ret; ret = set_registers(pegasus, EpromOffset, 4, d); enable_eprom_write(pegasus); ret = set_register(pegasus, EpromOffset, index); ret = set_registers(pegasus, EpromData, 2, &data); ret = set_register(pegasus, EpromCtrl, EPROM_WRITE); for (i = 0; i < REG_TIMEOUT; i++) { ret = get_registers(pegasus, EpromCtrl, 1, &tmp); if (tmp & EPROM_DONE) break; } disable_eprom_write(pegasus); if (i < REG_TIMEOUT) return 0; if (netif_msg_drv(pegasus)) dev_warn(&pegasus->intf->dev, "fail %s\n", __FUNCTION__); return -1; } #endif /* PEGASUS_WRITE_EEPROM */ static inline void get_node_id(pegasus_t * pegasus, __u8 * id) { int i; __u16 w16; for (i = 0; i < 3; i++) { read_eprom_word(pegasus, i, &w16); ((__le16 *) id)[i] = cpu_to_le16p(&w16); } } static void set_ethernet_addr(pegasus_t * pegasus) { __u8 node_id[6]; int ret; get_node_id(pegasus, node_id); ret = set_registers(pegasus, EthID, sizeof (node_id), node_id); memcpy(pegasus->net->dev_addr, node_id, sizeof (node_id)); } static inline int reset_mac(pegasus_t * pegasus) { __u8 data = 0x8; int i; int ret; ret = set_register(pegasus, EthCtrl1, data); for (i = 0; i < REG_TIMEOUT; i++) { ret = get_registers(pegasus, EthCtrl1, 1, &data); if (~data & 0x08) { if (loopback & 1) break; if (mii_mode && (pegasus->features & HAS_HOME_PNA)) ret = set_register(pegasus, Gpio1, 0x34); else ret = set_register(pegasus, Gpio1, 0x26); ret = set_register(pegasus, Gpio0, pegasus->features); ret = set_register(pegasus, Gpio0, DEFAULT_GPIO_SET); break; } } if (i == REG_TIMEOUT) return 1; if (usb_dev_id[pegasus->dev_index].vendor == VENDOR_LINKSYS || usb_dev_id[pegasus->dev_index].vendor == VENDOR_DLINK) { ret = set_register(pegasus, Gpio0, 0x24); ret = set_register(pegasus, Gpio0, 0x26); } if (usb_dev_id[pegasus->dev_index].vendor == VENDOR_ELCON) { __u16 auxmode; read_mii_word(pegasus, 3, 0x1b, &auxmode); write_mii_word(pegasus, 3, 0x1b, auxmode | 4); } return 0; } static int enable_net_traffic(struct net_device *dev, struct usb_device *usb) { __u16 linkpart; __u8 data[4]; pegasus_t *pegasus = netdev_priv(dev); int ret; read_mii_word(pegasus, pegasus->phy, MII_LPA, &linkpart); data[0] = 0xc9; data[1] = 0; if (linkpart & (ADVERTISE_100FULL | ADVERTISE_10FULL)) data[1] |= 0x20; /* set full duplex */ if (linkpart & (ADVERTISE_100FULL | ADVERTISE_100HALF)) data[1] |= 0x10; /* set 100 Mbps */ if (mii_mode) data[1] = 0; data[2] = (loopback & 1) ? 0x09 : 0x01; memcpy(pegasus->eth_regs, data, sizeof (data)); ret = set_registers(pegasus, EthCtrl0, 3, data); if (usb_dev_id[pegasus->dev_index].vendor == VENDOR_LINKSYS || usb_dev_id[pegasus->dev_index].vendor == VENDOR_DLINK) { u16 auxmode; read_mii_word(pegasus, 0, 0x1b, &auxmode); write_mii_word(pegasus, 0, 0x1b, auxmode | 4); } return 0; } static void fill_skb_pool(pegasus_t * pegasus) { int i; for (i = 0; i < RX_SKBS; i++) { if (pegasus->rx_pool[i]) continue; pegasus->rx_pool[i] = dev_alloc_skb(PEGASUS_MTU + 2); /* ** we give up if the allocation fail. the tasklet will be ** rescheduled again anyway... */ if (pegasus->rx_pool[i] == NULL) return; pegasus->rx_pool[i]->dev = pegasus->net; skb_reserve(pegasus->rx_pool[i], 2); } } static void free_skb_pool(pegasus_t * pegasus) { int i; for (i = 0; i < RX_SKBS; i++) { if (pegasus->rx_pool[i]) { dev_kfree_skb(pegasus->rx_pool[i]); pegasus->rx_pool[i] = NULL; } } } static inline struct sk_buff *pull_skb(pegasus_t * pegasus) { int i; struct sk_buff *skb; for (i = 0; i < RX_SKBS; i++) { if (likely(pegasus->rx_pool[i] != NULL)) { skb = pegasus->rx_pool[i]; pegasus->rx_pool[i] = NULL; return skb; } } return NULL; } static void read_bulk_callback(struct urb *urb, struct pt_regs *regs) { pegasus_t *pegasus = urb->context; struct net_device *net; int rx_status, count = urb->actual_length; u8 *buf = urb->transfer_buffer; __u16 pkt_len; if (!pegasus) return; net = pegasus->net; if (!netif_device_present(net) || !netif_running(net)) return; switch (urb->status) { case 0: break; case -ETIMEDOUT: if (netif_msg_rx_err(pegasus)) pr_debug("%s: reset MAC\n", net->name); pegasus->flags &= ~PEGASUS_RX_BUSY; break; case -EPIPE: /* stall, or disconnect from TT */ /* FIXME schedule work to clear the halt */ if (netif_msg_rx_err(pegasus)) printk(KERN_WARNING "%s: no rx stall recovery\n", net->name); return; case -ENOENT: case -ECONNRESET: case -ESHUTDOWN: if (netif_msg_ifdown(pegasus)) pr_debug("%s: rx unlink, %d\n", net->name, urb->status); return; default: if (netif_msg_rx_err(pegasus)) pr_debug("%s: RX status %d\n", net->name, urb->status); goto goon; } if (!count || count < 4) goto goon; rx_status = buf[count - 2]; if (rx_status & 0x1e) { if (netif_msg_rx_err(pegasus)) pr_debug("%s: RX packet error %x\n", net->name, rx_status); pegasus->stats.rx_errors++; if (rx_status & 0x06) // long or runt pegasus->stats.rx_length_errors++; if (rx_status & 0x08) pegasus->stats.rx_crc_errors++; if (rx_status & 0x10) // extra bits pegasus->stats.rx_frame_errors++; goto goon; } if (pegasus->chip == 0x8513) { pkt_len = le32_to_cpu(*(__le32 *)urb->transfer_buffer); pkt_len &= 0x0fff; pegasus->rx_skb->data += 2; } else { pkt_len = buf[count - 3] << 8; pkt_len += buf[count - 4]; pkt_len &= 0xfff; pkt_len -= 8; } /* * If the packet is unreasonably long, quietly drop it rather than * kernel panicing by calling skb_put. */ if (pkt_len > PEGASUS_MTU) goto goon; /* * at this point we are sure pegasus->rx_skb != NULL * so we go ahead and pass up the packet. */ skb_put(pegasus->rx_skb, pkt_len); pegasus->rx_skb->protocol = eth_type_trans(pegasus->rx_skb, net); netif_rx(pegasus->rx_skb); pegasus->stats.rx_packets++; pegasus->stats.rx_bytes += pkt_len; if (pegasus->flags & PEGASUS_UNPLUG) return; spin_lock(&pegasus->rx_pool_lock); pegasus->rx_skb = pull_skb(pegasus); spin_unlock(&pegasus->rx_pool_lock); if (pegasus->rx_skb == NULL) goto tl_sched; goon: usb_fill_bulk_urb(pegasus->rx_urb, pegasus->usb, usb_rcvbulkpipe(pegasus->usb, 1), pegasus->rx_skb->data, PEGASUS_MTU + 8, read_bulk_callback, pegasus); if (usb_submit_urb(pegasus->rx_urb, GFP_ATOMIC)) { pegasus->flags |= PEGASUS_RX_URB_FAIL; goto tl_sched; } else { pegasus->flags &= ~PEGASUS_RX_URB_FAIL; } return; tl_sched: tasklet_schedule(&pegasus->rx_tl); } static void rx_fixup(unsigned long data) { pegasus_t *pegasus; unsigned long flags; pegasus = (pegasus_t *) data; if (pegasus->flags & PEGASUS_UNPLUG) return; spin_lock_irqsave(&pegasus->rx_pool_lock, flags); fill_skb_pool(pegasus); if (pegasus->flags & PEGASUS_RX_URB_FAIL) if (pegasus->rx_skb) goto try_again; if (pegasus->rx_skb == NULL) { pegasus->rx_skb = pull_skb(pegasus); } if (pegasus->rx_skb == NULL) { if (netif_msg_rx_err(pegasus)) printk(KERN_WARNING "%s: low on memory\n", pegasus->net->name); tasklet_schedule(&pegasus->rx_tl); goto done; } usb_fill_bulk_urb(pegasus->rx_urb, pegasus->usb, usb_rcvbulkpipe(pegasus->usb, 1), pegasus->rx_skb->data, PEGASUS_MTU + 8, read_bulk_callback, pegasus); try_again: if (usb_submit_urb(pegasus->rx_urb, GFP_ATOMIC)) { pegasus->flags |= PEGASUS_RX_URB_FAIL; tasklet_schedule(&pegasus->rx_tl); } else { pegasus->flags &= ~PEGASUS_RX_URB_FAIL; } done: spin_unlock_irqrestore(&pegasus->rx_pool_lock, flags); } static void write_bulk_callback(struct urb *urb, struct pt_regs *regs) { pegasus_t *pegasus = urb->context; struct net_device *net = pegasus->net; if (!pegasus) return; if (!netif_device_present(net) || !netif_running(net)) return; switch (urb->status) { case -EPIPE: /* FIXME schedule_work() to clear the tx halt */ netif_stop_queue(net); if (netif_msg_tx_err(pegasus)) printk(KERN_WARNING "%s: no tx stall recovery\n", net->name); return; case -ENOENT: case -ECONNRESET: case -ESHUTDOWN: if (netif_msg_ifdown(pegasus)) pr_debug("%s: tx unlink, %d\n", net->name, urb->status); return; default: if (netif_msg_tx_err(pegasus)) pr_info("%s: TX status %d\n", net->name, urb->status); /* FALL THROUGH */ case 0: break; } net->trans_start = jiffies; netif_wake_queue(net); } static void intr_callback(struct urb *urb, struct pt_regs *regs) { pegasus_t *pegasus = urb->context; struct net_device *net; int status; if (!pegasus) return; net = pegasus->net; switch (urb->status) { case 0: break; case -ECONNRESET: /* unlink */ case -ENOENT: case -ESHUTDOWN: return; default: /* some Pegasus-I products report LOTS of data * toggle errors... avoid log spamming */ if (netif_msg_timer(pegasus)) pr_debug("%s: intr status %d\n", net->name, urb->status); } if (urb->actual_length >= 6) { u8 * d = urb->transfer_buffer; /* byte 0 == tx_status1, reg 2B */ if (d[0] & (TX_UNDERRUN|EXCESSIVE_COL |LATE_COL|JABBER_TIMEOUT)) { pegasus->stats.tx_errors++; if (d[0] & TX_UNDERRUN) pegasus->stats.tx_fifo_errors++; if (d[0] & (EXCESSIVE_COL | JABBER_TIMEOUT)) pegasus->stats.tx_aborted_errors++; if (d[0] & LATE_COL) pegasus->stats.tx_window_errors++; } /* d[5].LINK_STATUS lies on some adapters. * d[0].NO_CARRIER kicks in only with failed TX. * ... so monitoring with MII may be safest. */ if (d[0] & NO_CARRIER) netif_carrier_off(net); else netif_carrier_on(net); /* bytes 3-4 == rx_lostpkt, reg 2E/2F */ pegasus->stats.rx_missed_errors += ((d[3] & 0x7f) << 8) | d[4]; } status = usb_submit_urb(urb, SLAB_ATOMIC); if (status && netif_msg_timer(pegasus)) printk(KERN_ERR "%s: can't resubmit interrupt urb, %d\n", net->name, status); } static void pegasus_tx_timeout(struct net_device *net) { pegasus_t *pegasus = netdev_priv(net); if (netif_msg_timer(pegasus)) printk(KERN_WARNING "%s: tx timeout\n", net->name); usb_unlink_urb(pegasus->tx_urb); pegasus->stats.tx_errors++; } static int pegasus_start_xmit(struct sk_buff *skb, struct net_device *net) { pegasus_t *pegasus = netdev_priv(net); int count = ((skb->len + 2) & 0x3f) ? skb->len + 2 : skb->len + 3; int res; __u16 l16 = skb->len; netif_stop_queue(net); ((__le16 *) pegasus->tx_buff)[0] = cpu_to_le16(l16); memcpy(pegasus->tx_buff + 2, skb->data, skb->len); usb_fill_bulk_urb(pegasus->tx_urb, pegasus->usb, usb_sndbulkpipe(pegasus->usb, 2), pegasus->tx_buff, count, write_bulk_callback, pegasus); if ((res = usb_submit_urb(pegasus->tx_urb, GFP_ATOMIC))) { if (netif_msg_tx_err(pegasus)) printk(KERN_WARNING "%s: fail tx, %d\n", net->name, res); switch (res) { case -EPIPE: /* stall, or disconnect from TT */ /* cleanup should already have been scheduled */ break; case -ENODEV: /* disconnect() upcoming */ break; default: pegasus->stats.tx_errors++; netif_start_queue(net); } } else { pegasus->stats.tx_packets++; pegasus->stats.tx_bytes += skb->len; net->trans_start = jiffies; } dev_kfree_skb(skb); return 0; } static struct net_device_stats *pegasus_netdev_stats(struct net_device *dev) { return &((pegasus_t *) netdev_priv(dev))->stats; } static inline void disable_net_traffic(pegasus_t * pegasus) { int tmp = 0; int ret; ret = set_registers(pegasus, EthCtrl0, 2, &tmp); } static inline void get_interrupt_interval(pegasus_t * pegasus) { __u8 data[2]; read_eprom_word(pegasus, 4, (__u16 *) data); if (pegasus->usb->speed != USB_SPEED_HIGH) { if (data[1] < 0x80) { if (netif_msg_timer(pegasus)) dev_info(&pegasus->intf->dev, "intr interval " "changed from %ums to %ums\n", data[1], 0x80); data[1] = 0x80; #ifdef PEGASUS_WRITE_EEPROM write_eprom_word(pegasus, 4, *(__u16 *) data); #endif } } pegasus->intr_interval = data[1]; } static void set_carrier(struct net_device *net) { pegasus_t *pegasus = netdev_priv(net); u16 tmp; if (!read_mii_word(pegasus, pegasus->phy, MII_BMSR, &tmp)) return; if (tmp & BMSR_LSTATUS) netif_carrier_on(net); else netif_carrier_off(net); } static void free_all_urbs(pegasus_t * pegasus) { usb_free_urb(pegasus->intr_urb); usb_free_urb(pegasus->tx_urb); usb_free_urb(pegasus->rx_urb); usb_free_urb(pegasus->ctrl_urb); } static void unlink_all_urbs(pegasus_t * pegasus) { usb_kill_urb(pegasus->intr_urb); usb_kill_urb(pegasus->tx_urb); usb_kill_urb(pegasus->rx_urb); usb_kill_urb(pegasus->ctrl_urb); } static int alloc_urbs(pegasus_t * pegasus) { pegasus->ctrl_urb = usb_alloc_urb(0, GFP_KERNEL); if (!pegasus->ctrl_urb) { return 0; } pegasus->rx_urb = usb_alloc_urb(0, GFP_KERNEL); if (!pegasus->rx_urb) { usb_free_urb(pegasus->ctrl_urb); return 0; } pegasus->tx_urb = usb_alloc_urb(0, GFP_KERNEL); if (!pegasus->tx_urb) { usb_free_urb(pegasus->rx_urb); usb_free_urb(pegasus->ctrl_urb); return 0; } pegasus->intr_urb = usb_alloc_urb(0, GFP_KERNEL); if (!pegasus->intr_urb) { usb_free_urb(pegasus->tx_urb); usb_free_urb(pegasus->rx_urb); usb_free_urb(pegasus->ctrl_urb); return 0; } return 1; } static int pegasus_open(struct net_device *net) { pegasus_t *pegasus = netdev_priv(net); int res; if (pegasus->rx_skb == NULL) pegasus->rx_skb = pull_skb(pegasus); /* ** Note: no point to free the pool. it is empty :-) */ if (!pegasus->rx_skb) return -ENOMEM; res = set_registers(pegasus, EthID, 6, net->dev_addr); usb_fill_bulk_urb(pegasus->rx_urb, pegasus->usb, usb_rcvbulkpipe(pegasus->usb, 1), pegasus->rx_skb->data, PEGASUS_MTU + 8, read_bulk_callback, pegasus); if ((res = usb_submit_urb(pegasus->rx_urb, GFP_KERNEL))) { if (netif_msg_ifup(pegasus)) pr_debug("%s: failed rx_urb, %d", net->name, res); goto exit; } usb_fill_int_urb(pegasus->intr_urb, pegasus->usb, usb_rcvintpipe(pegasus->usb, 3), pegasus->intr_buff, sizeof (pegasus->intr_buff), intr_callback, pegasus, pegasus->intr_interval); if ((res = usb_submit_urb(pegasus->intr_urb, GFP_KERNEL))) { if (netif_msg_ifup(pegasus)) pr_debug("%s: failed intr_urb, %d\n", net->name, res); usb_kill_urb(pegasus->rx_urb); goto exit; } if ((res = enable_net_traffic(net, pegasus->usb))) { if (netif_msg_ifup(pegasus)) pr_debug("%s: can't enable_net_traffic() - %d\n", net->name, res); res = -EIO; usb_kill_urb(pegasus->rx_urb); usb_kill_urb(pegasus->intr_urb); free_skb_pool(pegasus); goto exit; } set_carrier(net); netif_start_queue(net); if (netif_msg_ifup(pegasus)) pr_debug("%s: open\n", net->name); res = 0; exit: return res; } static int pegasus_close(struct net_device *net) { pegasus_t *pegasus = netdev_priv(net); netif_stop_queue(net); if (!(pegasus->flags & PEGASUS_UNPLUG)) disable_net_traffic(pegasus); tasklet_kill(&pegasus->rx_tl); unlink_all_urbs(pegasus); return 0; } static void pegasus_get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info) { pegasus_t *pegasus = netdev_priv(dev); strncpy(info->driver, driver_name, sizeof (info->driver) - 1); strncpy(info->version, DRIVER_VERSION, sizeof (info->version) - 1); usb_make_path(pegasus->usb, info->bus_info, sizeof (info->bus_info)); } /* also handles three patterns of some kind in hardware */ #define WOL_SUPPORTED (WAKE_MAGIC|WAKE_PHY) static void pegasus_get_wol(struct net_device *dev, struct ethtool_wolinfo *wol) { pegasus_t *pegasus = netdev_priv(dev); wol->supported = WAKE_MAGIC | WAKE_PHY; wol->wolopts = pegasus->wolopts; } static int pegasus_set_wol(struct net_device *dev, struct ethtool_wolinfo *wol) { pegasus_t *pegasus = netdev_priv(dev); u8 reg78 = 0x04; if (wol->wolopts & ~WOL_SUPPORTED) return -EINVAL; if (wol->wolopts & WAKE_MAGIC) reg78 |= 0x80; if (wol->wolopts & WAKE_PHY) reg78 |= 0x40; /* FIXME this 0x10 bit still needs to get set in the chip... */ if (wol->wolopts) pegasus->eth_regs[0] |= 0x10; else pegasus->eth_regs[0] &= ~0x10; pegasus->wolopts = wol->wolopts; return set_register(pegasus, WakeupControl, reg78); } static inline void pegasus_reset_wol(struct net_device *dev) { struct ethtool_wolinfo wol; memset(&wol, 0, sizeof wol); (void) pegasus_set_wol(dev, &wol); } static int pegasus_get_settings(struct net_device *dev, struct ethtool_cmd *ecmd) { pegasus_t *pegasus; if (in_atomic()) return 0; pegasus = netdev_priv(dev); mii_ethtool_gset(&pegasus->mii, ecmd); return 0; } static int pegasus_set_settings(struct net_device *dev, struct ethtool_cmd *ecmd) { pegasus_t *pegasus = netdev_priv(dev); return mii_ethtool_sset(&pegasus->mii, ecmd); } static int pegasus_nway_reset(struct net_device *dev) { pegasus_t *pegasus = netdev_priv(dev); return mii_nway_restart(&pegasus->mii); } static u32 pegasus_get_link(struct net_device *dev) { pegasus_t *pegasus = netdev_priv(dev); return mii_link_ok(&pegasus->mii); } static u32 pegasus_get_msglevel(struct net_device *dev) { pegasus_t *pegasus = netdev_priv(dev); return pegasus->msg_enable; } static void pegasus_set_msglevel(struct net_device *dev, u32 v) { pegasus_t *pegasus = netdev_priv(dev); pegasus->msg_enable = v; } static struct ethtool_ops ops = { .get_drvinfo = pegasus_get_drvinfo, .get_settings = pegasus_get_settings, .set_settings = pegasus_set_settings, .nway_reset = pegasus_nway_reset, .get_link = pegasus_get_link, .get_msglevel = pegasus_get_msglevel, .set_msglevel = pegasus_set_msglevel, .get_wol = pegasus_get_wol, .set_wol = pegasus_set_wol, }; static int pegasus_ioctl(struct net_device *net, struct ifreq *rq, int cmd) { __u16 *data = (__u16 *) & rq->ifr_ifru; pegasus_t *pegasus = netdev_priv(net); int res; switch (cmd) { case SIOCDEVPRIVATE: data[0] = pegasus->phy; case SIOCDEVPRIVATE + 1: read_mii_word(pegasus, data[0], data[1] & 0x1f, &data[3]); res = 0; break; case SIOCDEVPRIVATE + 2: if (!capable(CAP_NET_ADMIN)) return -EPERM; write_mii_word(pegasus, pegasus->phy, data[1] & 0x1f, data[2]); res = 0; break; default: res = -EOPNOTSUPP; } return res; } static void pegasus_set_multicast(struct net_device *net) { pegasus_t *pegasus = netdev_priv(net); if (net->flags & IFF_PROMISC) { pegasus->eth_regs[EthCtrl2] |= RX_PROMISCUOUS; if (netif_msg_link(pegasus)) pr_info("%s: Promiscuous mode enabled.\n", net->name); } else if (net->mc_count || (net->flags & IFF_ALLMULTI)) { pegasus->eth_regs[EthCtrl0] |= RX_MULTICAST; pegasus->eth_regs[EthCtrl2] &= ~RX_PROMISCUOUS; if (netif_msg_link(pegasus)) pr_info("%s: set allmulti\n", net->name); } else { pegasus->eth_regs[EthCtrl0] &= ~RX_MULTICAST; pegasus->eth_regs[EthCtrl2] &= ~RX_PROMISCUOUS; } pegasus->flags |= ETH_REGS_CHANGE; ctrl_callback(pegasus->ctrl_urb, NULL); } static __u8 mii_phy_probe(pegasus_t * pegasus) { int i; __u16 tmp; for (i = 0; i < 32; i++) { read_mii_word(pegasus, i, MII_BMSR, &tmp); if (tmp == 0 || tmp == 0xffff || (tmp & BMSR_MEDIA) == 0) continue; else return i; } return 0xff; } static inline void setup_pegasus_II(pegasus_t * pegasus) { __u8 data = 0xa5; int ret; ret = set_register(pegasus, Reg1d, 0); ret = set_register(pegasus, Reg7b, 1); mdelay(100); if ((pegasus->features & HAS_HOME_PNA) && mii_mode) ret = set_register(pegasus, Reg7b, 0); else ret = set_register(pegasus, Reg7b, 2); ret = set_register(pegasus, 0x83, data); ret = get_registers(pegasus, 0x83, 1, &data); if (data == 0xa5) { pegasus->chip = 0x8513; } else { pegasus->chip = 0; } ret = set_register(pegasus, 0x80, 0xc0); ret = set_register(pegasus, 0x83, 0xff); ret = set_register(pegasus, 0x84, 0x01); if (pegasus->features & HAS_HOME_PNA && mii_mode) ret = set_register(pegasus, Reg81, 6); else ret = set_register(pegasus, Reg81, 2); } static struct workqueue_struct *pegasus_workqueue = NULL; #define CARRIER_CHECK_DELAY (2 * HZ) static void check_carrier(void *data) { pegasus_t *pegasus = data; set_carrier(pegasus->net); if (!(pegasus->flags & PEGASUS_UNPLUG)) { queue_delayed_work(pegasus_workqueue, &pegasus->carrier_check, CARRIER_CHECK_DELAY); } } static int pegasus_probe(struct usb_interface *intf, const struct usb_device_id *id) { struct usb_device *dev = interface_to_usbdev(intf); struct net_device *net; pegasus_t *pegasus; int dev_index = id - pegasus_ids; int res = -ENOMEM; usb_get_dev(dev); net = alloc_etherdev(sizeof(struct pegasus)); if (!net) { dev_err(&intf->dev, "can't allocate %s\n", "device"); goto out; } pegasus = netdev_priv(net); memset(pegasus, 0, sizeof (struct pegasus)); pegasus->dev_index = dev_index; init_waitqueue_head(&pegasus->ctrl_wait); if (!alloc_urbs(pegasus)) { dev_err(&intf->dev, "can't allocate %s\n", "urbs"); goto out1; } tasklet_init(&pegasus->rx_tl, rx_fixup, (unsigned long) pegasus); INIT_WORK(&pegasus->carrier_check, check_carrier, pegasus); pegasus->intf = intf; pegasus->usb = dev; pegasus->net = net; SET_MODULE_OWNER(net); net->open = pegasus_open; net->stop = pegasus_close; net->watchdog_timeo = PEGASUS_TX_TIMEOUT; net->tx_timeout = pegasus_tx_timeout; net->do_ioctl = pegasus_ioctl; net->hard_start_xmit = pegasus_start_xmit; net->set_multicast_list = pegasus_set_multicast; net->get_stats = pegasus_netdev_stats; SET_ETHTOOL_OPS(net, &ops); pegasus->mii.dev = net; pegasus->mii.mdio_read = mdio_read; pegasus->mii.mdio_write = mdio_write; pegasus->mii.phy_id_mask = 0x1f; pegasus->mii.reg_num_mask = 0x1f; spin_lock_init(&pegasus->rx_pool_lock); pegasus->msg_enable = netif_msg_init (msg_level, NETIF_MSG_DRV | NETIF_MSG_PROBE | NETIF_MSG_LINK); pegasus->features = usb_dev_id[dev_index].private; get_interrupt_interval(pegasus); if (reset_mac(pegasus)) { dev_err(&intf->dev, "can't reset MAC\n"); res = -EIO; goto out2; } set_ethernet_addr(pegasus); fill_skb_pool(pegasus); if (pegasus->features & PEGASUS_II) { dev_info(&intf->dev, "setup Pegasus II specific registers\n"); setup_pegasus_II(pegasus); } pegasus->phy = mii_phy_probe(pegasus); if (pegasus->phy == 0xff) { dev_warn(&intf->dev, "can't locate MII phy, using default\n"); pegasus->phy = 1; } pegasus->mii.phy_id = pegasus->phy; usb_set_intfdata(intf, pegasus); SET_NETDEV_DEV(net, &intf->dev); pegasus_reset_wol(net); res = register_netdev(net); if (res) goto out3; queue_delayed_work(pegasus_workqueue, &pegasus->carrier_check, CARRIER_CHECK_DELAY); dev_info(&intf->dev, "%s, %s, %02x:%02x:%02x:%02x:%02x:%02x\n", net->name, usb_dev_id[dev_index].name, net->dev_addr [0], net->dev_addr [1], net->dev_addr [2], net->dev_addr [3], net->dev_addr [4], net->dev_addr [5]); return 0; out3: usb_set_intfdata(intf, NULL); free_skb_pool(pegasus); out2: free_all_urbs(pegasus); out1: free_netdev(net); out: usb_put_dev(dev); return res; } static void pegasus_disconnect(struct usb_interface *intf) { struct pegasus *pegasus = usb_get_intfdata(intf); usb_set_intfdata(intf, NULL); if (!pegasus) { dev_dbg(&intf->dev, "unregistering non-bound device?\n"); return; } pegasus->flags |= PEGASUS_UNPLUG; cancel_delayed_work(&pegasus->carrier_check); unregister_netdev(pegasus->net); usb_put_dev(interface_to_usbdev(intf)); unlink_all_urbs(pegasus); free_all_urbs(pegasus); free_skb_pool(pegasus); if (pegasus->rx_skb) dev_kfree_skb(pegasus->rx_skb); free_netdev(pegasus->net); } static int pegasus_suspend (struct usb_interface *intf, pm_message_t message) { struct pegasus *pegasus = usb_get_intfdata(intf); netif_device_detach (pegasus->net); if (netif_running(pegasus->net)) { cancel_delayed_work(&pegasus->carrier_check); usb_kill_urb(pegasus->rx_urb); usb_kill_urb(pegasus->intr_urb); } intf->dev.power.power_state = PMSG_SUSPEND; return 0; } static int pegasus_resume (struct usb_interface *intf) { struct pegasus *pegasus = usb_get_intfdata(intf); intf->dev.power.power_state = PMSG_ON; netif_device_attach (pegasus->net); if (netif_running(pegasus->net)) { pegasus->rx_urb->status = 0; pegasus->rx_urb->actual_length = 0; read_bulk_callback(pegasus->rx_urb, NULL); pegasus->intr_urb->status = 0; pegasus->intr_urb->actual_length = 0; intr_callback(pegasus->intr_urb, NULL); queue_delayed_work(pegasus_workqueue, &pegasus->carrier_check, CARRIER_CHECK_DELAY); } return 0; } static struct usb_driver pegasus_driver = { .name = driver_name, .probe = pegasus_probe, .disconnect = pegasus_disconnect, .id_table = pegasus_ids, .suspend = pegasus_suspend, .resume = pegasus_resume, }; static int __init pegasus_init(void) { pr_info("%s: %s, " DRIVER_DESC "\n", driver_name, DRIVER_VERSION); pegasus_workqueue = create_singlethread_workqueue("pegasus"); if (!pegasus_workqueue) return -ENOMEM; return usb_register(&pegasus_driver); } static void __exit pegasus_exit(void) { destroy_workqueue(pegasus_workqueue); usb_deregister(&pegasus_driver); } module_init(pegasus_init); module_exit(pegasus_exit);
ipwndev/DSLinux-Mirror
linux-2.6.x/drivers/usb/net/pegasus.c
C
gpl-2.0
36,647
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- * vim:expandtab:shiftwidth=2:tabstop=2: */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is the Gtk2XtBin Widget Implementation. * * The Initial Developer of the Original Code is * Sun Microsystems, Inc. * Portions created by the Initial Developer are Copyright (C) 2002 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ /* * The GtkXtBin widget allows for Xt toolkit code to be used * inside a GTK application. */ #include "xembed.h" #include "gtk2xtbin.h" #include <gtk/gtk.h> #include <gdk/gdkx.h> #include <glib.h> #include <assert.h> #include <sys/time.h> #include <sys/types.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> /* Xlib/Xt stuff */ #include <X11/Xlib.h> #include <X11/Xutil.h> #include <X11/Shell.h> #include <X11/Intrinsic.h> #include <X11/StringDefs.h> /* uncomment this if you want debugging information about widget creation and destruction */ #undef DEBUG_XTBIN #define XTBIN_MAX_EVENTS 30 static void gtk_xtbin_class_init (GtkXtBinClass *klass); static void gtk_xtbin_init (GtkXtBin *xtbin); static void gtk_xtbin_realize (GtkWidget *widget); static void gtk_xtbin_unrealize (GtkWidget *widget); static void gtk_xtbin_destroy (GtkObject *object); static void gtk_xtbin_shutdown (GtkObject *object); /* Xt aware XEmbed */ static void xt_client_init (XtClient * xtclient, Visual *xtvisual, Colormap xtcolormap, int xtdepth); static void xt_client_create (XtClient * xtclient, Window embeder, int height, int width ); static void xt_client_unrealize (XtClient* xtclient); static void xt_client_destroy (XtClient* xtclient); static void xt_client_set_info (Widget xtplug, unsigned long flags); static void xt_client_event_handler (Widget w, XtPointer client_data, XEvent *event); static void xt_client_handle_xembed_message (Widget w, XtPointer client_data, XEvent *event); static void xt_client_focus_listener (Widget w, XtPointer user_data, XEvent *event); static void xt_add_focus_listener( Widget w, XtPointer user_data ); static void xt_add_focus_listener_tree ( Widget treeroot, XtPointer user_data); static void xt_remove_focus_listener(Widget w, XtPointer user_data); static void send_xembed_message (XtClient *xtclient, long message, long detail, long data1, long data2, long time); static int error_handler (Display *display, XErrorEvent *error); /* For error trap of XEmbed */ static void trap_errors(void); static int untrap_error(void); static int (*old_error_handler) (Display *, XErrorEvent *); static int trapped_error_code = 0; static GtkWidgetClass *parent_class = NULL; static Display *xtdisplay = NULL; static String *fallback = NULL; static gboolean xt_is_initialized = FALSE; static gint num_widgets = 0; static GPollFD xt_event_poll_fd; static gint xt_polling_timer_id = 0; static guint tag = 0; static gboolean xt_event_prepare (GSource* source_data, gint *timeout) { int mask; GDK_THREADS_ENTER(); mask = XPending(xtdisplay); GDK_THREADS_LEAVE(); return (gboolean)mask; } static gboolean xt_event_check (GSource* source_data) { GDK_THREADS_ENTER (); if (xt_event_poll_fd.revents & G_IO_IN) { int mask; mask = XPending(xtdisplay); GDK_THREADS_LEAVE (); return (gboolean)mask; } GDK_THREADS_LEAVE (); return FALSE; } static gboolean xt_event_dispatch (GSource* source_data, GSourceFunc call_back, gpointer user_data) { XEvent event; XtAppContext ac; int i = 0; ac = XtDisplayToApplicationContext(xtdisplay); GDK_THREADS_ENTER (); /* Process only real X traffic here. We only look for data on the * pipe, limit it to XTBIN_MAX_EVENTS and only call * XtAppProcessEvent so that it will look for X events. There's no * timer processing here since we already have a timer callback that * does it. */ for (i=0; i < XTBIN_MAX_EVENTS && XPending(xtdisplay); i++) { XtAppProcessEvent(ac, XtIMXEvent); } GDK_THREADS_LEAVE (); return TRUE; } static GSourceFuncs xt_event_funcs = { xt_event_prepare, xt_event_check, xt_event_dispatch, g_free, (GSourceFunc)NULL, (GSourceDummyMarshal)NULL }; static gboolean xt_event_polling_timer_callback(gpointer user_data) { Display * display; XtAppContext ac; int eventsToProcess = 20; display = (Display *)user_data; ac = XtDisplayToApplicationContext(display); /* We need to process many Xt events here. If we just process one event we might starve one or more Xt consumers. On the other hand this could hang the whole app if Xt events come pouring in. So process up to 20 Xt events right now and save the rest for later. This is a hack, but it oughta work. We *really* should have out of process plugins. */ while (eventsToProcess-- && XtAppPending(ac)) XtAppProcessEvent(ac, XtIMAll); return TRUE; } GType gtk_xtbin_get_type (void) { static GType xtbin_type = 0; if (!xtbin_type) { static const GTypeInfo xtbin_info = { sizeof (GtkXtBinClass), NULL, NULL, (GClassInitFunc)gtk_xtbin_class_init, NULL, NULL, sizeof (GtkXtBin), 0, (GInstanceInitFunc)gtk_xtbin_init, }; xtbin_type = g_type_register_static (GTK_TYPE_SOCKET, "GtkXtBin", &xtbin_info, 0); } return xtbin_type; } static void gtk_xtbin_class_init (GtkXtBinClass *klass) { GtkWidgetClass *widget_class; GtkObjectClass *object_class; parent_class = g_type_class_peek_parent (klass); widget_class = GTK_WIDGET_CLASS (klass); widget_class->realize = gtk_xtbin_realize; widget_class->unrealize = gtk_xtbin_unrealize; object_class = GTK_OBJECT_CLASS (klass); object_class->destroy = gtk_xtbin_destroy; } static void gtk_xtbin_init (GtkXtBin *xtbin) { xtbin->xtdisplay = NULL; xtbin->parent_window = NULL; xtbin->xtwindow = 0; xtbin->x = 0; xtbin->y = 0; } static void gtk_xtbin_realize (GtkWidget *widget) { GtkXtBin *xtbin; GtkAllocation allocation = { 0, 0, 200, 200 }; gint x, y, w, h, d; /* geometry of window */ #ifdef DEBUG_XTBIN printf("gtk_xtbin_realize()\n"); #endif g_return_if_fail (GTK_IS_XTBIN (widget)); xtbin = GTK_XTBIN (widget); /* caculate the allocation before realize */ gdk_window_get_geometry(xtbin->parent_window, &x, &y, &w, &h, &d); allocation.width = w; allocation.height = h; gtk_widget_size_allocate (widget, &allocation); #ifdef DEBUG_XTBIN printf("initial allocation %d %d %d %d\n", x, y, w, h); #endif xtbin->width = widget->allocation.width; xtbin->height = widget->allocation.height; /* use GtkSocket's realize */ (*GTK_WIDGET_CLASS(parent_class)->realize)(widget); /* create the Xt client widget */ xt_client_create(&(xtbin->xtclient), gtk_socket_get_id(GTK_SOCKET(xtbin)), xtbin->height, xtbin->width); xtbin->xtwindow = XtWindow(xtbin->xtclient.child_widget); gdk_flush(); /* now that we have created the xt client, add it to the socket. */ gtk_socket_add_id(GTK_SOCKET(widget), xtbin->xtwindow); } GtkWidget* gtk_xtbin_new (GdkWindow *parent_window, String * f) { GtkXtBin *xtbin; gpointer user_data; assert(parent_window != NULL); xtbin = g_object_new (GTK_TYPE_XTBIN, NULL); if (!xtbin) return (GtkWidget*)NULL; if (f) fallback = f; /* Initialize the Xt toolkit */ xtbin->parent_window = parent_window; xt_client_init(&(xtbin->xtclient), GDK_VISUAL_XVISUAL(gdk_rgb_get_visual()), GDK_COLORMAP_XCOLORMAP(gdk_rgb_get_colormap()), gdk_rgb_get_visual()->depth); if (!xtbin->xtclient.xtdisplay) { /* If XtOpenDisplay failed, we can't go any further. * Bail out. */ #ifdef DEBUG_XTBIN printf("gtk_xtbin_init: XtOpenDisplay() returned NULL.\n"); #endif g_free (xtbin); return (GtkWidget *)NULL; } /* If this is the first running widget, hook this display into the mainloop */ if (0 == num_widgets) { int cnumber; /* * hook Xt event loop into the glib event loop. */ /* the assumption is that gtk_init has already been called */ GSource* gs = g_source_new(&xt_event_funcs, sizeof(GSource)); if (!gs) { return NULL; } g_source_set_priority(gs, GDK_PRIORITY_EVENTS); g_source_set_can_recurse(gs, TRUE); tag = g_source_attach(gs, (GMainContext*)NULL); #ifdef VMS cnumber = XConnectionNumber(xtdisplay); #else cnumber = ConnectionNumber(xtdisplay); #endif xt_event_poll_fd.fd = cnumber; xt_event_poll_fd.events = G_IO_IN; xt_event_poll_fd.revents = 0; /* hmm... is this correct? */ g_main_context_add_poll ((GMainContext*)NULL, &xt_event_poll_fd, G_PRIORITY_LOW); /* add a timer so that we can poll and process Xt timers */ xt_polling_timer_id = g_timeout_add(25, (GSourceFunc)xt_event_polling_timer_callback, xtdisplay); } /* Bump up our usage count */ num_widgets++; /* Build the hierachy */ xtbin->xtdisplay = xtbin->xtclient.xtdisplay; gtk_widget_set_parent_window(GTK_WIDGET(xtbin), parent_window); gdk_window_get_user_data(xtbin->parent_window, &user_data); if (user_data) gtk_container_add(GTK_CONTAINER(user_data), GTK_WIDGET(xtbin)); return GTK_WIDGET (xtbin); } void gtk_xtbin_set_position (GtkXtBin *xtbin, gint x, gint y) { xtbin->x = x; xtbin->y = y; if (GTK_WIDGET_REALIZED (xtbin)) gdk_window_move (GTK_WIDGET (xtbin)->window, x, y); } void gtk_xtbin_resize (GtkWidget *widget, gint width, gint height) { Arg args[2]; GtkXtBin *xtbin = GTK_XTBIN (widget); GtkAllocation allocation; #ifdef DEBUG_XTBIN printf("gtk_xtbin_resize %p %d %d\n", (void *)widget, width, height); #endif xtbin->height = height; xtbin->width = width; // Avoid BadValue errors in XtSetValues if (height <= 0 || width <=0) { height = 1; width = 1; } XtSetArg(args[0], XtNheight, height); XtSetArg(args[1], XtNwidth, width); XtSetValues(xtbin->xtclient.top_widget, args, 2); /* we need to send a size allocate so the socket knows about the size changes */ allocation.x = xtbin->x; allocation.y = xtbin->y; allocation.width = xtbin->width; allocation.height = xtbin->height; gtk_widget_size_allocate(widget, &allocation); } static void gtk_xtbin_unrealize (GtkWidget *object) { GtkXtBin *xtbin; GtkWidget *widget; #ifdef DEBUG_XTBIN printf("gtk_xtbin_unrealize()\n"); #endif /* gtk_object_destroy() will already hold a refcount on object */ xtbin = GTK_XTBIN(object); widget = GTK_WIDGET(object); GTK_WIDGET_UNSET_FLAGS (widget, GTK_VISIBLE); if (GTK_WIDGET_REALIZED (widget)) { xt_client_unrealize(&(xtbin->xtclient)); } (*GTK_WIDGET_CLASS (parent_class)->unrealize)(widget); } static void gtk_xtbin_destroy (GtkObject *object) { GtkXtBin *xtbin; #ifdef DEBUG_XTBIN printf("gtk_xtbin_destroy()\n"); #endif g_return_if_fail (object != NULL); g_return_if_fail (GTK_IS_XTBIN (object)); xtbin = GTK_XTBIN (object); if(xtbin->xtwindow) { /* remove the event handler */ xt_client_destroy(&(xtbin->xtclient)); xtbin->xtwindow = 0; num_widgets--; /* reduce our usage count */ /* If this is the last running widget, remove the Xt display connection from the mainloop */ if (0 == num_widgets) { #ifdef DEBUG_XTBIN printf("removing the Xt connection from the main loop\n"); #endif g_main_context_remove_poll((GMainContext*)NULL, &xt_event_poll_fd); g_source_remove(tag); g_source_remove(xt_polling_timer_id); xt_polling_timer_id = 0; } } GTK_OBJECT_CLASS(parent_class)->destroy(object); } /* * Following is the implementation of Xt XEmbedded for client side */ /* Initial Xt plugin */ static void xt_client_init( XtClient * xtclient, Visual *xtvisual, Colormap xtcolormap, int xtdepth) { XtAppContext app_context; char *mArgv[1]; int mArgc = 0; /* * Initialize Xt stuff */ xtclient->top_widget = NULL; xtclient->child_widget = NULL; xtclient->xtdisplay = NULL; xtclient->xtvisual = NULL; xtclient->xtcolormap = 0; xtclient->xtdepth = 0; if (!xt_is_initialized) { #ifdef DEBUG_XTBIN printf("starting up Xt stuff\n"); #endif XtToolkitInitialize(); app_context = XtCreateApplicationContext(); if (fallback) XtAppSetFallbackResources(app_context, fallback); xtdisplay = XtOpenDisplay(app_context, gdk_get_display(), NULL, "Wrapper", NULL, 0, &mArgc, mArgv); if (xtdisplay) xt_is_initialized = TRUE; } xtclient->xtdisplay = xtdisplay; xtclient->xtvisual = xtvisual; xtclient->xtcolormap = xtcolormap; xtclient->xtdepth = xtdepth; } /* Create the Xt client widgets * */ static void xt_client_create ( XtClient* xtclient , Window embedderid, int height, int width ) { int n; Arg args[6]; Widget child_widget; Widget top_widget; #ifdef DEBUG_XTBIN printf("xt_client_create() \n"); #endif top_widget = XtAppCreateShell("drawingArea", "Wrapper", applicationShellWidgetClass, xtclient->xtdisplay, NULL, 0); xtclient->top_widget = top_widget; /* set size of Xt window */ n = 0; XtSetArg(args[n], XtNheight, height);n++; XtSetArg(args[n], XtNwidth, width);n++; XtSetValues(top_widget, args, n); child_widget = XtVaCreateWidget("form", compositeWidgetClass, top_widget, NULL); n = 0; XtSetArg(args[n], XtNheight, height);n++; XtSetArg(args[n], XtNwidth, width);n++; XtSetArg(args[n], XtNvisual, xtclient->xtvisual ); n++; XtSetArg(args[n], XtNdepth, xtclient->xtdepth ); n++; XtSetArg(args[n], XtNcolormap, xtclient->xtcolormap ); n++; XtSetArg(args[n], XtNborderWidth, 0); n++; XtSetValues(child_widget, args, n); XSync(xtclient->xtdisplay, FALSE); xtclient->oldwindow = top_widget->core.window; top_widget->core.window = embedderid; /* this little trick seems to finish initializing the widget */ #if XlibSpecificationRelease >= 6 XtRegisterDrawable(xtclient->xtdisplay, embedderid, top_widget); #else _XtRegisterWindow( embedderid, top_widget); #endif XtRealizeWidget(child_widget); /* listen to all Xt events */ XSelectInput(xtclient->xtdisplay, XtWindow(top_widget), 0x0FFFFF); xt_client_set_info (child_widget, 0); XtManageChild(child_widget); xtclient->child_widget = child_widget; /* set the event handler */ XtAddEventHandler(child_widget, 0x0FFFFF & ~ResizeRedirectMask, TRUE, (XtEventHandler)xt_client_event_handler, xtclient); XtAddEventHandler(child_widget, SubstructureNotifyMask | ButtonReleaseMask, TRUE, (XtEventHandler)xt_client_focus_listener, xtclient); XSync(xtclient->xtdisplay, FALSE); } static void xt_client_unrealize ( XtClient* xtclient ) { #if XlibSpecificationRelease >= 6 XtUnregisterDrawable(xtclient->xtdisplay, xtclient->top_widget->core.window); #else _XtUnregisterWindow(xtclient->top_widget->core.window, xtclient->top_widget); #endif /* flush the queue before we returning origin top_widget->core.window or we can get X error since the window is gone */ XSync(xtclient->xtdisplay, False); xtclient->top_widget->core.window = xtclient->oldwindow; XtUnrealizeWidget(xtclient->top_widget); } static void xt_client_destroy (XtClient* xtclient) { if(xtclient->top_widget) { XtRemoveEventHandler(xtclient->child_widget, 0x0FFFFF, TRUE, (XtEventHandler)xt_client_event_handler, xtclient); XtDestroyWidget(xtclient->top_widget); xtclient->top_widget = NULL; } } static void xt_client_set_info (Widget xtplug, unsigned long flags) { unsigned long buffer[2]; Atom infoAtom = XInternAtom(XtDisplay(xtplug), "_XEMBED_INFO", False); buffer[1] = 0; /* Protocol version */ buffer[1] = flags; XChangeProperty (XtDisplay(xtplug), XtWindow(xtplug), infoAtom, infoAtom, 32, PropModeReplace, (unsigned char *)buffer, 2); } static void xt_client_handle_xembed_message(Widget w, XtPointer client_data, XEvent *event) { XtClient *xtplug = (XtClient*)client_data; switch (event->xclient.data.l[1]) { case XEMBED_EMBEDDED_NOTIFY: break; case XEMBED_WINDOW_ACTIVATE: #ifdef DEBUG_XTBIN printf("Xt client get XEMBED_WINDOW_ACTIVATE\n"); #endif break; case XEMBED_WINDOW_DEACTIVATE: #ifdef DEBUG_XTBIN printf("Xt client get XEMBED_WINDOW_DEACTIVATE\n"); #endif break; case XEMBED_MODALITY_ON: #ifdef DEBUG_XTBIN printf("Xt client get XEMBED_MODALITY_ON\n"); #endif break; case XEMBED_MODALITY_OFF: #ifdef DEBUG_XTBIN printf("Xt client get XEMBED_MODALITY_OFF\n"); #endif break; case XEMBED_FOCUS_IN: case XEMBED_FOCUS_OUT: { XEvent xevent; memset(&xevent, 0, sizeof(xevent)); if(event->xclient.data.l[1] == XEMBED_FOCUS_IN) { #ifdef DEBUG_XTBIN printf("XTEMBED got focus in\n"); #endif xevent.xfocus.type = FocusIn; } else { #ifdef DEBUG_XTBIN printf("XTEMBED got focus out\n"); #endif xevent.xfocus.type = FocusOut; } xevent.xfocus.window = XtWindow(xtplug->child_widget); xevent.xfocus.display = XtDisplay(xtplug->child_widget); XSendEvent(XtDisplay(xtplug->child_widget), xevent.xfocus.window, False, NoEventMask, &xevent ); XSync( XtDisplay(xtplug->child_widget), False); } break; default: break; } /* End of XEmbed Message */ } static void xt_client_event_handler( Widget w, XtPointer client_data, XEvent *event) { XtClient *xtplug = (XtClient*)client_data; switch(event->type) { case ClientMessage: /* Handle xembed message */ if (event->xclient.message_type== XInternAtom (XtDisplay(xtplug->child_widget), "_XEMBED", False)) { xt_client_handle_xembed_message(w, client_data, event); } break; case ReparentNotify: break; case MappingNotify: xt_client_set_info (w, XEMBED_MAPPED); break; case UnmapNotify: xt_client_set_info (w, 0); break; case FocusIn: send_xembed_message ( xtplug, XEMBED_REQUEST_FOCUS, 0, 0, 0, 0); break; case FocusOut: break; case KeyPress: #ifdef DEBUG_XTBIN printf("Key Press Got!\n"); #endif break; default: break; } /* End of switch(event->type) */ } static void send_xembed_message (XtClient *xtclient, long message, long detail, long data1, long data2, long time) { XEvent xevent; Window w=XtWindow(xtclient->top_widget); Display* dpy=xtclient->xtdisplay; int errorcode; memset(&xevent,0,sizeof(xevent)); xevent.xclient.window = w; xevent.xclient.type = ClientMessage; xevent.xclient.message_type = XInternAtom(dpy,"_XEMBED",False); xevent.xclient.format = 32; xevent.xclient.data.l[0] = time; xevent.xclient.data.l[1] = message; xevent.xclient.data.l[2] = detail; xevent.xclient.data.l[3] = data1; xevent.xclient.data.l[4] = data2; trap_errors (); XSendEvent (dpy, w, False, NoEventMask, &xevent); XSync (dpy,False); if((errorcode = untrap_error())) { #ifdef DEBUG_XTBIN printf("send_xembed_message error(%d)!!!\n",errorcode); #endif } } static int error_handler(Display *display, XErrorEvent *error) { trapped_error_code = error->error_code; return 0; } static void trap_errors(void) { trapped_error_code =0; old_error_handler = XSetErrorHandler(error_handler); } static int untrap_error(void) { XSetErrorHandler(old_error_handler); if(trapped_error_code) { #ifdef DEBUG_XTBIN printf("Get X Window Error = %d\n", trapped_error_code); #endif } return trapped_error_code; } static void xt_client_focus_listener( Widget w, XtPointer user_data, XEvent *event) { Display *dpy = XtDisplay(w); XtClient *xtclient = user_data; Window win = XtWindow(w); switch(event->type) { case CreateNotify: if(event->xcreatewindow.parent == win) { Widget child=XtWindowToWidget( dpy, event->xcreatewindow.window); if (child) xt_add_focus_listener_tree(child, user_data); } break; case DestroyNotify: xt_remove_focus_listener( w, user_data); break; case ReparentNotify: if(event->xreparent.parent == win) { /* I am the new parent */ Widget child=XtWindowToWidget(dpy, event->xreparent.window); if (child) xt_add_focus_listener_tree( child, user_data); } else if(event->xreparent.window == win) { /* I am the new child */ } else { /* I am the old parent */ } break; case ButtonRelease: #if 0 XSetInputFocus(dpy, XtWindow(xtclient->child_widget), RevertToParent, event->xbutton.time); #endif send_xembed_message ( xtclient, XEMBED_REQUEST_FOCUS, 0, 0, 0, 0); break; default: break; } /* End of switch(event->type) */ } static void xt_add_focus_listener( Widget w, XtPointer user_data) { XWindowAttributes attr; long eventmask; XtClient *xtclient = user_data; int errorcode; trap_errors (); XGetWindowAttributes(XtDisplay(w), XtWindow(w), &attr); eventmask = attr.your_event_mask | SubstructureNotifyMask | ButtonReleaseMask; XSelectInput(XtDisplay(w), XtWindow(w), eventmask); XtAddEventHandler(w, SubstructureNotifyMask | ButtonReleaseMask, TRUE, (XtEventHandler)xt_client_focus_listener, xtclient); untrap_error(); } static void xt_remove_focus_listener(Widget w, XtPointer user_data) { int errorcode; trap_errors (); XtRemoveEventHandler(w, SubstructureNotifyMask | ButtonReleaseMask, TRUE, (XtEventHandler)xt_client_focus_listener, user_data); untrap_error(); } static void xt_add_focus_listener_tree ( Widget treeroot, XtPointer user_data) { Window win = XtWindow(treeroot); Window *children; Window root, parent; Display *dpy = XtDisplay(treeroot); unsigned int i, nchildren; /* ensure we don't add more than once */ xt_remove_focus_listener( treeroot, user_data); xt_add_focus_listener( treeroot, user_data); trap_errors(); if(!XQueryTree(dpy, win, &root, &parent, &children, &nchildren)) { untrap_error(); return; } if(untrap_error()) return; for(i=0; i<nchildren; ++i) { Widget child = XtWindowToWidget(dpy, children[i]); if (child) xt_add_focus_listener_tree( child, user_data); } XFree((void*)children); return; }
EpicCM/SPH-D700-Kernel
external/webkit/WebCore/plugins/gtk/gtk2xtbin.c
C
gpl-2.0
26,348
/* Separate lexical analyzer for GNU C++. Copyright (C) 1987, 1989, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2007, 2008, 2010 Free Software Foundation, Inc. Hacked by Michael Tiemann (tiemann@cygnus.com) This file is part of GCC. GCC 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, or (at your option) any later version. GCC 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 GCC; see the file COPYING3. If not see <http://www.gnu.org/licenses/>. */ /* This file is the lexical analyzer for GNU C++. */ #include "config.h" #include "system.h" #include "coretypes.h" #include "tm.h" #include "input.h" #include "tree.h" #include "cp-tree.h" #include "cpplib.h" #include "flags.h" #include "c-family/c-pragma.h" #include "c-family/c-objc.h" #include "tm_p.h" #include "timevar.h" static int interface_strcmp (const char *); static void init_cp_pragma (void); static tree parse_strconst_pragma (const char *, int); static void handle_pragma_vtable (cpp_reader *); static void handle_pragma_unit (cpp_reader *); static void handle_pragma_interface (cpp_reader *); static void handle_pragma_implementation (cpp_reader *); static void handle_pragma_java_exceptions (cpp_reader *); static void init_operators (void); static void copy_lang_type (tree); /* A constraint that can be tested at compile time. */ #define CONSTRAINT(name, expr) extern int constraint_##name [(expr) ? 1 : -1] /* Functions and data structures for #pragma interface. `#pragma implementation' means that the main file being compiled is considered to implement (provide) the classes that appear in its main body. I.e., if this is file "foo.cc", and class `bar' is defined in "foo.cc", then we say that "foo.cc implements bar". All main input files "implement" themselves automagically. `#pragma interface' means that unless this file (of the form "foo.h" is not presently being included by file "foo.cc", the CLASSTYPE_INTERFACE_ONLY bit gets set. The effect is that none of the vtables nor any of the inline functions defined in foo.h will ever be output. There are cases when we want to link files such as "defs.h" and "main.cc". In this case, we give "defs.h" a `#pragma interface', and "main.cc" has `#pragma implementation "defs.h"'. */ struct impl_files { const char *filename; struct impl_files *next; }; static struct impl_files *impl_file_chain; /* True if we saw "#pragma GCC java_exceptions". */ bool pragma_java_exceptions; void cxx_finish (void) { c_common_finish (); } /* A mapping from tree codes to operator name information. */ operator_name_info_t operator_name_info[(int) MAX_TREE_CODES]; /* Similar, but for assignment operators. */ operator_name_info_t assignment_operator_name_info[(int) MAX_TREE_CODES]; /* Initialize data structures that keep track of operator names. */ #define DEF_OPERATOR(NAME, C, M, AR, AP) \ CONSTRAINT (C, sizeof "operator " + sizeof NAME <= 256); #include "operators.def" #undef DEF_OPERATOR static void init_operators (void) { tree identifier; char buffer[256]; struct operator_name_info_t *oni; #define DEF_OPERATOR(NAME, CODE, MANGLING, ARITY, ASSN_P) \ sprintf (buffer, ISALPHA (NAME[0]) ? "operator %s" : "operator%s", NAME); \ identifier = get_identifier (buffer); \ IDENTIFIER_OPNAME_P (identifier) = 1; \ \ oni = (ASSN_P \ ? &assignment_operator_name_info[(int) CODE] \ : &operator_name_info[(int) CODE]); \ oni->identifier = identifier; \ oni->name = NAME; \ oni->mangled_name = MANGLING; \ oni->arity = ARITY; #include "operators.def" #undef DEF_OPERATOR operator_name_info[(int) ERROR_MARK].identifier = get_identifier ("<invalid operator>"); /* Handle some special cases. These operators are not defined in the language, but can be produced internally. We may need them for error-reporting. (Eventually, we should ensure that this does not happen. Error messages involving these operators will be confusing to users.) */ operator_name_info [(int) INIT_EXPR].name = operator_name_info [(int) MODIFY_EXPR].name; operator_name_info [(int) EXACT_DIV_EXPR].name = "(ceiling /)"; operator_name_info [(int) CEIL_DIV_EXPR].name = "(ceiling /)"; operator_name_info [(int) FLOOR_DIV_EXPR].name = "(floor /)"; operator_name_info [(int) ROUND_DIV_EXPR].name = "(round /)"; operator_name_info [(int) CEIL_MOD_EXPR].name = "(ceiling %)"; operator_name_info [(int) FLOOR_MOD_EXPR].name = "(floor %)"; operator_name_info [(int) ROUND_MOD_EXPR].name = "(round %)"; operator_name_info [(int) ABS_EXPR].name = "abs"; operator_name_info [(int) TRUTH_AND_EXPR].name = "strict &&"; operator_name_info [(int) TRUTH_OR_EXPR].name = "strict ||"; operator_name_info [(int) RANGE_EXPR].name = "..."; operator_name_info [(int) UNARY_PLUS_EXPR].name = "+"; assignment_operator_name_info [(int) EXACT_DIV_EXPR].name = "(exact /=)"; assignment_operator_name_info [(int) CEIL_DIV_EXPR].name = "(ceiling /=)"; assignment_operator_name_info [(int) FLOOR_DIV_EXPR].name = "(floor /=)"; assignment_operator_name_info [(int) ROUND_DIV_EXPR].name = "(round /=)"; assignment_operator_name_info [(int) CEIL_MOD_EXPR].name = "(ceiling %=)"; assignment_operator_name_info [(int) FLOOR_MOD_EXPR].name = "(floor %=)"; assignment_operator_name_info [(int) ROUND_MOD_EXPR].name = "(round %=)"; } /* Initialize the reserved words. */ void init_reswords (void) { unsigned int i; tree id; int mask = 0; if (cxx_dialect < cxx0x) mask |= D_CXX0X; if (flag_no_asm) mask |= D_ASM | D_EXT; if (flag_no_gnu_keywords) mask |= D_EXT; /* The Objective-C keywords are all context-dependent. */ mask |= D_OBJC; ridpointers = ggc_alloc_cleared_vec_tree ((int) RID_MAX); for (i = 0; i < num_c_common_reswords; i++) { if (c_common_reswords[i].disable & D_CONLY) continue; id = get_identifier (c_common_reswords[i].word); C_SET_RID_CODE (id, c_common_reswords[i].rid); ridpointers [(int) c_common_reswords[i].rid] = id; if (! (c_common_reswords[i].disable & mask)) C_IS_RESERVED_WORD (id) = 1; } } static void init_cp_pragma (void) { c_register_pragma (0, "vtable", handle_pragma_vtable); c_register_pragma (0, "unit", handle_pragma_unit); c_register_pragma (0, "interface", handle_pragma_interface); c_register_pragma (0, "implementation", handle_pragma_implementation); c_register_pragma ("GCC", "interface", handle_pragma_interface); c_register_pragma ("GCC", "implementation", handle_pragma_implementation); c_register_pragma ("GCC", "java_exceptions", handle_pragma_java_exceptions); } /* TRUE if a code represents a statement. */ bool statement_code_p[MAX_TREE_CODES]; /* Initialize the C++ front end. This function is very sensitive to the exact order that things are done here. It would be nice if the initialization done by this routine were moved to its subroutines, and the ordering dependencies clarified and reduced. */ bool cxx_init (void) { location_t saved_loc; unsigned int i; static const enum tree_code stmt_codes[] = { CTOR_INITIALIZER, TRY_BLOCK, HANDLER, EH_SPEC_BLOCK, USING_STMT, TAG_DEFN, IF_STMT, CLEANUP_STMT, FOR_STMT, RANGE_FOR_STMT, WHILE_STMT, DO_STMT, BREAK_STMT, CONTINUE_STMT, SWITCH_STMT, EXPR_STMT }; memset (&statement_code_p, 0, sizeof (statement_code_p)); for (i = 0; i < ARRAY_SIZE (stmt_codes); i++) statement_code_p[stmt_codes[i]] = true; saved_loc = input_location; input_location = BUILTINS_LOCATION; init_reswords (); init_tree (); init_cp_semantics (); init_operators (); init_method (); init_error (); current_function_decl = NULL; class_type_node = ridpointers[(int) RID_CLASS]; cxx_init_decl_processing (); if (c_common_init () == false) { input_location = saved_loc; return false; } init_cp_pragma (); init_repo (); input_location = saved_loc; return true; } /* Return nonzero if S is not considered part of an INTERFACE/IMPLEMENTATION pair. Otherwise, return 0. */ static int interface_strcmp (const char* s) { /* Set the interface/implementation bits for this scope. */ struct impl_files *ifiles; const char *s1; for (ifiles = impl_file_chain; ifiles; ifiles = ifiles->next) { const char *t1 = ifiles->filename; s1 = s; if (*s1 == 0 || filename_ncmp (s1, t1, 1) != 0) continue; while (*s1 != 0 && filename_ncmp (s1, t1, 1) == 0) s1++, t1++; /* A match. */ if (*s1 == *t1) return 0; /* Don't get faked out by xxx.yyy.cc vs xxx.zzz.cc. */ if (strchr (s1, '.') || strchr (t1, '.')) continue; if (*s1 == '\0' || s1[-1] != '.' || t1[-1] != '.') continue; /* A match. */ return 0; } /* No matches. */ return 1; } /* Parse a #pragma whose sole argument is a string constant. If OPT is true, the argument is optional. */ static tree parse_strconst_pragma (const char* name, int opt) { tree result, x; enum cpp_ttype t; t = pragma_lex (&result); if (t == CPP_STRING) { if (pragma_lex (&x) != CPP_EOF) warning (0, "junk at end of #pragma %s", name); return result; } if (t == CPP_EOF && opt) return NULL_TREE; error ("invalid #pragma %s", name); return error_mark_node; } static void handle_pragma_vtable (cpp_reader* /*dfile*/) { parse_strconst_pragma ("vtable", 0); sorry ("#pragma vtable no longer supported"); } static void handle_pragma_unit (cpp_reader* /*dfile*/) { /* Validate syntax, but don't do anything. */ parse_strconst_pragma ("unit", 0); } static void handle_pragma_interface (cpp_reader* /*dfile*/) { tree fname = parse_strconst_pragma ("interface", 1); struct c_fileinfo *finfo; const char *filename; if (fname == error_mark_node) return; else if (fname == 0) filename = lbasename (input_filename); else filename = TREE_STRING_POINTER (fname); finfo = get_fileinfo (input_filename); if (impl_file_chain == 0) { /* If this is zero at this point, then we are auto-implementing. */ if (main_input_filename == 0) main_input_filename = input_filename; } finfo->interface_only = interface_strcmp (filename); /* If MULTIPLE_SYMBOL_SPACES is set, we cannot assume that we can see a definition in another file. */ if (!MULTIPLE_SYMBOL_SPACES || !finfo->interface_only) finfo->interface_unknown = 0; } /* Note that we have seen a #pragma implementation for the key MAIN_FILENAME. We used to only allow this at toplevel, but that restriction was buggy in older compilers and it seems reasonable to allow it in the headers themselves, too. It only needs to precede the matching #p interface. We don't touch finfo->interface_only or finfo->interface_unknown; the user must specify a matching #p interface for this to have any effect. */ static void handle_pragma_implementation (cpp_reader* /*dfile*/) { tree fname = parse_strconst_pragma ("implementation", 1); const char *filename; struct impl_files *ifiles = impl_file_chain; if (fname == error_mark_node) return; if (fname == 0) { if (main_input_filename) filename = main_input_filename; else filename = input_filename; filename = lbasename (filename); } else { filename = TREE_STRING_POINTER (fname); if (cpp_included_before (parse_in, filename, input_location)) warning (0, "#pragma implementation for %qs appears after " "file is included", filename); } for (; ifiles; ifiles = ifiles->next) { if (! filename_cmp (ifiles->filename, filename)) break; } if (ifiles == 0) { ifiles = XNEW (struct impl_files); ifiles->filename = xstrdup (filename); ifiles->next = impl_file_chain; impl_file_chain = ifiles; } } /* Indicate that this file uses Java-personality exception handling. */ static void handle_pragma_java_exceptions (cpp_reader* /*dfile*/) { tree x; if (pragma_lex (&x) != CPP_EOF) warning (0, "junk at end of #pragma GCC java_exceptions"); choose_personality_routine (lang_java); pragma_java_exceptions = true; } /* Issue an error message indicating that the lookup of NAME (an IDENTIFIER_NODE) failed. Returns the ERROR_MARK_NODE. */ tree unqualified_name_lookup_error (tree name) { if (IDENTIFIER_OPNAME_P (name)) { if (name != ansi_opname (ERROR_MARK)) error ("%qD not defined", name); } else { if (!objc_diagnose_private_ivar (name)) { error ("%qD was not declared in this scope", name); suggest_alternatives_for (location_of (name), name); } /* Prevent repeated error messages by creating a VAR_DECL with this NAME in the innermost block scope. */ if (local_bindings_p ()) { tree decl; decl = build_decl (input_location, VAR_DECL, name, error_mark_node); DECL_CONTEXT (decl) = current_function_decl; push_local_binding (name, decl, 0); /* Mark the variable as used so that we do not get warnings about it being unused later. */ TREE_USED (decl) = 1; } } return error_mark_node; } /* Like unqualified_name_lookup_error, but NAME is an unqualified-id used as a function. Returns an appropriate expression for NAME. */ tree unqualified_fn_lookup_error (tree name) { if (processing_template_decl) { /* In a template, it is invalid to write "f()" or "f(3)" if no declaration of "f" is available. Historically, G++ and most other compilers accepted that usage since they deferred all name lookup until instantiation time rather than doing unqualified name lookup at template definition time; explain to the user what is going wrong. Note that we have the exact wording of the following message in the manual (trouble.texi, node "Name lookup"), so they need to be kept in synch. */ permerror (input_location, "there are no arguments to %qD that depend on a template " "parameter, so a declaration of %qD must be available", name, name); if (!flag_permissive) { static bool hint; if (!hint) { inform (input_location, "(if you use %<-fpermissive%>, G++ will accept your " "code, but allowing the use of an undeclared name is " "deprecated)"); hint = true; } } return name; } return unqualified_name_lookup_error (name); } /* Wrapper around build_lang_decl_loc(). Should gradually move to build_lang_decl_loc() and then rename build_lang_decl_loc() back to build_lang_decl(). */ tree build_lang_decl (enum tree_code code, tree name, tree type) { return build_lang_decl_loc (input_location, code, name, type); } /* Build a decl from CODE, NAME, TYPE declared at LOC, and then add DECL_LANG_SPECIFIC info to the result. */ tree build_lang_decl_loc (location_t loc, enum tree_code code, tree name, tree type) { tree t; t = build_decl (loc, code, name, type); retrofit_lang_decl (t); return t; } /* Add DECL_LANG_SPECIFIC info to T. Called from build_lang_decl and pushdecl (for functions generated by the back end). */ void retrofit_lang_decl (tree t) { struct lang_decl *ld; size_t size; int sel; if (TREE_CODE (t) == FUNCTION_DECL) sel = 1, size = sizeof (struct lang_decl_fn); else if (TREE_CODE (t) == NAMESPACE_DECL) sel = 2, size = sizeof (struct lang_decl_ns); else if (TREE_CODE (t) == PARM_DECL) sel = 3, size = sizeof (struct lang_decl_parm); else if (LANG_DECL_HAS_MIN (t)) sel = 0, size = sizeof (struct lang_decl_min); else gcc_unreachable (); ld = ggc_alloc_cleared_lang_decl (size); ld->u.base.selector = sel; DECL_LANG_SPECIFIC (t) = ld; if (current_lang_name == lang_name_cplusplus || decl_linkage (t) == lk_none) SET_DECL_LANGUAGE (t, lang_cplusplus); else if (current_lang_name == lang_name_c) SET_DECL_LANGUAGE (t, lang_c); else if (current_lang_name == lang_name_java) SET_DECL_LANGUAGE (t, lang_java); else gcc_unreachable (); if (GATHER_STATISTICS) { tree_node_counts[(int)lang_decl] += 1; tree_node_sizes[(int)lang_decl] += size; } } void cxx_dup_lang_specific_decl (tree node) { int size; struct lang_decl *ld; if (! DECL_LANG_SPECIFIC (node)) return; if (TREE_CODE (node) == FUNCTION_DECL) size = sizeof (struct lang_decl_fn); else if (TREE_CODE (node) == NAMESPACE_DECL) size = sizeof (struct lang_decl_ns); else if (TREE_CODE (node) == PARM_DECL) size = sizeof (struct lang_decl_parm); else if (LANG_DECL_HAS_MIN (node)) size = sizeof (struct lang_decl_min); else gcc_unreachable (); ld = ggc_alloc_lang_decl (size); memcpy (ld, DECL_LANG_SPECIFIC (node), size); DECL_LANG_SPECIFIC (node) = ld; if (GATHER_STATISTICS) { tree_node_counts[(int)lang_decl] += 1; tree_node_sizes[(int)lang_decl] += size; } } /* Copy DECL, including any language-specific parts. */ tree copy_decl (tree decl) { tree copy; copy = copy_node (decl); cxx_dup_lang_specific_decl (copy); return copy; } /* Replace the shared language-specific parts of NODE with a new copy. */ static void copy_lang_type (tree node) { int size; struct lang_type *lt; if (! TYPE_LANG_SPECIFIC (node)) return; if (TYPE_LANG_SPECIFIC (node)->u.h.is_lang_type_class) size = sizeof (struct lang_type); else size = sizeof (struct lang_type_ptrmem); lt = ggc_alloc_lang_type (size); memcpy (lt, TYPE_LANG_SPECIFIC (node), size); TYPE_LANG_SPECIFIC (node) = lt; if (GATHER_STATISTICS) { tree_node_counts[(int)lang_type] += 1; tree_node_sizes[(int)lang_type] += size; } } /* Copy TYPE, including any language-specific parts. */ tree copy_type (tree type) { tree copy; copy = copy_node (type); copy_lang_type (copy); return copy; } tree cxx_make_type (enum tree_code code) { tree t = make_node (code); /* Create lang_type structure. */ if (RECORD_OR_UNION_CODE_P (code) || code == BOUND_TEMPLATE_TEMPLATE_PARM) { struct lang_type *pi = ggc_alloc_cleared_lang_type (sizeof (struct lang_type)); TYPE_LANG_SPECIFIC (t) = pi; pi->u.c.h.is_lang_type_class = 1; if (GATHER_STATISTICS) { tree_node_counts[(int)lang_type] += 1; tree_node_sizes[(int)lang_type] += sizeof (struct lang_type); } } /* Set up some flags that give proper default behavior. */ if (RECORD_OR_UNION_CODE_P (code)) { struct c_fileinfo *finfo = get_fileinfo (input_filename); SET_CLASSTYPE_INTERFACE_UNKNOWN_X (t, finfo->interface_unknown); CLASSTYPE_INTERFACE_ONLY (t) = finfo->interface_only; } return t; } tree make_class_type (enum tree_code code) { tree t = cxx_make_type (code); SET_CLASS_TYPE_P (t, 1); return t; } /* Returns true if we are currently in the main source file, or in a template instantiation started from the main source file. */ bool in_main_input_context (void) { struct tinst_level *tl = outermost_tinst_level(); if (tl) return filename_cmp (main_input_filename, LOCATION_FILE (tl->locus)) == 0; else return filename_cmp (main_input_filename, input_filename) == 0; }
h4ck3rm1k3/gcc
gcc/cp/lex.c
C
gpl-2.0
19,780
/* packet-forces.c * RFC 5810 * Routines for dissecting IETF ForCES protocol layer messages.Now support the following TML types:TCP+UDP,SCTP. * Copyright 2009, NDSC & Zhejiang Gongshang University,Fenggen Jia <fgjia@mail.zjgsu.edu.cn or fenggen.jia@gmail.com> * * $Id$ * * Wireshark - Network traffic analyzer * By Gerald Combs <gerald@wireshark.org> * Copyright 1998 Gerald Combs * * 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. * * This program 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 this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "config.h" #include <glib.h> #include <epan/packet.h> #include <epan/prefs.h> #include <epan/expert.h> static dissector_handle_t ip_handle; /* Initialize the ForCES protocol and registered fields */ static int proto_forces = -1; /*Main header*/ static int hf_forces_version = -1; static int hf_forces_rsvd = -1; static int hf_forces_messagetype = -1; static int hf_forces_sid = -1; static int hf_forces_did = -1; static int hf_forces_correlator = -1; static int hf_forces_length = -1; /*Flags*/ static int hf_forces_flags= -1; static int hf_forces_flags_ack= -1; static int hf_forces_flags_pri= -1; static int hf_forces_flags_rsrvd= -1; static int hf_forces_flags_em= -1; static int hf_forces_flags_at= -1; static int hf_forces_flags_tp= -1; static int hf_forces_flags_reserved = -1; static int hf_forces_tlv_type = -1; static int hf_forces_tlv_length = -1; /*Initiation of LFBSelect TLV*/ static int hf_forces_lfbselect_tlv_type_lfb_classid = -1; static int hf_forces_lfbselect_tlv_type_lfb_instanceid = -1; /*Initiation of Operation TLV*/ static int hf_forces_lfbselect_tlv_type_operation_type = -1; static int hf_forces_lfbselect_tlv_type_operation_length = -1; static int hf_forces_lfbselect_tlv_type_operation_path_type = -1; static int hf_forces_lfbselect_tlv_type_operation_path_length = -1; static int hf_forces_lfbselect_tlv_type_operation_path_flags = -1; static int hf_forces_lfbselect_tlv_type_operation_path_flags_selector = -1; static int hf_forces_lfbselect_tlv_type_operation_path_flags_reserved = -1; static int hf_forces_lfbselect_tlv_type_operation_path_IDcount = -1; static int hf_forces_lfbselect_tlv_type_operation_path_IDs = -1; static int hf_forces_lfbselect_tlv_type_operation_path_data = -1; /*Initiation of Redirect TLV*/ static int hf_forces_redirect_tlv_meta_data_tlv_type = -1; static int hf_forces_redirect_tlv_meta_data_tlv_length = -1; static int hf_forces_redirect_tlv_meta_data_tlv_meta_data_ilv = -1; static int hf_forces_redirect_tlv_meta_data_tlv_meta_data_ilv_id = -1; static int hf_forces_redirect_tlv_meta_data_tlv_meta_data_ilv_length = -1; static int hf_forces_redirect_tlv_redirect_data_tlv_type = -1; static int hf_forces_redirect_tlv_redirect_data_tlv_length = -1; /*Initiation of ASResult TLV*/ static int hf_forces_asresult_association_setup_result = -1; /*Initiation of ASTreason TLV*/ static int hf_forces_astreason_tlv_teardown_reason = -1; /*Main TLV may be unknown*/ static int hf_forces_unknown_tlv = -1; /*Message Types */ #define AssociationSetup 0x01 #define AssociationTeardown 0x02 #define Config 0x03 #define Query 0x04 #define EventNotification 0x05 #define PacketRedirect 0x06 #define Heartbeat 0x0F #define AssociationSetupRepsonse 0x11 #define ConfigResponse 0x13 #define QueryResponse 0x14 /*TLV Types*/ #define Reserved 0x0000 #define REDIRECT_TLV 0x0001 #define ASResult_TLV 0x0010 #define ASTreason_TLV 0x0011 #define LFBselect_TLV 0x1000 #define PATH_DATA_TLV 0x0110 #define KEYINFO_TLV 0x0111 #define FULLDATA_TLV 0x0112 #define SPARSEDATA_TLV 0x0113 #define RESULT_TLV 0x0114 #define METADATA_TLV 0x0115 #define REDIRECTDATA_TLV 0x0116 /*Operation Type*/ #define Reserved 0x0000 #define SET 0x0001 #define SET_PROP 0x0002 #define SET_RESPONSE 0x0003 #define SET_PROP_RESPONSE 0x0004 #define DEL 0x0005 #define DEL_RESPONSE 0x0006 #define GET 0x0007 #define GET_PROP 0x0008 #define GET_RESPONSE 0x0009 #define GET_PROP_RESPONSE 0x000A #define REPORT 0x000B #define COMMIT 0x000C #define COMMIT_RESPONSE 0x000D #define TRCOMP 0x000E #define FLAG_SELECTOR 0x8000 #define ForCES_HEADER_LENGTH 24 #define TLV_TL_LENGTH 4 /*Type+length*/ #define MIN_IP_HEADER_LENGTH 20 /*For TCP+UDP TML. There are two bytes added to the ForCES PL message, not strictly combine to the ForCES protocol. For other type TMLs,no need to add these 2 bytes.*/ #define TCP_UDP_TML_FOCES_MESSAGE_OFFSET_TCP 2 /*TCP+UDP TML*/ static guint forces_alternate_tcp_port = 0; static guint forces_alternate_udp_port = 0; /*SCTP TML*/ static guint forces_alternate_sctp_high_prio_channel_port = 0; static guint forces_alternate_sctp_med_prio_channel_port = 0; static guint forces_alternate_sctp_low_prio_channel_port = 0; /*Initialize the subtree pointers*/ static gint ett_forces = -1; static gint ett_forces_main_header = -1; static gint ett_forces_flags = -1; static gint ett_forces_tlv = -1; static gint ett_forces_lfbselect_tlv_type = -1; /*Operation TLV subtree*/ static gint ett_forces_lfbselect_tlv_type_operation = -1; static gint ett_forces_lfbselect_tlv_type_operation_path = -1; static gint ett_forces_lfbselect_tlv_type_operation_path_data = -1; static gint ett_forces_lfbselect_tlv_type_operation_path_data_path = -1; static gint ett_forces_path_data_tlv = -1; static gint ett_forces_path_data_tlv_flags = -1; /*Selector subtree*/ static gint ett_forces_lfbselect_tlv_type_operation_path_selector = -1; /*Redirect TLV subtree*/ static gint ett_forces_redirect_tlv_type = -1; static gint ett_forces_redirect_tlv_meta_data_tlv = -1; static gint ett_forces_redirect_tlv_meta_data_tlv_meta_data_ilv = -1; static gint ett_forces_redirect_tlv_redirect_data_tlv = -1; /*ASResult TLV subtree*/ static gint ett_forces_asresult_tlv = -1; /*ASReason subtree*/ static gint ett_forces_astreason_tlv = -1; /*Main_TLV unknown subtree*/ static gint ett_forces_unknown_tlv = -1; static expert_field ei_forces_length = EI_INIT; static expert_field ei_forces_tlv_type = EI_INIT; static expert_field ei_forces_tlv_length = EI_INIT; static expert_field ei_forces_lfbselect_tlv_type_operation_path_length = EI_INIT; static expert_field ei_forces_lfbselect_tlv_type_operation_type = EI_INIT; static expert_field ei_forces_redirect_tlv_redirect_data_tlv_length = EI_INIT; /*ACK values and the strings to be displayed*/ static const value_string main_header_flags_ack_vals[] = { { 0x0, "NoACK" }, { 0x1, "SuccessACK" }, { 0x2, "FailureACK" }, { 0x3, "AlwaysACK" }, { 0, NULL} }; /*Execution mode(EM) values and the strings to be displayed*/ static const value_string main_header_flags_em_vals[] = { { 0x0, "Reserved" }, { 0x1, "Execute-all-or-none" }, { 0x2, "Execute-until-failure" }, { 0x3, "Continue-execute-on-failure" }, { 0, NULL} }; /*Transaction Phase values and the strings to be displayed*/ static const value_string main_header_flags_tp_vals[] = { { 0x0, "SOT (Start of Transaction)" }, { 0x1, "MOT (Middle of Transaction)" }, { 0x2, "EOT (End of Transaction)" }, { 0x3, "ABT (Abort)" }, { 0, NULL} }; /*Atomic Transaction(AT) values and the strings to be displayed*/ static const value_string main_header_flags_at_vals[] = { { 0x0, "Stand-alone Message"}, { 0x1, "2PC Transaction Message"}, { 0, NULL} }; /*Association Setup Result*/ static const value_string association_setup_result_at_vals[] = { { 0x0, "success"}, { 0x1, "FE ID invalid"}, { 0x2, "permission denied"}, { 0, NULL}, }; /*Teardown Reason*/ static const value_string teardown_reason_at_vals[] = { { 0x0, "normal-teardown by administrator"}, { 0x1, "error - loss of heartbeats"}, { 0x2, "error - out of bandwidth"}, { 0x3, "error - out of memory"}, { 0x4, "error - application crash"}, { 0x255, "error - other or unspecified"}, { 0, NULL}, }; static const value_string message_type_vals[] = { { AssociationSetup, "AssociationSetup" }, { AssociationTeardown, "AssociationTeardown" }, { Config, "Config" }, { Query, "Query" }, { EventNotification, "EventNotification" }, { PacketRedirect, "PacketRedirect" }, { Heartbeat, "Heartbeat" }, { AssociationSetupRepsonse, "AssociationSetupRepsonse" }, { ConfigResponse, "ConfigResponse" }, { QueryResponse, "QueryResponse" }, { 0, NULL}, }; static const value_string tlv_type_vals[] = { { REDIRECT_TLV, "REDIRECT-TLV" }, { ASResult_TLV, "ASResult-TLV" }, { ASTreason_TLV, "ASTreason-TLV" }, { LFBselect_TLV, "LFBselect-TLV" }, { PATH_DATA_TLV, "PATH DATA-TLV" }, { KEYINFO_TLV, "KEYINFO-TLV" }, { FULLDATA_TLV, "FULLDATA-TLV" }, { SPARSEDATA_TLV, "SPARSEDATA-TLV" }, { RESULT_TLV, "RESULT-TLV" }, { METADATA_TLV, "METADATA-TLV" }, { REDIRECTDATA_TLV, "REDIRECTDATA-TLV" }, { 0, NULL}, }; static const value_string operation_type_vals[] = { { Reserved, "Reserved" }, { SET, "SET" }, { SET_PROP, "SET-PROP" }, { SET_RESPONSE, "SET-RESPONSE" }, { SET_PROP_RESPONSE, "SET-PROP-RESPONSE" }, { DEL, "DEL" }, { DEL_RESPONSE, "DEL-RESPONSE" }, { GET, "GET" }, { GET_PROP, "GET-PROP" }, { GET_RESPONSE, "GET-RESPONSE" }, { GET_PROP_RESPONSE, "GET-PROP-RESPONSE" }, { REPORT, "REPORT" }, { COMMIT, "COMMIT" }, { COMMIT_RESPONSE, "COMMIT-RESPONSE" }, { TRCOMP, "TRCOMP" }, { 0, NULL}, }; static void dissect_path_data_tlv(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, gint offset) { proto_item *ti, *flag_item; guint length_TLV, IDcount, i; guint16 type, flag; proto_tree *tlv_tree, *path_data_tree, *flag_tree; while (tvb_reported_length_remaining(tvb, offset) >= TLV_TL_LENGTH) { ti = proto_tree_add_text(tree, tvb, offset, TLV_TL_LENGTH, "TLV"); tlv_tree = proto_item_add_subtree(ti, ett_forces_path_data_tlv); type = tvb_get_ntohs(tvb, offset); proto_tree_add_item(tlv_tree, hf_forces_lfbselect_tlv_type_operation_path_type, tvb, offset, 2, ENC_BIG_ENDIAN); length_TLV = tvb_get_ntohs(tvb, offset+2); proto_tree_add_item(tlv_tree, hf_forces_lfbselect_tlv_type_operation_path_length, tvb, offset+2, 2, ENC_BIG_ENDIAN); if (length_TLV < TLV_TL_LENGTH) { expert_add_info_format(pinfo, ti, &ei_forces_lfbselect_tlv_type_operation_path_length, "Bogus TLV length: %u", length_TLV); break; } proto_item_set_len(ti, length_TLV); if (type == PATH_DATA_TLV) { ti = proto_tree_add_text(tree, tvb, offset+TLV_TL_LENGTH, length_TLV-TLV_TL_LENGTH, "Path Data TLV"); path_data_tree = proto_item_add_subtree(ti, ett_forces_path_data_tlv); flag = tvb_get_ntohs(tvb, offset+TLV_TL_LENGTH); flag_item = proto_tree_add_item(path_data_tree, hf_forces_lfbselect_tlv_type_operation_path_flags, tvb, offset+TLV_TL_LENGTH, 2, ENC_BIG_ENDIAN); flag_tree = proto_item_add_subtree(flag_item, ett_forces_path_data_tlv_flags); proto_tree_add_item(flag_tree, hf_forces_lfbselect_tlv_type_operation_path_flags_selector, tvb, offset+TLV_TL_LENGTH, 2, ENC_BIG_ENDIAN); proto_tree_add_item(flag_tree, hf_forces_lfbselect_tlv_type_operation_path_flags_reserved, tvb, offset+TLV_TL_LENGTH, 2, ENC_BIG_ENDIAN); IDcount = tvb_get_ntohs(tvb, offset + TLV_TL_LENGTH + 2); proto_tree_add_item(path_data_tree, hf_forces_lfbselect_tlv_type_operation_path_IDcount, tvb, offset+TLV_TL_LENGTH+2, 2, ENC_BIG_ENDIAN); for (i = 0; i < IDcount; i++) proto_tree_add_item(path_data_tree, hf_forces_lfbselect_tlv_type_operation_path_IDs, tvb, offset+TLV_TL_LENGTH+2+(i*4), 4, ENC_BIG_ENDIAN); } else { flag = 0; proto_tree_add_item(tree, hf_forces_lfbselect_tlv_type_operation_path_data, tvb, offset+TLV_TL_LENGTH, length_TLV-TLV_TL_LENGTH, ENC_NA); } if ((flag & FLAG_SELECTOR) == 0) break; offset += length_TLV; } } static void dissect_operation_tlv(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, gint offset, gint length_count) { proto_item *ti; proto_tree *oper_tree; guint type, length; while (tvb_reported_length_remaining(tvb, offset) >= TLV_TL_LENGTH) { ti = proto_tree_add_text(tree, tvb, offset, length_count, "Operation TLV"); oper_tree = proto_item_add_subtree(ti, ett_forces_lfbselect_tlv_type_operation); type = tvb_get_ntohs(tvb,offset); ti = proto_tree_add_item(oper_tree, hf_forces_lfbselect_tlv_type_operation_type, tvb, offset, 2, ENC_BIG_ENDIAN); if (try_val_to_str(type, operation_type_vals) == NULL) expert_add_info_format(pinfo, ti, &ei_forces_lfbselect_tlv_type_operation_type, "Bogus: ForCES Operation TLV (Type:0x%04x) is not supported", type); length = tvb_get_ntohs(tvb, offset+2); proto_tree_add_uint_format_value(oper_tree, hf_forces_lfbselect_tlv_type_operation_length, tvb, offset+2, 2, length, "%u Bytes", length); dissect_path_data_tlv(tvb, pinfo, oper_tree, offset+TLV_TL_LENGTH); if (length == 0) break; offset += length; } } static void dissect_lfbselecttlv(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, gint offset, gint length_count) { guint tlv_length; proto_tree_add_item(tree, hf_forces_lfbselect_tlv_type_lfb_classid, tvb, offset, 4, ENC_BIG_ENDIAN); proto_tree_add_item(tree, hf_forces_lfbselect_tlv_type_lfb_instanceid, tvb, offset+4, 4, ENC_BIG_ENDIAN); offset += 8; while ((tvb_reported_length_remaining(tvb, offset) > TLV_TL_LENGTH) && (length_count > 12)) { tlv_length = tvb_get_ntohs(tvb, offset+2); dissect_operation_tlv(tvb, pinfo, tree, offset, tlv_length); if (tlv_length == 0) break; offset += tlv_length; } } static void dissect_redirecttlv(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, gint offset) { proto_tree *meta_data_tree, *meta_data_ilv_tree, *redirect_data_tree; gint start_offset; gint length_meta, length_ilv, length_redirect; proto_item *ti; address src_addr = pinfo->src, src_net_addr = pinfo->net_src, dst_addr = pinfo->dst, dst_net_addr = pinfo->net_dst; ti = proto_tree_add_text(tree, tvb, offset, TLV_TL_LENGTH, "Meta Data TLV"); meta_data_tree = proto_item_add_subtree(ti, ett_forces_redirect_tlv_meta_data_tlv); proto_tree_add_item(meta_data_tree, hf_forces_redirect_tlv_meta_data_tlv_type, tvb, offset, 2, ENC_BIG_ENDIAN); length_meta = tvb_get_ntohs(tvb, offset+2); proto_tree_add_uint_format_value(meta_data_tree, hf_forces_redirect_tlv_meta_data_tlv_length, tvb, offset+2, 2, length_meta, "%u Bytes", length_meta); proto_item_set_len(ti, length_meta); start_offset = offset; while ((tvb_reported_length_remaining(tvb, offset) >= 8) && (start_offset+length_meta > offset)) { ti = proto_tree_add_text(tree, tvb, offset, TLV_TL_LENGTH, "Meta Data ILV"); meta_data_ilv_tree = proto_item_add_subtree(ti, ett_forces_redirect_tlv_meta_data_tlv_meta_data_ilv); proto_tree_add_item(meta_data_ilv_tree, hf_forces_redirect_tlv_meta_data_tlv_meta_data_ilv_id, tvb, offset+8, 4, ENC_BIG_ENDIAN); length_ilv = tvb_get_ntohl(tvb, offset+12); proto_tree_add_uint_format_value(meta_data_ilv_tree, hf_forces_redirect_tlv_meta_data_tlv_meta_data_ilv_length, tvb, offset+12, 4, length_ilv, "%u Bytes", length_ilv); if (length_ilv > 0) proto_tree_add_item(meta_data_ilv_tree, hf_forces_redirect_tlv_meta_data_tlv_meta_data_ilv, tvb, offset+8, length_ilv, ENC_NA); proto_item_set_len(ti, length_ilv + 8); offset += length_ilv + 8; } if (tvb_reported_length_remaining(tvb, offset) > 0) { ti = proto_tree_add_text(tree, tvb, offset, TLV_TL_LENGTH, "Redirect Data TLV"); redirect_data_tree = proto_item_add_subtree(ti, ett_forces_redirect_tlv_redirect_data_tlv); proto_tree_add_item(redirect_data_tree, hf_forces_redirect_tlv_redirect_data_tlv_type, tvb, offset, 2, ENC_BIG_ENDIAN); length_redirect = tvb_get_ntohs(tvb, offset+2); proto_tree_add_uint_format_value(redirect_data_tree, hf_forces_redirect_tlv_redirect_data_tlv_length, tvb, offset+2, 2, length_redirect, "%u Bytes", length_redirect); if (tvb_reported_length_remaining(tvb, offset) < length_redirect) { expert_add_info_format(pinfo, ti, &ei_forces_redirect_tlv_redirect_data_tlv_length, "Bogus: Redirect Data TLV length (%u bytes) is wrong", length_redirect); } else if (length_redirect < TLV_TL_LENGTH + MIN_IP_HEADER_LENGTH) { expert_add_info_format(pinfo, ti, &ei_forces_redirect_tlv_redirect_data_tlv_length, "Bogus: Redirect Data TLV length (%u bytes) not big enough for IP layer", length_redirect); } else { tvbuff_t *next_tvb; next_tvb = tvb_new_subset(tvb, offset+4, length_redirect-TLV_TL_LENGTH, length_redirect-TLV_TL_LENGTH); call_dissector(ip_handle, next_tvb, pinfo, redirect_data_tree); /* Restore IP info */ memcpy(&(pinfo->src), &src_addr, sizeof(address)); memcpy(&(pinfo->net_src), &src_net_addr, sizeof(address)); memcpy(&(pinfo->dst), &dst_addr, sizeof(address)); memcpy(&(pinfo->net_dst), &dst_net_addr, sizeof(address)); } } } static void dissect_forces(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint32 offset) { /* Set up structures needed to add the protocol subtree and manage it */ proto_item *ti, *tlv_item; proto_tree *forces_tree, *forces_flags_tree; proto_tree *forces_main_header_tree, *forces_tlv_tree, *tlv_tree; gint length_count; guint8 message_type; guint16 tlv_type; /* Make entries in Protocol column and Info column on summary display */ col_set_str(pinfo->cinfo, COL_PROTOCOL, "ForCES"); col_clear(pinfo->cinfo, COL_INFO); ti = proto_tree_add_item(tree, proto_forces, tvb, 0, -1, ENC_NA); forces_tree = proto_item_add_subtree(ti, ett_forces); ti = proto_tree_add_text(forces_tree, tvb, 0, ForCES_HEADER_LENGTH, "Common Header"); forces_main_header_tree = proto_item_add_subtree(ti, ett_forces_main_header); proto_tree_add_item(forces_main_header_tree, hf_forces_version, tvb, 0, 1, ENC_BIG_ENDIAN); proto_tree_add_item(forces_main_header_tree, hf_forces_rsvd, tvb, 0, 1, ENC_BIG_ENDIAN); message_type = tvb_get_guint8(tvb, offset+1); proto_tree_add_item( forces_main_header_tree, hf_forces_messagetype, tvb, offset+1, 1, ENC_BIG_ENDIAN); length_count = tvb_get_ntohs(tvb, offset+2) * 4; /*multiply 4 DWORD*/ ti = proto_tree_add_uint_format( forces_main_header_tree, hf_forces_length, tvb, offset+2, 2, length_count, "Length: %u Bytes", length_count); if (length_count != tvb_reported_length_remaining(tvb, offset)) expert_add_info_format(pinfo, ti, &ei_forces_length, "Bogus: ForCES Header length (%u bytes) is wrong),should be (%u bytes)", length_count, tvb_reported_length_remaining(tvb, offset)); if (length_count < 24) expert_add_info_format(pinfo, ti, &ei_forces_length, "Bogus: ForCES Header length (%u bytes) is less than 24bytes)", length_count); col_add_fstr(pinfo->cinfo, COL_INFO, "Message Type: %s, Total Length: %u Bytes", val_to_str(message_type, message_type_vals, "Unknown messagetype 0x%x"), length_count); proto_tree_add_item( forces_main_header_tree, hf_forces_sid, tvb, offset+4, 4, ENC_BIG_ENDIAN); proto_tree_add_item( forces_main_header_tree, hf_forces_did, tvb, offset+8, 4, ENC_BIG_ENDIAN); proto_tree_add_item( forces_main_header_tree, hf_forces_correlator, tvb, offset+12, 8, ENC_BIG_ENDIAN); /*Add flags tree*/ ti = proto_tree_add_item(forces_main_header_tree, hf_forces_flags, tvb, offset+20, 4, ENC_BIG_ENDIAN); forces_flags_tree = proto_item_add_subtree(ti, ett_forces_flags); proto_tree_add_item(forces_flags_tree, hf_forces_flags_ack, tvb, offset+20, 4, ENC_BIG_ENDIAN); proto_tree_add_item(forces_flags_tree, hf_forces_flags_at, tvb, offset+20, 4, ENC_BIG_ENDIAN); proto_tree_add_item(forces_flags_tree, hf_forces_flags_em, tvb, offset+20, 4, ENC_BIG_ENDIAN); proto_tree_add_item(forces_flags_tree, hf_forces_flags_pri, tvb, offset+20, 4, ENC_BIG_ENDIAN); proto_tree_add_item(forces_flags_tree, hf_forces_flags_reserved, tvb, offset+20, 4, ENC_BIG_ENDIAN); proto_tree_add_item(forces_flags_tree, hf_forces_flags_rsrvd, tvb, offset+20, 4, ENC_BIG_ENDIAN); proto_tree_add_item(forces_flags_tree, hf_forces_flags_tp, tvb, offset+20, 4, ENC_BIG_ENDIAN); offset += 24; while (tvb_reported_length_remaining(tvb, offset) >= TLV_TL_LENGTH) { ti = proto_tree_add_text(forces_tree, tvb, offset, TLV_TL_LENGTH, "TLV"); forces_tlv_tree = proto_item_add_subtree(ti, ett_forces_tlv); tlv_type = tvb_get_ntohs(tvb, offset); tlv_item = proto_tree_add_item(forces_tlv_tree, hf_forces_tlv_type, tvb, offset, 2, ENC_BIG_ENDIAN); length_count = tvb_get_ntohs(tvb, offset+2) * 4; proto_item_set_len(ti, length_count); ti = proto_tree_add_uint_format_value(forces_tlv_tree, hf_forces_tlv_length, tvb, offset+2, 2, length_count, "%u Bytes", length_count); if (tvb_reported_length_remaining(tvb, offset) < length_count) expert_add_info_format(pinfo, ti, &ei_forces_tlv_length, "Bogus: Main TLV length (%u bytes) is wrong", length_count); if (length_count < TLV_TL_LENGTH) { expert_add_info_format(pinfo, ti, &ei_forces_tlv_length, "Bogus TLV length: %u", length_count); break; } offset += TLV_TL_LENGTH; length_count -= TLV_TL_LENGTH; switch(tlv_type) { case LFBselect_TLV: ti = proto_tree_add_text(forces_tlv_tree, tvb, offset, length_count, "LFB select TLV"); tlv_tree = proto_item_add_subtree(ti, ett_forces_lfbselect_tlv_type); dissect_lfbselecttlv(tvb, pinfo, tlv_tree, offset, length_count); break; case REDIRECT_TLV: ti = proto_tree_add_text(forces_tlv_tree, tvb, offset, length_count, "Redirect TLV"); tlv_tree = proto_item_add_subtree(ti, ett_forces_redirect_tlv_type); dissect_redirecttlv(tvb, pinfo, tlv_tree, offset); break; case ASResult_TLV: ti = proto_tree_add_text(forces_tlv_tree, tvb, offset, length_count, "ASResult TLV"); tlv_tree = proto_item_add_subtree(ti, ett_forces_asresult_tlv); proto_tree_add_item(tlv_tree, hf_forces_asresult_association_setup_result, tvb, offset, 4, ENC_BIG_ENDIAN); break; case ASTreason_TLV: ti = proto_tree_add_text(forces_tlv_tree, tvb, offset, length_count, "ASTreason TLV"); tlv_tree = proto_item_add_subtree(ti, ett_forces_astreason_tlv); proto_tree_add_item(tlv_tree, hf_forces_astreason_tlv_teardown_reason, tvb, offset, 4, ENC_BIG_ENDIAN); break; default: expert_add_info(pinfo, tlv_item, &ei_forces_tlv_type); ti = proto_tree_add_text(forces_tlv_tree, tvb, offset, length_count, "Unknown TLV"); tlv_tree = proto_item_add_subtree(ti, ett_forces_unknown_tlv); proto_tree_add_item(tlv_tree, hf_forces_unknown_tlv, tvb, offset, length_count, ENC_NA); break; } offset += length_count; } } /* Code to actually dissect the TCP packets */ static void dissect_forces_tcp(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree) { dissect_forces(tvb, pinfo, tree, TCP_UDP_TML_FOCES_MESSAGE_OFFSET_TCP); } /* Code to actually dissect the ForCES protocol layer packets,like UDP,SCTP and others */ static void dissect_forces_not_tcp(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree) { dissect_forces(tvb, pinfo, tree, 0); } void proto_reg_handoff_forces(void); void proto_register_forces(void) { module_t *forces_module; expert_module_t* expert_forces; /* Setup list of header fields See Section 1.6.1 for details*/ static hf_register_info hf[] = { { &hf_forces_version, { "Version", "forces.flags.version", FT_UINT8, BASE_DEC, NULL, 0xF0, NULL, HFILL } }, { &hf_forces_rsvd, { "Rsvd", "forces.flags.rsvd", FT_UINT8, BASE_DEC, NULL, 0x0F, NULL, HFILL } }, { &hf_forces_messagetype, { "Message Type", "forces.messagetype", FT_UINT8, BASE_DEC, NULL, 0x0, NULL, HFILL } }, { &hf_forces_length, { "Header Length", "forces.length", FT_UINT16, BASE_DEC, NULL, 0x0, NULL, HFILL } }, { &hf_forces_sid, { "Source ID", "forces.sid", FT_IPv4, BASE_NONE, NULL, 0x0, NULL, HFILL } }, { &hf_forces_did, { "Destination ID", "forces.did", FT_IPv4, BASE_NONE, NULL, 0x0, NULL, HFILL } }, { &hf_forces_correlator, { "Correlator", "forces.correlator", FT_UINT64, BASE_HEX, NULL, 0x0, NULL, HFILL } }, { &hf_forces_tlv_type, { "Type", "forces.tlv.type", FT_UINT16, BASE_DEC, NULL, 0x0, NULL, HFILL } }, { &hf_forces_tlv_length, { "Length", "forces.tlv.length", FT_UINT16, BASE_DEC, NULL, 0x0, NULL, HFILL } }, /*flags*/ { &hf_forces_flags, { "Flags", "forces.Flags", FT_UINT32, BASE_DEC, NULL, 0x0, NULL, HFILL } }, { &hf_forces_flags_ack, { "ACK indicator", "forces.flags.ack", FT_UINT32, BASE_DEC, VALS(main_header_flags_ack_vals), 0xC0000000, NULL, HFILL } }, { &hf_forces_flags_pri, { "Priority", "forces.flags.pri", FT_UINT32, BASE_DEC, NULL, 0x38000000, NULL, HFILL } }, { &hf_forces_flags_rsrvd, { "Rsrvd", "forces.Flags", FT_UINT32, BASE_DEC,NULL, 0x07000000, NULL, HFILL } }, { &hf_forces_flags_em, { "Execution mode", "forces.flags.em", FT_UINT32, BASE_DEC, VALS(main_header_flags_em_vals), 0x00C00000, NULL, HFILL } }, { &hf_forces_flags_at, { "Atomic Transaction", "forces.flags.at", FT_UINT32, BASE_DEC, VALS(main_header_flags_at_vals), 0x00200000, NULL, HFILL } }, { &hf_forces_flags_tp, { "Transaction phase", "forces.flags.tp", FT_UINT32, BASE_DEC, VALS(main_header_flags_tp_vals), 0x00180000, NULL, HFILL } }, { &hf_forces_flags_reserved, { "Reserved", "forces.flags.reserved", FT_UINT32, BASE_DEC,NULL, 0x0007ffff, NULL, HFILL } }, /*LFBSelectTLV*/ { &hf_forces_lfbselect_tlv_type_lfb_classid, { "Class ID", "forces.lfbselect.tlv.type.lfb.classid", FT_IPv4, BASE_NONE, NULL, 0x0, NULL, HFILL } }, { &hf_forces_lfbselect_tlv_type_lfb_instanceid, { "Instance ID", "forces.fbselect.tlv.type.lfb.instanceid", FT_IPv4, BASE_NONE, NULL, 0x0, NULL, HFILL } }, /*Operation TLV*/ { &hf_forces_lfbselect_tlv_type_operation_type, { "Type", "forces.lfbselect.tlv.type.operation.type", FT_UINT16, BASE_DEC, VALS(operation_type_vals), 0x0, NULL, HFILL } }, { &hf_forces_lfbselect_tlv_type_operation_length, { "Length", "forces.lfbselect.tlv.type.operation.length", FT_UINT16, BASE_DEC, NULL, 0x0, NULL, HFILL } }, { &hf_forces_lfbselect_tlv_type_operation_path_type, { "Type", "forces.lfbselect.tlv.type.operation.path.type", FT_UINT16, BASE_DEC, VALS(tlv_type_vals), 0x0, NULL, HFILL } }, { &hf_forces_lfbselect_tlv_type_operation_path_length, { "Length", "forces.lfbselect.tlv.type.operation.path.length", FT_UINT16, BASE_DEC, NULL, 0x0, NULL, HFILL } }, { &hf_forces_lfbselect_tlv_type_operation_path_data, { "Data", "forces.lfbselect.tlv.type.operation.path.data", FT_BYTES, BASE_NONE, NULL, 0x0, NULL, HFILL } }, { &hf_forces_lfbselect_tlv_type_operation_path_flags, {"Path Data Flags", "forces.lfbselect.tlv.type.operation.path.data.flags", FT_UINT16, BASE_HEX, NULL, 0x0, NULL, HFILL } }, { &hf_forces_lfbselect_tlv_type_operation_path_flags_selector, {"Selector", "forces.lfbselect.tlv.type.operation.path.data.flags.selector", FT_UINT16, BASE_HEX, NULL, 0x80, NULL, HFILL } }, { &hf_forces_lfbselect_tlv_type_operation_path_flags_reserved, {"Reserved", "forces.lfbselect.tlv.type.operation.path.data.flags.reserved", FT_UINT16, BASE_HEX, NULL, 0x7F, NULL, HFILL } }, { &hf_forces_lfbselect_tlv_type_operation_path_IDcount, { "Path Data IDcount", "forces.lfbselect.tlv.type.operation.path.data.IDcount", FT_UINT16, BASE_DEC, NULL, 0x0, NULL, HFILL } }, { &hf_forces_lfbselect_tlv_type_operation_path_IDs, { "Path Data IDs", "forces.lfbselect.tlv.type.operation.path.data.IDs", FT_UINT32, BASE_DEC, NULL, 0x0, NULL, HFILL } }, /*Meta data TLV*/ {&hf_forces_redirect_tlv_meta_data_tlv_type, { "Type", "forces.redirect.tlv.meta.data.tlv.type", FT_UINT16, BASE_DEC, NULL, 0x0, NULL, HFILL } }, { &hf_forces_redirect_tlv_meta_data_tlv_length, { "Length", "forces.redirect.tlv.meta.data.tlv.length", FT_UINT16, BASE_DEC, NULL, 0x0, NULL, HFILL } }, { &hf_forces_redirect_tlv_meta_data_tlv_meta_data_ilv, { "Meta Data ILV", "forces.redirect.tlv.meta.data.tlv.meta.data.ilv", FT_BYTES, BASE_NONE, NULL, 0x0, NULL, HFILL } }, { &hf_forces_redirect_tlv_meta_data_tlv_meta_data_ilv_id, { "ID", "forces.redirect.tlv.meta.data.tlv.meta.data.ilv.id", FT_UINT32, BASE_HEX_DEC, NULL, 0x0, NULL, HFILL } }, { &hf_forces_redirect_tlv_meta_data_tlv_meta_data_ilv_length, { "Length", "forces.redirect.tlv.meta.data.tlv.meta.data.ilv.length", FT_UINT32, BASE_DEC, NULL, 0x0, NULL, HFILL } }, { &hf_forces_redirect_tlv_redirect_data_tlv_type, { "Type", "forces.redirect.tlv.redirect.data.tlv.type", FT_UINT16, BASE_DEC, VALS(tlv_type_vals), 0x0, NULL, HFILL } }, { &hf_forces_redirect_tlv_redirect_data_tlv_length, { "Length", "forces.redirect.tlv.redirect.data.tlv.length", FT_UINT16, BASE_DEC, NULL, 0x0, NULL, HFILL } }, { &hf_forces_asresult_association_setup_result, { "Association Setup Result", "forces.teardown.reason", FT_UINT32, BASE_DEC, VALS(association_setup_result_at_vals), 0x0, NULL, HFILL } }, { &hf_forces_astreason_tlv_teardown_reason, { "AStreason TLV TearDonw Reason", "forces.astreason.tlv.teardonw.reason", FT_UINT32, BASE_DEC, VALS(teardown_reason_at_vals), 0x0, NULL, HFILL } }, { &hf_forces_unknown_tlv, { "Data", "forces.unknown.tlv", FT_BYTES, BASE_NONE, NULL, 0x0, NULL, HFILL } } }; /* Setup protocol subtree array */ static gint *ett[] = { &ett_forces, &ett_forces_main_header, &ett_forces_flags, &ett_forces_tlv, &ett_forces_lfbselect_tlv_type, &ett_forces_lfbselect_tlv_type_operation, &ett_forces_lfbselect_tlv_type_operation_path, &ett_forces_lfbselect_tlv_type_operation_path_data, &ett_forces_lfbselect_tlv_type_operation_path_data_path, &ett_forces_lfbselect_tlv_type_operation_path_selector, &ett_forces_path_data_tlv, &ett_forces_path_data_tlv_flags, &ett_forces_redirect_tlv_type, &ett_forces_redirect_tlv_meta_data_tlv, &ett_forces_redirect_tlv_redirect_data_tlv, &ett_forces_redirect_tlv_meta_data_tlv_meta_data_ilv, &ett_forces_asresult_tlv, &ett_forces_astreason_tlv, &ett_forces_unknown_tlv }; static ei_register_info ei[] = { { &ei_forces_length, { "forces.length.bad", PI_PROTOCOL, PI_WARN, "ForCES Header length is wrong", EXPFILL }}, { &ei_forces_tlv_type, { "forces.tlv.type.unknown", PI_PROTOCOL, PI_WARN, "Bogus: The Main_TLV type is unknown", EXPFILL }}, { &ei_forces_tlv_length, { "forces.tlv.length.bad", PI_PROTOCOL, PI_WARN, "Bogus TLV length", EXPFILL }}, { &ei_forces_lfbselect_tlv_type_operation_path_length, { "forces.lfbselect.tlv.type.operation.path.length.bad", PI_PROTOCOL, PI_WARN, "Bogus TLV length", EXPFILL }}, { &ei_forces_lfbselect_tlv_type_operation_type, { "forces.lfbselect.tlv.type.operation.type.unsupported", PI_PROTOCOL, PI_WARN, "ForCES Operation TLV is not supported", EXPFILL }}, { &ei_forces_redirect_tlv_redirect_data_tlv_length, { "forces.redirect.tlv.redirect.data.tlv.length.bad", PI_PROTOCOL, PI_WARN, "Redirect Data TLV length is wrong", EXPFILL }}, }; /* Register the protocol name and description */ proto_forces = proto_register_protocol("Forwarding and Control Element Separation Protocol", "ForCES", "forces"); /* Required function calls to register the header fields and subtrees used */ proto_register_field_array(proto_forces, hf, array_length(hf)); proto_register_subtree_array(ett, array_length(ett)); expert_forces = expert_register_protocol(proto_forces); expert_register_field_array(expert_forces, ei, array_length(ei)); forces_module = prefs_register_protocol(proto_forces,proto_reg_handoff_forces); prefs_register_uint_preference(forces_module, "tcp_alternate_port", "TCP port", "Decode packets on this TCP port as ForCES", 10, &forces_alternate_tcp_port); prefs_register_uint_preference(forces_module, "udp_alternate_port", "UDP port", "Decode packets on this UDP port as ForCES", 10, &forces_alternate_udp_port); prefs_register_uint_preference(forces_module, "sctp_high_prio_port", "SCTP High Priority channel port", "Decode packets on this sctp port as ForCES", 10, &forces_alternate_sctp_high_prio_channel_port); prefs_register_uint_preference(forces_module, "sctp_med_prio_port", "SCTP Meidium Priority channel port", "Decode packets on this sctp port as ForCES", 10, &forces_alternate_sctp_med_prio_channel_port); prefs_register_uint_preference(forces_module, "sctp_low_prio_port", "SCTP Low Priority channel port", "Decode packets on this sctp port as ForCES", 10, &forces_alternate_sctp_low_prio_channel_port); } void proto_reg_handoff_forces(void) { static gboolean inited = FALSE; static guint alternate_tcp_port = 0; /* 3000 */ static guint alternate_udp_port = 0; static guint alternate_sctp_high_prio_channel_port = 0; /* 6700 */ static guint alternate_sctp_med_prio_channel_port = 0; static guint alternate_sctp_low_prio_channel_port = 0; static dissector_handle_t forces_handle_tcp, forces_handle; if (!inited) { forces_handle_tcp = create_dissector_handle(dissect_forces_tcp, proto_forces); forces_handle = create_dissector_handle(dissect_forces_not_tcp, proto_forces); ip_handle = find_dissector("ip"); inited = TRUE; } /* Register TCP port for dissection */ if ((alternate_tcp_port != 0) && (alternate_tcp_port != forces_alternate_tcp_port)) dissector_delete_uint("tcp.port", alternate_tcp_port, forces_handle_tcp); if ((forces_alternate_tcp_port != 0) && (alternate_tcp_port != forces_alternate_tcp_port)) dissector_add_uint("tcp.port", forces_alternate_tcp_port, forces_handle_tcp); alternate_tcp_port = forces_alternate_tcp_port; /* Register UDP port for dissection */ if ((alternate_udp_port != 0) && (alternate_udp_port != forces_alternate_udp_port)) dissector_delete_uint("udp.port", alternate_udp_port, forces_handle); if ((forces_alternate_udp_port != 0) && (alternate_udp_port != forces_alternate_udp_port)) dissector_add_uint("udp.port", forces_alternate_udp_port, forces_handle); alternate_udp_port = forces_alternate_udp_port; /* Register SCTP port for high priority dissection */ if ((alternate_sctp_high_prio_channel_port != 0) && (alternate_sctp_high_prio_channel_port != forces_alternate_sctp_high_prio_channel_port)) dissector_delete_uint("sctp.port", alternate_sctp_high_prio_channel_port, forces_handle); if ((forces_alternate_sctp_high_prio_channel_port != 0) && (alternate_sctp_high_prio_channel_port != forces_alternate_sctp_high_prio_channel_port)) dissector_add_uint("sctp.port", forces_alternate_sctp_high_prio_channel_port, forces_handle); alternate_sctp_high_prio_channel_port = forces_alternate_sctp_high_prio_channel_port; /* Register SCTP port for medium priority dissection */ if ((alternate_sctp_med_prio_channel_port != 0) && (alternate_sctp_med_prio_channel_port != forces_alternate_sctp_med_prio_channel_port)) dissector_delete_uint("udp.port", alternate_sctp_med_prio_channel_port, forces_handle); if ((forces_alternate_sctp_med_prio_channel_port != 0) && (alternate_sctp_med_prio_channel_port != forces_alternate_sctp_med_prio_channel_port)) dissector_add_uint("udp.port", forces_alternate_sctp_med_prio_channel_port, forces_handle); alternate_sctp_med_prio_channel_port = forces_alternate_sctp_med_prio_channel_port; /* Register SCTP port for low priority dissection */ if ((alternate_sctp_low_prio_channel_port != 0) && (alternate_sctp_low_prio_channel_port != forces_alternate_sctp_low_prio_channel_port)) dissector_delete_uint("udp.port", alternate_sctp_low_prio_channel_port, forces_handle); if ((forces_alternate_sctp_low_prio_channel_port != 0) && (alternate_sctp_low_prio_channel_port != forces_alternate_sctp_low_prio_channel_port)) dissector_add_uint("udp.port", forces_alternate_sctp_low_prio_channel_port, forces_handle); alternate_sctp_low_prio_channel_port = forces_alternate_sctp_low_prio_channel_port; } /* * Editor modelines - http://www.wireshark.org/tools/modelines.html * * Local variables: * c-basic-offset: 4 * tab-width: 8 * indent-tabs-mode: nil * End: * * vi: set shiftwidth=4 tabstop=8 expandtab: * :indentSize=4:tabSize=8:noTabs=true: */
slowfranklin/wireshark
epan/dissectors/packet-forces.c
C
gpl-2.0
41,483
/* * This file is part of the coreboot project. * * Copyright 2014 Google Inc. * * 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; version 2 of the License. * * This program 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 this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <arch/io.h> #include <gpio.h> #include <reset.h> #include "board.h" void hard_reset(void) { gpio_output(GPIO_RESET, 1); while (1) ; }
acorn-marvell/coreboot
src/mainboard/google/veyron_rialto/reset.c
C
gpl-2.0
902
/* Duplicate handle for selection of locales. Copyright (C) 1997, 2000, 2001 Free Software Foundation, Inc. This file is part of the GNU C Library. Contributed by Ulrich Drepper <drepper@cygnus.com>, 1997. The GNU C 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. The GNU C 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 the GNU C Library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. */ #include <locale.h> #include <bits/libc-lock.h> #include <stdlib.h> #include <localeinfo.h> /* Lock for protecting global data. */ __libc_lock_define (extern , __libc_setlocale_lock) __locale_t __duplocale (__locale_t dataset) { __locale_t result; /* We modify global data. */ __libc_lock_lock (__libc_setlocale_lock); /* Get memory. */ result = (__locale_t) malloc (sizeof (struct __locale_struct)); if (result != NULL) { int cnt; for (cnt = 0; cnt < __LC_LAST; ++cnt) if (cnt != LC_ALL) { result->__locales[cnt] = dataset->__locales[cnt]; if (result->__locales[cnt]->usage_count < MAX_USAGE_COUNT) ++result->__locales[cnt]->usage_count; } } /* Update the special members. */ result->__ctype_b = dataset->__ctype_b; result->__ctype_tolower = dataset->__ctype_tolower; result->__ctype_toupper = dataset->__ctype_toupper; /* It's done. */ __libc_lock_unlock (__libc_setlocale_lock); return result; }
nslu2/glibc
locale/duplocale.c
C
gpl-2.0
1,954
/* packet-bpkmreq.c * Routines for Baseline Privacy Key Management Request dissection * Copyright 2002, Anand V. Narwani <anand[AT]narwani.org> * * $Id: packet-bpkmreq.c 45015 2012-09-20 01:29:52Z morriss $ * * Wireshark - Network traffic analyzer * By Gerald Combs <gerald@wireshark.org> * Copyright 1998 Gerald Combs * * 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. * * This program 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 this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "config.h" #include <epan/packet.h> /* Initialize the protocol and registered fields */ static int proto_docsis_bpkmreq = -1; static int hf_docsis_bpkmreq_code = -1; static int hf_docsis_bpkmreq_length = -1; static int hf_docsis_bpkmreq_ident = -1; static const value_string code_field_vals[] = { {0, "Reserved"}, {1, "Reserved"}, {2, "Reserved"}, {3, "Reserved"}, {4, "Auth Request"}, {5, "Auth Reply"}, {6, "Auth Reject"}, {7, "Key Request"}, {8, "Key Reply"}, {9, "Key Reject"}, {10, "Auth Invalid"}, {11, "TEK Invalid"}, {12, "Authent Info"}, {13, "Map Request"}, {14, "Map Reply"}, {15, "Map Reject"}, {0, NULL}, }; /* Initialize the subtree pointers */ static gint ett_docsis_bpkmreq = -1; static dissector_handle_t attrs_handle; /* Code to actually dissect the packets */ static void dissect_bpkmreq (tvbuff_t * tvb, packet_info * pinfo, proto_tree * tree) { proto_item *it; proto_tree *bpkmreq_tree; guint8 code; tvbuff_t *attrs_tvb; code = tvb_get_guint8 (tvb, 0); col_add_fstr (pinfo->cinfo, COL_INFO, "BPKM Request (%s)", val_to_str (code, code_field_vals, "%d")); if (tree) { it = proto_tree_add_protocol_format (tree, proto_docsis_bpkmreq, tvb, 0, -1, "BPKM Request Message"); bpkmreq_tree = proto_item_add_subtree (it, ett_docsis_bpkmreq); proto_tree_add_item (bpkmreq_tree, hf_docsis_bpkmreq_code, tvb, 0, 1, ENC_BIG_ENDIAN); proto_tree_add_item (bpkmreq_tree, hf_docsis_bpkmreq_ident, tvb, 1, 1, ENC_BIG_ENDIAN); proto_tree_add_item (bpkmreq_tree, hf_docsis_bpkmreq_length, tvb, 2, 2, ENC_BIG_ENDIAN); } /* Code to Call subdissector */ attrs_tvb = tvb_new_subset_remaining (tvb, 4); call_dissector (attrs_handle, attrs_tvb, pinfo, tree); } /* Register the protocol with Wireshark */ /* this format is require because a script is used to build the C function that calls all the protocol registration. */ void proto_register_docsis_bpkmreq (void) { /* Setup list of header fields See Section 1.6.1 for details*/ static hf_register_info hf[] = { {&hf_docsis_bpkmreq_code, {"BPKM Code", "docsis_bpkmreq.code", FT_UINT8, BASE_DEC, VALS (code_field_vals), 0x0, "BPKM Request Message", HFILL} }, {&hf_docsis_bpkmreq_ident, {"BPKM Identifier", "docsis_bpkmreq.ident", FT_UINT8, BASE_DEC, NULL, 0x0, NULL, HFILL} }, {&hf_docsis_bpkmreq_length, {"BPKM Length", "docsis_bpkmreq.length", FT_UINT16, BASE_DEC, NULL, 0x0, NULL, HFILL} }, }; /* Setup protocol subtree array */ static gint *ett[] = { &ett_docsis_bpkmreq, }; /* Register the protocol name and description */ proto_docsis_bpkmreq = proto_register_protocol ("DOCSIS Baseline Privacy Key Management Request", "DOCSIS BPKM-REQ", "docsis_bpkmreq"); /* Required function calls to register the header fields and subtrees used */ proto_register_field_array (proto_docsis_bpkmreq, hf, array_length (hf)); proto_register_subtree_array (ett, array_length (ett)); register_dissector ("docsis_bpkmreq", dissect_bpkmreq, proto_docsis_bpkmreq); } /* If this dissector uses sub-dissector registration add a registration routine. This format is required because a script is used to find these routines and create the code that calls these routines. */ void proto_reg_handoff_docsis_bpkmreq (void) { dissector_handle_t docsis_bpkmreq_handle; docsis_bpkmreq_handle = find_dissector ("docsis_bpkmreq"); attrs_handle = find_dissector ("docsis_bpkmattr"); dissector_add_uint ("docsis_mgmt", 0x0C, docsis_bpkmreq_handle); }
P1sec/LTE_monitor_c2xx
wireshark/plugins/docsis/packet-bpkmreq.c
C
gpl-2.0
4,716
/* hostlist_sctp.c 2008 Stig Bjorlykke * * Wireshark - Network traffic analyzer * By Gerald Combs <gerald@wireshark.org> * Copyright 1998 Gerald Combs * * 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. * * This program 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 this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "config.h" #include <string.h> #include <gtk/gtk.h> #include "epan/packet.h" #include <epan/stat_cmd_args.h> #include <epan/tap.h> #include <epan/dissectors/packet-sctp.h> #include "../stat_menu.h" #include "ui/gtk/gui_stat_menu.h" #include "ui/gtk/hostlist_table.h" void register_tap_listener_sctp_hostlist(void); static int sctp_hostlist_packet(void *pit, packet_info *pinfo, epan_dissect_t *edt _U_, const void *vip) { hostlist_table *hosts=(hostlist_table *)pit; const struct _sctp_info *sctphdr=(const struct _sctp_info *)vip; /* Take two "add" passes per packet, adding for each direction, ensures that all packets are counted properly (even if address is sending to itself) XXX - this could probably be done more efficiently inside hostlist_table */ add_hostlist_table_data(hosts, &sctphdr->ip_src, sctphdr->sport, TRUE, 1, pinfo->fd->pkt_len, SAT_NONE, PT_SCTP); add_hostlist_table_data(hosts, &sctphdr->ip_dst, sctphdr->dport, FALSE, 1, pinfo->fd->pkt_len, SAT_NONE, PT_SCTP); return 1; } static void gtk_sctp_hostlist_init(const char *opt_arg, void* userdata _U_) { const char *filter=NULL; if(!strncmp(opt_arg,"hosts,sctp,",11)){ filter=opt_arg+11; } else { filter=NULL; } init_hostlist_table(FALSE, "SCTP", "sctp", filter, sctp_hostlist_packet); } void gtk_sctp_hostlist_cb(GtkAction *action _U_, gpointer user_data _U_) { gtk_sctp_hostlist_init("hosts,sctp",NULL); } void register_tap_listener_sctp_hostlist(void) { register_stat_cmd_arg("hosts,sctp", gtk_sctp_hostlist_init,NULL); register_hostlist_table(FALSE, "SCTP", "sctp", NULL /*filter*/, sctp_hostlist_packet); }
morynicz/pyroshark
ui/gtk/hostlist_sctp.c
C
gpl-2.0
2,658
/* * Fence mechanism for dma-buf and to allow for asynchronous dma access * * Copyright (C) 2012 Canonical Ltd * Copyright (C) 2012 Texas Instruments * * Authors: * Rob Clark <robdclark@gmail.com> * Maarten Lankhorst <maarten.lankhorst@canonical.com> * * 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. * * This program 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. */ #include <linux/slab.h> #include <linux/export.h> #include <linux/atomic.h> #include <linux/fence.h> #define CREATE_TRACE_POINTS #include <trace/events/fence.h> EXPORT_TRACEPOINT_SYMBOL(fence_annotate_wait_on); EXPORT_TRACEPOINT_SYMBOL(fence_emit); /* * fence context counter: each execution context should have its own * fence context, this allows checking if fences belong to the same * context or not. One device can have multiple separate contexts, * and they're used if some engine can run independently of another. */ static atomic_t fence_context_counter = ATOMIC_INIT(0); /** * fence_context_alloc - allocate an array of fence contexts * @num: [in] amount of contexts to allocate * * This function will return the first index of the number of fences allocated. * The fence context is used for setting fence->context to a unique number. */ unsigned fence_context_alloc(unsigned num) { BUG_ON(!num); return atomic_add_return(num, &fence_context_counter) - num; } EXPORT_SYMBOL(fence_context_alloc); /** * fence_signal_locked - signal completion of a fence * @fence: the fence to signal * * Signal completion for software callbacks on a fence, this will unblock * fence_wait() calls and run all the callbacks added with * fence_add_callback(). Can be called multiple times, but since a fence * can only go from unsignaled to signaled state, it will only be effective * the first time. * * Unlike fence_signal, this function must be called with fence->lock held. */ int fence_signal_locked(struct fence *fence) { struct fence_cb *cur, *tmp; int ret = 0; if (WARN_ON(!fence)) return -EINVAL; if (!ktime_to_ns(fence->timestamp)) { fence->timestamp = ktime_get(); smp_mb(); } if (test_and_set_bit(FENCE_FLAG_SIGNALED_BIT, &fence->flags)) { ret = -EINVAL; /* * we might have raced with the unlocked fence_signal, * still run through all callbacks */ } else trace_fence_signaled(fence); list_for_each_entry_safe(cur, tmp, &fence->cb_list, node) { list_del_init(&cur->node); cur->func(fence, cur); } return ret; } EXPORT_SYMBOL(fence_signal_locked); /** * fence_signal - signal completion of a fence * @fence: the fence to signal * * Signal completion for software callbacks on a fence, this will unblock * fence_wait() calls and run all the callbacks added with * fence_add_callback(). Can be called multiple times, but since a fence * can only go from unsignaled to signaled state, it will only be effective * the first time. */ int fence_signal(struct fence *fence) { unsigned long flags; if (!fence) return -EINVAL; if (!ktime_to_ns(fence->timestamp)) { fence->timestamp = ktime_get(); smp_mb(); } if (test_and_set_bit(FENCE_FLAG_SIGNALED_BIT, &fence->flags)) return -EINVAL; trace_fence_signaled(fence); if (test_bit(FENCE_FLAG_ENABLE_SIGNAL_BIT, &fence->flags)) { struct fence_cb *cur, *tmp; spin_lock_irqsave(fence->lock, flags); list_for_each_entry_safe(cur, tmp, &fence->cb_list, node) { list_del_init(&cur->node); cur->func(fence, cur); } spin_unlock_irqrestore(fence->lock, flags); } return 0; } EXPORT_SYMBOL(fence_signal); /** * fence_wait_timeout - sleep until the fence gets signaled * or until timeout elapses * @fence: [in] the fence to wait on * @intr: [in] if true, do an interruptible wait * @timeout: [in] timeout value in jiffies, or MAX_SCHEDULE_TIMEOUT * * Returns -ERESTARTSYS if interrupted, 0 if the wait timed out, or the * remaining timeout in jiffies on success. Other error values may be * returned on custom implementations. * * Performs a synchronous wait on this fence. It is assumed the caller * directly or indirectly (buf-mgr between reservation and committing) * holds a reference to the fence, otherwise the fence might be * freed before return, resulting in undefined behavior. */ signed long fence_wait_timeout(struct fence *fence, bool intr, signed long timeout) { signed long ret; if (WARN_ON(timeout < 0)) return -EINVAL; trace_fence_wait_start(fence); ret = fence->ops->wait(fence, intr, timeout); trace_fence_wait_end(fence); return ret; } EXPORT_SYMBOL(fence_wait_timeout); void fence_release(struct kref *kref) { struct fence *fence = container_of(kref, struct fence, refcount); trace_fence_destroy(fence); BUG_ON(!list_empty(&fence->cb_list)); if (fence->ops->release) fence->ops->release(fence); else fence_free(fence); } EXPORT_SYMBOL(fence_release); void fence_free(struct fence *fence) { kfree_rcu(fence, rcu); } EXPORT_SYMBOL(fence_free); /** * fence_enable_sw_signaling - enable signaling on fence * @fence: [in] the fence to enable * * this will request for sw signaling to be enabled, to make the fence * complete as soon as possible */ void fence_enable_sw_signaling(struct fence *fence) { unsigned long flags; if (!test_and_set_bit(FENCE_FLAG_ENABLE_SIGNAL_BIT, &fence->flags) && !test_bit(FENCE_FLAG_SIGNALED_BIT, &fence->flags)) { trace_fence_enable_signal(fence); spin_lock_irqsave(fence->lock, flags); if (!fence->ops->enable_signaling(fence)) fence_signal_locked(fence); spin_unlock_irqrestore(fence->lock, flags); } } EXPORT_SYMBOL(fence_enable_sw_signaling); /** * fence_add_callback - add a callback to be called when the fence * is signaled * @fence: [in] the fence to wait on * @cb: [in] the callback to register * @func: [in] the function to call * * cb will be initialized by fence_add_callback, no initialization * by the caller is required. Any number of callbacks can be registered * to a fence, but a callback can only be registered to one fence at a time. * * Note that the callback can be called from an atomic context. If * fence is already signaled, this function will return -ENOENT (and * *not* call the callback) * * Add a software callback to the fence. Same restrictions apply to * refcount as it does to fence_wait, however the caller doesn't need to * keep a refcount to fence afterwards: when software access is enabled, * the creator of the fence is required to keep the fence alive until * after it signals with fence_signal. The callback itself can be called * from irq context. * */ int fence_add_callback(struct fence *fence, struct fence_cb *cb, fence_func_t func) { unsigned long flags; int ret = 0; bool was_set; if (WARN_ON(!fence || !func)) return -EINVAL; if (test_bit(FENCE_FLAG_SIGNALED_BIT, &fence->flags)) { INIT_LIST_HEAD(&cb->node); return -ENOENT; } spin_lock_irqsave(fence->lock, flags); was_set = test_and_set_bit(FENCE_FLAG_ENABLE_SIGNAL_BIT, &fence->flags); if (test_bit(FENCE_FLAG_SIGNALED_BIT, &fence->flags)) ret = -ENOENT; else if (!was_set) { trace_fence_enable_signal(fence); if (!fence->ops->enable_signaling(fence)) { fence_signal_locked(fence); ret = -ENOENT; } } if (!ret) { cb->func = func; list_add_tail(&cb->node, &fence->cb_list); } else INIT_LIST_HEAD(&cb->node); spin_unlock_irqrestore(fence->lock, flags); return ret; } EXPORT_SYMBOL(fence_add_callback); /** * fence_remove_callback - remove a callback from the signaling list * @fence: [in] the fence to wait on * @cb: [in] the callback to remove * * Remove a previously queued callback from the fence. This function returns * true if the callback is succesfully removed, or false if the fence has * already been signaled. * * *WARNING*: * Cancelling a callback should only be done if you really know what you're * doing, since deadlocks and race conditions could occur all too easily. For * this reason, it should only ever be done on hardware lockup recovery, * with a reference held to the fence. */ bool fence_remove_callback(struct fence *fence, struct fence_cb *cb) { unsigned long flags; bool ret; spin_lock_irqsave(fence->lock, flags); ret = !list_empty(&cb->node); if (ret) list_del_init(&cb->node); spin_unlock_irqrestore(fence->lock, flags); return ret; } EXPORT_SYMBOL(fence_remove_callback); struct default_wait_cb { struct fence_cb base; struct task_struct *task; }; static void fence_default_wait_cb(struct fence *fence, struct fence_cb *cb) { struct default_wait_cb *wait = container_of(cb, struct default_wait_cb, base); wake_up_state(wait->task, TASK_NORMAL); } /** * fence_default_wait - default sleep until the fence gets signaled * or until timeout elapses * @fence: [in] the fence to wait on * @intr: [in] if true, do an interruptible wait * @timeout: [in] timeout value in jiffies, or MAX_SCHEDULE_TIMEOUT * * Returns -ERESTARTSYS if interrupted, 0 if the wait timed out, or the * remaining timeout in jiffies on success. */ signed long fence_default_wait(struct fence *fence, bool intr, signed long timeout) { struct default_wait_cb cb; unsigned long flags; signed long ret = timeout; bool was_set; if (test_bit(FENCE_FLAG_SIGNALED_BIT, &fence->flags)) return timeout; spin_lock_irqsave(fence->lock, flags); if (intr && signal_pending(current)) { ret = -ERESTARTSYS; goto out; } was_set = test_and_set_bit(FENCE_FLAG_ENABLE_SIGNAL_BIT, &fence->flags); if (test_bit(FENCE_FLAG_SIGNALED_BIT, &fence->flags)) goto out; if (!was_set) { trace_fence_enable_signal(fence); if (!fence->ops->enable_signaling(fence)) { fence_signal_locked(fence); goto out; } } cb.base.func = fence_default_wait_cb; cb.task = current; list_add(&cb.base.node, &fence->cb_list); while (!test_bit(FENCE_FLAG_SIGNALED_BIT, &fence->flags) && ret > 0) { if (intr) __set_current_state(TASK_INTERRUPTIBLE); else __set_current_state(TASK_UNINTERRUPTIBLE); spin_unlock_irqrestore(fence->lock, flags); ret = schedule_timeout(ret); spin_lock_irqsave(fence->lock, flags); if (ret > 0 && intr && signal_pending(current)) ret = -ERESTARTSYS; } if (!list_empty(&cb.base.node)) list_del(&cb.base.node); __set_current_state(TASK_RUNNING); out: spin_unlock_irqrestore(fence->lock, flags); return ret; } EXPORT_SYMBOL(fence_default_wait); /** * fence_init - Initialize a custom fence. * @fence: [in] the fence to initialize * @ops: [in] the fence_ops for operations on this fence * @lock: [in] the irqsafe spinlock to use for locking this fence * @context: [in] the execution context this fence is run on * @seqno: [in] a linear increasing sequence number for this context * * Initializes an allocated fence, the caller doesn't have to keep its * refcount after committing with this fence, but it will need to hold a * refcount again if fence_ops.enable_signaling gets called. This can * be used for other implementing other types of fence. * * context and seqno are used for easy comparison between fences, allowing * to check which fence is later by simply using fence_later. */ void fence_init(struct fence *fence, const struct fence_ops *ops, spinlock_t *lock, unsigned context, unsigned seqno) { BUG_ON(!lock); BUG_ON(!ops || !ops->wait || !ops->enable_signaling || !ops->get_driver_name || !ops->get_timeline_name); kref_init(&fence->refcount); fence->ops = ops; INIT_LIST_HEAD(&fence->cb_list); fence->lock = lock; fence->context = context; fence->seqno = seqno; fence->flags = 0UL; trace_fence_init(fence); } EXPORT_SYMBOL(fence_init);
kofemann/linux-redpatch
drivers/base/fence.c
C
gpl-2.0
11,942
/* SPDX-License-Identifier: LGPL-2.1+ */ /*** This file is part of systemd. Copyright 2010 Lennart Poettering systemd 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. systemd 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 systemd; If not, see <http://www.gnu.org/licenses/>. ***/ #include "hostname-setup.h" #include "util.h" int main(int argc, char* argv[]) { int r; r = hostname_setup(); if (r < 0) log_error_errno(r, "hostname: %m"); return 0; }
Mic92/systemd
src/test/test-hostname.c
C
gpl-2.0
980
/* Copyright (C) 1991, 1993, 1995, 1996, 1997 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C 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. The GNU C 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 the GNU C Library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. */ #include <errno.h> #include <stdlib.h> /* Execute LINE as a shell command. */ int __libc_system (line) const char *line; { if (line == NULL) return 0; /* This indicates no command processor. */ __sys_errno (ENOSYS); return -1; } weak_alias (__libc_system, system) stub_warning (system) #include <stub-tag.h>
nslu2/glibc
sysdeps/generic/system.c
C
gpl-2.0
1,207
/* * Asterisk -- An open source telephony toolkit. * * Copyright (C) 2007-2008, Trinity College Computing Center * Written by David Chappell <David.Chappell@trincoll.edu> * * See http://www.asterisk.org for more information about * the Asterisk project. Please do not directly contact * any of the maintainers of this project for assistance; * the project provides a web site, mailing lists and IRC * channels for your use. * * This program is free software, distributed under the terms of * the GNU General Public License Version 2. See the LICENSE file * at the top of the source tree. */ /*! \file * * \brief Trivial application to read an extension into a variable * * \author David Chappell <David.Chappell@trincoll.edu> * * \ingroup applications */ /*** MODULEINFO <support_level>core</support_level> ***/ #include "asterisk.h" ASTERISK_REGISTER_FILE() #include "asterisk/file.h" #include "asterisk/pbx.h" #include "asterisk/app.h" #include "asterisk/module.h" #include "asterisk/indications.h" #include "asterisk/channel.h" /*** DOCUMENTATION <application name="ReadExten" language="en_US"> <synopsis> Read an extension into a variable. </synopsis> <syntax> <parameter name="variable" required="true" /> <parameter name="filename"> <para>File to play before reading digits or tone with option <literal>i</literal></para> </parameter> <parameter name="context"> <para>Context in which to match extensions.</para> </parameter> <parameter name="option"> <optionlist> <option name="s"> <para>Return immediately if the channel is not answered.</para> </option> <option name="i"> <para>Play <replaceable>filename</replaceable> as an indication tone from your <filename>indications.conf</filename> or a directly specified list of frequencies and durations.</para> </option> <option name="n"> <para>Read digits even if the channel is not answered.</para> </option> </optionlist> </parameter> <parameter name="timeout"> <para>An integer number of seconds to wait for a digit response. If greater than <literal>0</literal>, that value will override the default timeout.</para> </parameter> </syntax> <description> <para>Reads a <literal>#</literal> terminated string of digits from the user into the given variable.</para> <para>Will set READEXTENSTATUS on exit with one of the following statuses:</para> <variablelist> <variable name="READEXTENSTATUS"> <value name="OK"> A valid extension exists in ${variable}. </value> <value name="TIMEOUT"> No extension was entered in the specified time. Also sets ${variable} to "t". </value> <value name="INVALID"> An invalid extension, ${INVALID_EXTEN}, was entered. Also sets ${variable} to "i". </value> <value name="SKIP"> Line was not up and the option 's' was specified. </value> <value name="ERROR"> Invalid arguments were passed. </value> </variable> </variablelist> </description> </application> ***/ enum readexten_option_flags { OPT_SKIP = (1 << 0), OPT_INDICATION = (1 << 1), OPT_NOANSWER = (1 << 2), }; AST_APP_OPTIONS(readexten_app_options, { AST_APP_OPTION('s', OPT_SKIP), AST_APP_OPTION('i', OPT_INDICATION), AST_APP_OPTION('n', OPT_NOANSWER), }); static char *app = "ReadExten"; static int readexten_exec(struct ast_channel *chan, const char *data) { int res = 0; char exten[256] = ""; int maxdigits = sizeof(exten) - 1; int timeout = 0, digit_timeout = 0, x = 0; char *argcopy = NULL, *status = ""; struct ast_tone_zone_sound *ts = NULL; struct ast_flags flags = {0}; AST_DECLARE_APP_ARGS(arglist, AST_APP_ARG(variable); AST_APP_ARG(filename); AST_APP_ARG(context); AST_APP_ARG(options); AST_APP_ARG(timeout); ); if (ast_strlen_zero(data)) { ast_log(LOG_WARNING, "ReadExten requires at least one argument\n"); pbx_builtin_setvar_helper(chan, "READEXTENSTATUS", "ERROR"); return 0; } argcopy = ast_strdupa(data); AST_STANDARD_APP_ARGS(arglist, argcopy); if (ast_strlen_zero(arglist.variable)) { ast_log(LOG_WARNING, "Usage: ReadExten(variable[,filename[,context[,options[,timeout]]]])\n"); pbx_builtin_setvar_helper(chan, "READEXTENSTATUS", "ERROR"); return 0; } if (ast_strlen_zero(arglist.filename)) { arglist.filename = NULL; } if (ast_strlen_zero(arglist.context)) { arglist.context = ast_strdupa(ast_channel_context(chan)); } if (!ast_strlen_zero(arglist.options)) { ast_app_parse_options(readexten_app_options, &flags, NULL, arglist.options); } if (!ast_strlen_zero(arglist.timeout)) { timeout = atoi(arglist.timeout); if (timeout > 0) timeout *= 1000; } if (timeout <= 0) timeout = ast_channel_pbx(chan) ? ast_channel_pbx(chan)->rtimeoutms : 10000; if (digit_timeout <= 0) digit_timeout = ast_channel_pbx(chan) ? ast_channel_pbx(chan)->dtimeoutms : 5000; if (ast_test_flag(&flags, OPT_INDICATION) && !ast_strlen_zero(arglist.filename)) { ts = ast_get_indication_tone(ast_channel_zone(chan), arglist.filename); } do { if (ast_channel_state(chan) != AST_STATE_UP) { if (ast_test_flag(&flags, OPT_SKIP)) { /* At the user's option, skip if the line is not up */ pbx_builtin_setvar_helper(chan, arglist.variable, ""); status = "SKIP"; break; } else if (!ast_test_flag(&flags, OPT_NOANSWER)) { /* Otherwise answer unless we're supposed to read while on-hook */ res = ast_answer(chan); } } if (res < 0) { status = "HANGUP"; break; } ast_playtones_stop(chan); ast_stopstream(chan); if (ts && ts->data[0]) { res = ast_playtones_start(chan, 0, ts->data, 0); } else if (arglist.filename) { if (ast_test_flag(&flags, OPT_INDICATION) && ast_fileexists(arglist.filename, NULL, ast_channel_language(chan)) <= 0) { /* * We were asked to play an indication that did not exist in the config. * If no such file exists, play it as a tonelist. With any luck they won't * have a file named "350+440.ulaw" * (but honestly, who would do something so silly?) */ res = ast_playtones_start(chan, 0, arglist.filename, 0); } else { res = ast_streamfile(chan, arglist.filename, ast_channel_language(chan)); } } for (x = 0; x < maxdigits; x++) { ast_debug(3, "extension so far: '%s', timeout: %d\n", exten, timeout); res = ast_waitfordigit(chan, timeout); ast_playtones_stop(chan); ast_stopstream(chan); timeout = digit_timeout; if (res < 1) { /* timeout expired or hangup */ if (ast_check_hangup(chan)) { status = "HANGUP"; } else if (x == 0) { pbx_builtin_setvar_helper(chan, arglist.variable, "t"); status = "TIMEOUT"; } break; } exten[x] = res; if (!ast_matchmore_extension(chan, arglist.context, exten, 1 /* priority */, S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, NULL))) { if (!ast_exists_extension(chan, arglist.context, exten, 1, S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, NULL)) && res == '#') { exten[x] = '\0'; } break; } } if (!ast_strlen_zero(status)) break; if (ast_exists_extension(chan, arglist.context, exten, 1, S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, NULL))) { ast_debug(3, "User entered valid extension '%s'\n", exten); pbx_builtin_setvar_helper(chan, arglist.variable, exten); status = "OK"; } else { ast_debug(3, "User dialed invalid extension '%s' in context '%s' on %s\n", exten, arglist.context, ast_channel_name(chan)); pbx_builtin_setvar_helper(chan, arglist.variable, "i"); pbx_builtin_setvar_helper(chan, "INVALID_EXTEN", exten); status = "INVALID"; } } while (0); if (ts) { ts = ast_tone_zone_sound_unref(ts); } pbx_builtin_setvar_helper(chan, "READEXTENSTATUS", status); return status[0] == 'H' ? -1 : 0; } static int unload_module(void) { int res = ast_unregister_application(app); return res; } static int load_module(void) { int res = ast_register_application_xml(app, readexten_exec); return res; } AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "Read and evaluate extension validity");
leedm777/asterisk
apps/app_readexten.c
C
gpl-2.0
8,312
/* * arch/arm/mach-tegra/board-smba1002.c * * Copyright (C) 2011 Eduardo José Tagle <ejtagle@tutopia.com> * * This software is licensed under the terms of the GNU General Public * License version 2, as published by the Free Software Foundation, and * may be copied, distributed, and modified under those terms. * * This program 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. * */ #include <linux/console.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/version.h> #include <linux/platform_device.h> #include <linux/serial_8250.h> #include <linux/clk.h> #include <linux/mtd/mtd.h> #include <linux/mtd/partitions.h> #include <linux/dma-mapping.h> #include <linux/fsl_devices.h> #include <linux/platform_data/tegra_usb.h> #include <linux/pda_power.h> #include <linux/gpio.h> #include <linux/delay.h> #include <linux/reboot.h> #include <linux/i2c-tegra.h> #include <linux/memblock.h> #include <linux/antares_dock.h> #include <asm/mach-types.h> #include <asm/mach/arch.h> #include <asm/mach/time.h> #include <asm/setup.h> #include <mach/io.h> #include <mach/w1.h> #include <mach/iomap.h> #include <mach/irqs.h> #include <mach/nand.h> #include <mach/iomap.h> #include <mach/sdhci.h> #include <mach/gpio.h> #include <mach/clk.h> #include <mach/usb_phy.h> #include <mach/i2s.h> #include <mach/system.h> #include <linux/nvmap.h> #include "board.h" #include "board-smba1002.h" #include "clock.h" #include "gpio-names.h" #include "devices.h" #include "pm.h" #include "wakeups-t2.h" #include "wdt-recovery.h" #include <linux/rfkill-gpio.h> #define PMC_CTRL 0x0 #define PMC_CTRL_INTR_LOW (1 << 17) static struct rfkill_gpio_platform_data bluetooth_rfkill = { .name = "bluetooth_rfkill", .shutdown_gpio = -1, .reset_gpio = SMBA1002_BT_RESET, .type = RFKILL_TYPE_BLUETOOTH, }; static struct platform_device bluetooth_rfkill_device = { .name = "rfkill_gpio", .id = -1, .dev = { .platform_data = &bluetooth_rfkill, }, }; #ifdef CONFIG_BT_BLUEDROID extern void bluesleep_setup_uart_port(struct platform_device *uart_dev); #endif void __init smba_setup_bluesleep(void) { /*Add Clock Resource*/ clk_add_alias("bcm4329_32k_clk", bluetooth_rfkill_device.name, \ "blink", NULL); #ifdef CONFIG_BT_BLUEDROID bluesleep_setup_uart_port(&tegra_uartc_device); #endif return; } static struct resource smba_bluesleep_resources[] = { [0] = { .name = "gpio_host_wake", .start = SMBA1002_BT_IRQ, .end = SMBA1002_BT_IRQ, .flags = IORESOURCE_IO, }, [1] = { .name = "gpio_ext_wake", .start = SMBA1002_BT_WAKEUP, .end = SMBA1002_BT_WAKEUP, .flags = IORESOURCE_IO, }, [2] = { .name = "host_wake", .start = TEGRA_GPIO_TO_IRQ(SMBA1002_BT_IRQ), .end = TEGRA_GPIO_TO_IRQ(SMBA1002_BT_IRQ), .flags = IORESOURCE_IRQ | IORESOURCE_IRQ_LOWEDGE, }, }; static struct platform_device smba_bluesleep_device = { .name = "bluesleep", .id = -1, .num_resources = ARRAY_SIZE(smba_bluesleep_resources), .resource = smba_bluesleep_resources, }; static struct dock_platform_data dock_on_platform_data = { .irq = TEGRA_GPIO_TO_IRQ(SMBA1002_DOCK), .gpio_num = SMBA1002_DOCK, }; static struct platform_device tegra_dock_device = { .name = "tegra_dock", .id = -1, .dev = { .platform_data = &dock_on_platform_data, }, }; static struct platform_device *smba_devices[] __initdata = { &tegra_pmu_device, &tegra_gart_device, &tegra_aes_device, &bluetooth_rfkill_device, &smba_bluesleep_device, &tegra_wdt_device, &tegra_avp_device, &tegra_dock_device }; static void __init tegra_smba_init(void) { /* Initialize the pinmux */ smba_pinmux_init(); /* Initialize the clocks - clocks require the pinmux to be initialized first */ smba_clks_init(); platform_add_devices(smba_devices,ARRAY_SIZE(smba_devices)); /* Register i2c devices - required for Power management and MUST be done before the power register */ smba_i2c_register_devices(); /* Register the power subsystem - Including the poweroff handler - Required by all the others */ smba_charge_init(); smba_regulator_init(); /* Register the USB device */ smba_usb_register_devices(); /* Register UART devices */ smba_uart_register_devices(); /* Register RAM Console */ tegra_ram_console_debug_init(); /* Register GPU devices */ smba_panel_init(); /* Register Audio devices */ smba_audio_register_devices(); /* Register all the keyboard devices */ smba_keys_init(); /* Register touchscreen devices */ smba_touch_register_devices(); /* Register accelerometer device */ smba_sensors_register_devices(); /* Register Camera powermanagement devices */ smba_camera_register_devices(); /* Register NAND flash devices */ smba_nand_register_devices(); /* Register SDHCI devices */ smba_sdhci_init(); /* Register Bluetooth powermanagement devices */ smba_setup_bluesleep(); /* Release the tegra bootloader framebuffer */ tegra_release_bootloader_fb(); } static void __init tegra_smba_reserve(void) { if (memblock_reserve(0x0, 4096) < 0) pr_warn("Cannot reserve first 4K of memory for safety\n"); /* Reserve the graphics memory */ tegra_reserve(SMBA1002_GPU_MEM_SIZE, SMBA1002_FB1_MEM_SIZE, SMBA1002_FB2_MEM_SIZE); tegra_ram_console_debug_reserve(SZ_1M); } static void __init tegra_smba_fixup(struct machine_desc *desc, struct tag *tags, char **cmdline, struct meminfo *mi) { mi->nr_banks = SMBA1002_MEM_BANKS; mi->bank[0].start = PHYS_OFFSET; mi->bank[0].size = SMBA1002_MEM_SIZE - SMBA1002_TOTAL_GPU_MEM_SIZE; } MACHINE_START(HARMONY, "harmony") .boot_params = 0x00000100, .fixup = tegra_smba_fixup, .map_io = tegra_map_common_io, .reserve = tegra_smba_reserve, .init_early = tegra_init_early, .init_irq = tegra_init_irq, .timer = &tegra_timer, .init_machine = tegra_smba_init, MACHINE_END
fosser2/android-tegra-nv-3.1.10-rel-15r7
arch/arm/mach-tegra/board-smba1002.c
C
gpl-2.0
6,001