code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
/* * Copyright (C) 2011 Anton Burdinuk * clark15b@gmail.com * https://tsdemuxer.googlecode.com/svn/trunk/xupnpd */ #ifndef __SOAP_H #define __SOAP_H namespace soap { class string { protected: char* ptr; int size; public: string(void):ptr(0),size(0) {} ~string(void) { clear(); } void clear(void); int length(void) const { return size; } const char* c_str(void) const { return ptr?ptr:""; } void swap(string& s); void trim_right(void); friend class string_builder; friend class ctx; }; struct chunk { enum { max_size=64 }; char* ptr; int size; chunk* next; }; class string_builder { protected: chunk *beg,*end; int add_chunk(void); public: string_builder(void):beg(0),end(0) {} ~string_builder(void) { clear(); } void clear(void); void add(int ch) { if(!end || end->size>=chunk::max_size) if(add_chunk()) return; ((unsigned char*)end->ptr)[end->size++]=ch; } void add(const char* s,int len); void swap(string& s); }; struct node { node* parent; node* next; node* beg; node* end; char* name; char* data; int len; node(void):parent(0),next(0),beg(0),end(0),name(0),data(0),len(0) {} ~node(void) { clear(); } void init(void) { parent=next=beg=end=0; name=data=0; len=0; } node* add_node(void); void clear(void); node* find_child(const char* s,int l); node* find(const char* s); const char* operator[](const char* s) { return find_data(s); } const char* find_data(const char* s) { node* pp=find(s); if(pp && pp->data) return pp->data; return ""; } }; class ctx { protected: node* cur; short st; short st_close_tag; short st_quot; short st_text; short err; string_builder data; enum { max_tok_size=64 }; char tok[max_tok_size]; int tok_size; void tok_add(unsigned char ch) { if(tok_size<max_tok_size-1) ((unsigned char*)tok)[tok_size++]=ch; } void tok_reset(void) { tok_size=0; } void ch_push(unsigned char ch) { data.add(ch); } void tok_push(void); void tag_open(const char* s,int len); void tag_close(const char* s,int len); void data_push(void); public: int line; public: ctx(node* root):cur(root),st(0),err(0),line(0),tok_size(0),st_close_tag(0),st_quot(0),st_text(0) {} void begin(void); int parse(const char* buf,int len); int end(void); }; int parse(const char* s,int l,node* root); } #endif /* __SOAP_H */
Happy-Neko/xupnpd
src/soap.h
C
gpl-2.0
3,054
/* Copyright (c) 2012-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/kernel.h> #include <linux/init.h> #include <linux/module.h> #include <linux/kthread.h> #include <linux/mutex.h> #include <linux/msm_tsens.h> #include <linux/workqueue.h> #include <linux/completion.h> #include <linux/cpu.h> #include <linux/cpufreq.h> #include <linux/msm_tsens.h> #include <linux/msm_thermal.h> #include <linux/platform_device.h> #include <linux/of.h> #include <linux/err.h> #include <linux/slab.h> #include <linux/of.h> #include <linux/sysfs.h> #include <linux/types.h> #include <linux/android_alarm.h> #include <linux/thermal.h> #include <mach/rpm-regulator.h> #include <mach/rpm-regulator-smd.h> #include <linux/regulator/consumer.h> #include <linux/msm_thermal_ioctl.h> #define MAX_CURRENT_UA 1000000 #define MAX_RAILS 5 #define MAX_THRESHOLD 2 #ifdef CONFIG_PANTECH #define FEATURE_PANTECH_ECO_CPU_MODE #endif #if defined(FEATURE_PANTECH_ECO_CPU_MODE) static int ecocpu; #endif static struct msm_thermal_data msm_thermal_info; static struct delayed_work check_temp_work; static bool core_control_enabled; static uint32_t cpus_offlined; static DEFINE_MUTEX(core_control_mutex); static uint32_t wakeup_ms; static struct alarm thermal_rtc; static struct kobject *tt_kobj; static struct kobject *cc_kobj; static struct work_struct timer_work; static struct task_struct *hotplug_task; static struct task_struct *freq_mitigation_task; static struct completion hotplug_notify_complete; static struct completion freq_mitigation_complete; static int enabled; static int rails_cnt; static int psm_rails_cnt; static int ocr_rail_cnt; static int limit_idx; static int limit_idx_low; static int limit_idx_high; static int max_tsens_num; static struct cpufreq_frequency_table *table; static uint32_t usefreq; static int freq_table_get; static bool vdd_rstr_enabled; static bool vdd_rstr_nodes_called; static bool vdd_rstr_probed; static bool psm_enabled; static bool psm_nodes_called; static bool psm_probed; static bool hotplug_enabled; static bool freq_mitigation_enabled; static bool ocr_enabled; static bool ocr_nodes_called; static bool ocr_probed; static int *tsens_id_map; static DEFINE_MUTEX(vdd_rstr_mutex); static DEFINE_MUTEX(psm_mutex); static DEFINE_MUTEX(ocr_mutex); static uint32_t min_freq_limit; enum thermal_threshold { HOTPLUG_THRESHOLD_HIGH, HOTPLUG_THRESHOLD_LOW, FREQ_THRESHOLD_HIGH, FREQ_THRESHOLD_LOW, THRESHOLD_MAX_NR, }; struct cpu_info { uint32_t cpu; const char *sensor_type; uint32_t sensor_id; bool offline; bool user_offline; bool hotplug_thresh_clear; struct sensor_threshold threshold[THRESHOLD_MAX_NR]; bool max_freq; uint32_t user_max_freq; uint32_t user_min_freq; uint32_t limited_max_freq; uint32_t limited_min_freq; bool freq_thresh_clear; }; struct rail { const char *name; uint32_t freq_req; uint32_t min_level; uint32_t num_levels; int32_t curr_level; uint32_t levels[3]; struct kobj_attribute value_attr; struct kobj_attribute level_attr; struct regulator *reg; struct attribute_group attr_gp; }; struct psm_rail { const char *name; uint8_t init; uint8_t mode; struct kobj_attribute mode_attr; struct rpm_regulator *reg; struct regulator *phase_reg; struct attribute_group attr_gp; }; static struct psm_rail *psm_rails; static struct psm_rail *ocr_rails; static struct rail *rails; static struct cpu_info cpus[NR_CPUS]; struct vdd_rstr_enable { struct kobj_attribute ko_attr; uint32_t enabled; }; /* For SMPS only*/ enum PMIC_SW_MODE { PMIC_AUTO_MODE = RPM_REGULATOR_MODE_AUTO, PMIC_IPEAK_MODE = RPM_REGULATOR_MODE_IPEAK, PMIC_PWM_MODE = RPM_REGULATOR_MODE_HPM, }; enum ocr_request { OPTIMUM_CURRENT_MIN, OPTIMUM_CURRENT_MAX, OPTIMUM_CURRENT_NR, }; #define VDD_RES_RO_ATTRIB(_rail, ko_attr, j, _name) \ ko_attr.attr.name = __stringify(_name); \ ko_attr.attr.mode = 444; \ ko_attr.show = vdd_rstr_reg_##_name##_show; \ ko_attr.store = NULL; \ sysfs_attr_init(&ko_attr.attr); \ _rail.attr_gp.attrs[j] = &ko_attr.attr; #define VDD_RES_RW_ATTRIB(_rail, ko_attr, j, _name) \ ko_attr.attr.name = __stringify(_name); \ ko_attr.attr.mode = 644; \ ko_attr.show = vdd_rstr_reg_##_name##_show; \ ko_attr.store = vdd_rstr_reg_##_name##_store; \ sysfs_attr_init(&ko_attr.attr); \ _rail.attr_gp.attrs[j] = &ko_attr.attr; #define VDD_RSTR_ENABLE_FROM_ATTRIBS(attr) \ (container_of(attr, struct vdd_rstr_enable, ko_attr)); #define VDD_RSTR_REG_VALUE_FROM_ATTRIBS(attr) \ (container_of(attr, struct rail, value_attr)); #define VDD_RSTR_REG_LEVEL_FROM_ATTRIBS(attr) \ (container_of(attr, struct rail, level_attr)); #define OCR_RW_ATTRIB(_rail, ko_attr, j, _name) \ ko_attr.attr.name = __stringify(_name); \ ko_attr.attr.mode = 644; \ ko_attr.show = ocr_reg_##_name##_show; \ ko_attr.store = ocr_reg_##_name##_store; \ sysfs_attr_init(&ko_attr.attr); \ _rail.attr_gp.attrs[j] = &ko_attr.attr; #define PSM_RW_ATTRIB(_rail, ko_attr, j, _name) \ ko_attr.attr.name = __stringify(_name); \ ko_attr.attr.mode = 644; \ ko_attr.show = psm_reg_##_name##_show; \ ko_attr.store = psm_reg_##_name##_store; \ sysfs_attr_init(&ko_attr.attr); \ _rail.attr_gp.attrs[j] = &ko_attr.attr; #define PSM_REG_MODE_FROM_ATTRIBS(attr) \ (container_of(attr, struct psm_rail, mode_attr)); static int msm_thermal_cpufreq_callback(struct notifier_block *nfb, unsigned long event, void *data) { struct cpufreq_policy *policy = data; uint32_t max_freq_req = cpus[policy->cpu].limited_max_freq; uint32_t min_freq_req = cpus[policy->cpu].limited_min_freq; switch (event) { case CPUFREQ_INCOMPATIBLE: pr_debug("%s: mitigating cpu %d to freq max: %u min: %u\n", KBUILD_MODNAME, policy->cpu, max_freq_req, min_freq_req); cpufreq_verify_within_limits(policy, min_freq_req, max_freq_req); if (max_freq_req < min_freq_req) pr_err("Invalid frequency request Max:%u Min:%u\n", max_freq_req, min_freq_req); break; } return NOTIFY_OK; } static struct notifier_block msm_thermal_cpufreq_notifier = { .notifier_call = msm_thermal_cpufreq_callback, }; /* If freq table exists, then we can send freq request */ static int check_freq_table(void) { int ret = 0; struct cpufreq_frequency_table *table = NULL; table = cpufreq_frequency_get_table(0); if (!table) { pr_debug("%s: error reading cpufreq table\n", __func__); return -EINVAL; } freq_table_get = 1; return ret; } static void update_cpu_freq(int cpu) { if (cpu_online(cpu)) { if (cpufreq_update_policy(cpu)) pr_err("Unable to update policy for cpu:%d\n", cpu); } } static int update_cpu_min_freq_all(uint32_t min) { uint32_t cpu = 0; int ret = 0; if (!freq_table_get) { ret = check_freq_table(); if (ret) { pr_err("%s:Fail to get freq table\n", KBUILD_MODNAME); return ret; } } /* If min is larger than allowed max */ min = min(min, table[limit_idx_high].frequency); if (freq_mitigation_task) { min_freq_limit = min; complete(&freq_mitigation_complete); } else { get_online_cpus(); for_each_possible_cpu(cpu) { cpus[cpu].limited_min_freq = min; update_cpu_freq(cpu); } put_online_cpus(); } return ret; } static int vdd_restriction_apply_freq(struct rail *r, int level) { int ret = 0; if (level == r->curr_level) return ret; /* level = -1: disable, level = 0,1,2..n: enable */ if (level == -1) { ret = update_cpu_min_freq_all(r->min_level); if (ret) return ret; else r->curr_level = -1; } else if (level >= 0 && level < (r->num_levels)) { ret = update_cpu_min_freq_all(r->levels[level]); if (ret) return ret; else r->curr_level = level; } else { pr_err("level input:%d is not within range\n", level); return -EINVAL; } return ret; } static int vdd_restriction_apply_voltage(struct rail *r, int level) { int ret = 0; if (r->reg == NULL) { pr_info("Do not have regulator handle:%s, can't apply vdd\n", r->name); return -EFAULT; } if (level == r->curr_level) return ret; /* level = -1: disable, level = 0,1,2..n: enable */ if (level == -1) { ret = regulator_set_voltage(r->reg, r->min_level, r->levels[r->num_levels - 1]); if (!ret) r->curr_level = -1; } else if (level >= 0 && level < (r->num_levels)) { ret = regulator_set_voltage(r->reg, r->levels[level], r->levels[r->num_levels - 1]); if (!ret) r->curr_level = level; } else { pr_err("level input:%d is not within range\n", level); return -EINVAL; } return ret; } /* Setting all rails the same mode */ static int psm_set_mode_all(int mode) { int i = 0; int fail_cnt = 0; int ret = 0; for (i = 0; i < psm_rails_cnt; i++) { if (psm_rails[i].mode != mode) { ret = rpm_regulator_set_mode(psm_rails[i].reg, mode); if (ret) { pr_err("Cannot set mode:%d for %s", mode, psm_rails[i].name); fail_cnt++; } else psm_rails[i].mode = mode; } } return fail_cnt ? (-EFAULT) : ret; } static int vdd_rstr_en_show( struct kobject *kobj, struct kobj_attribute *attr, char *buf) { struct vdd_rstr_enable *en = VDD_RSTR_ENABLE_FROM_ATTRIBS(attr); return snprintf(buf, PAGE_SIZE, "%d\n", en->enabled); } static ssize_t vdd_rstr_en_store(struct kobject *kobj, struct kobj_attribute *attr, const char *buf, size_t count) { int ret = 0; int i = 0; uint8_t en_cnt = 0; uint8_t dis_cnt = 0; uint32_t val = 0; struct kernel_param kp; struct vdd_rstr_enable *en = VDD_RSTR_ENABLE_FROM_ATTRIBS(attr); mutex_lock(&vdd_rstr_mutex); kp.arg = &val; ret = param_set_bool(buf, &kp); if (ret) { pr_err("Invalid input %s for enabled\n", buf); goto done_vdd_rstr_en; } if ((val == 0) && (en->enabled == 0)) goto done_vdd_rstr_en; for (i = 0; i < rails_cnt; i++) { if (rails[i].freq_req == 1 && freq_table_get) ret = vdd_restriction_apply_freq(&rails[i], (val) ? 0 : -1); else ret = vdd_restriction_apply_voltage(&rails[i], (val) ? 0 : -1); /* * Even if fail to set one rail, still try to set the * others. Continue the loop */ if (ret) pr_err("Set vdd restriction for %s failed\n", rails[i].name); else { if (val) en_cnt++; else dis_cnt++; } } /* As long as one rail is enabled, vdd rstr is enabled */ if (val && en_cnt) en->enabled = 1; else if (!val && (dis_cnt == rails_cnt)) en->enabled = 0; done_vdd_rstr_en: mutex_unlock(&vdd_rstr_mutex); return count; } static struct vdd_rstr_enable vdd_rstr_en = { .ko_attr.attr.name = __stringify(enabled), .ko_attr.attr.mode = 644, .ko_attr.show = vdd_rstr_en_show, .ko_attr.store = vdd_rstr_en_store, .enabled = 1, }; static struct attribute *vdd_rstr_en_attribs[] = { &vdd_rstr_en.ko_attr.attr, NULL, }; static struct attribute_group vdd_rstr_en_attribs_gp = { .attrs = vdd_rstr_en_attribs, }; static int vdd_rstr_reg_value_show( struct kobject *kobj, struct kobj_attribute *attr, char *buf) { int val = 0; struct rail *reg = VDD_RSTR_REG_VALUE_FROM_ATTRIBS(attr); /* -1:disabled, -2:fail to get regualtor handle */ if (reg->curr_level < 0) val = reg->curr_level; else val = reg->levels[reg->curr_level]; return snprintf(buf, PAGE_SIZE, "%d\n", val); } static int vdd_rstr_reg_level_show( struct kobject *kobj, struct kobj_attribute *attr, char *buf) { struct rail *reg = VDD_RSTR_REG_LEVEL_FROM_ATTRIBS(attr); return snprintf(buf, PAGE_SIZE, "%d\n", reg->curr_level); } static ssize_t vdd_rstr_reg_level_store(struct kobject *kobj, struct kobj_attribute *attr, const char *buf, size_t count) { int ret = 0; int val = 0; struct rail *reg = VDD_RSTR_REG_LEVEL_FROM_ATTRIBS(attr); mutex_lock(&vdd_rstr_mutex); if (vdd_rstr_en.enabled == 0) goto done_store_level; ret = kstrtouint(buf, 10, &val); if (ret) { pr_err("Invalid input %s for level\n", buf); goto done_store_level; } if (val < 0 || val > reg->num_levels - 1) { pr_err(" Invalid number %d for level\n", val); goto done_store_level; } if (val != reg->curr_level) { if (reg->freq_req == 1 && freq_table_get) update_cpu_min_freq_all(reg->levels[val]); else { ret = vdd_restriction_apply_voltage(reg, val); if (ret) { pr_err( \ "Set vdd restriction for regulator %s failed\n", reg->name); goto done_store_level; } } reg->curr_level = val; } done_store_level: mutex_unlock(&vdd_rstr_mutex); return count; } static int request_optimum_current(struct psm_rail *rail, enum ocr_request req) { int ret = 0; if ((!rail) || (req >= OPTIMUM_CURRENT_NR) || (req < 0)) { pr_err("%s:%s Invalid input\n", KBUILD_MODNAME, __func__); ret = -EINVAL; goto request_ocr_exit; } ret = regulator_set_optimum_mode(rail->phase_reg, (req == OPTIMUM_CURRENT_MAX) ? MAX_CURRENT_UA : 0); if (ret < 0) { pr_err("%s: Optimum current request failed\n", KBUILD_MODNAME); goto request_ocr_exit; } ret = 0; /*regulator_set_optimum_mode returns the mode on success*/ pr_debug("%s: Requested optimum current mode: %d\n", KBUILD_MODNAME, req); request_ocr_exit: return ret; } static int ocr_set_mode_all(enum ocr_request req) { int ret = 0, i; for (i = 0; i < ocr_rail_cnt; i++) { if (ocr_rails[i].mode == req) continue; ret = request_optimum_current(&ocr_rails[i], req); if (ret) goto ocr_set_mode_exit; ocr_rails[i].mode = req; } ocr_set_mode_exit: return ret; } static int ocr_reg_mode_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf) { struct psm_rail *reg = PSM_REG_MODE_FROM_ATTRIBS(attr); return snprintf(buf, PAGE_SIZE, "%d\n", reg->mode); } static ssize_t ocr_reg_mode_store(struct kobject *kobj, struct kobj_attribute *attr, const char *buf, size_t count) { int ret = 0; int val = 0; struct psm_rail *reg = PSM_REG_MODE_FROM_ATTRIBS(attr); if (!ocr_enabled) return count; mutex_lock(&ocr_mutex); ret = kstrtoint(buf, 10, &val); if (ret) { pr_err("%s: Invalid input %s for mode\n", KBUILD_MODNAME, buf); goto done_ocr_store; } if ((val != OPTIMUM_CURRENT_MAX) && (val != OPTIMUM_CURRENT_MIN)) { pr_err("%s: Invalid value %d for mode\n", KBUILD_MODNAME, val); goto done_ocr_store; } if (val != reg->mode) { ret = request_optimum_current(reg, val); if (ret) goto done_ocr_store; reg->mode = val; } done_ocr_store: mutex_unlock(&ocr_mutex); return count; } static int psm_reg_mode_show( struct kobject *kobj, struct kobj_attribute *attr, char *buf) { struct psm_rail *reg = PSM_REG_MODE_FROM_ATTRIBS(attr); return snprintf(buf, PAGE_SIZE, "%d\n", reg->mode); } static ssize_t psm_reg_mode_store(struct kobject *kobj, struct kobj_attribute *attr, const char *buf, size_t count) { int ret = 0; int val = 0; struct psm_rail *reg = PSM_REG_MODE_FROM_ATTRIBS(attr); mutex_lock(&psm_mutex); ret = kstrtoint(buf, 10, &val); if (ret) { pr_err("Invalid input %s for mode\n", buf); goto done_psm_store; } if ((val != PMIC_PWM_MODE) && (val != PMIC_AUTO_MODE)) { pr_err(" Invalid number %d for mode\n", val); goto done_psm_store; } if (val != reg->mode) { ret = rpm_regulator_set_mode(reg->reg, val); if (ret) { pr_err( \ "Fail to set PMIC SW Mode:%d for %s\n", val, reg->name); goto done_psm_store; } reg->mode = val; } done_psm_store: mutex_unlock(&psm_mutex); return count; } static int check_sensor_id(int sensor_id) { int i = 0; bool hw_id_found; int ret = 0; for (i = 0; i < max_tsens_num; i++) { if (sensor_id == tsens_id_map[i]) { hw_id_found = true; break; } } if (!hw_id_found) { pr_err("%s: Invalid sensor hw id :%d\n", __func__, sensor_id); return -EINVAL; } return ret; } static int create_sensor_id_map(void) { int i = 0; int ret = 0; tsens_id_map = kzalloc(sizeof(int) * max_tsens_num, GFP_KERNEL); if (!tsens_id_map) { pr_err("%s: Cannot allocate memory for tsens_id_map\n", __func__); return -ENOMEM; } for (i = 0; i < max_tsens_num; i++) { ret = tsens_get_hw_id_mapping(i, &tsens_id_map[i]); /* If return -ENXIO, hw_id is default in sequence */ if (ret) { if (ret == -ENXIO) { tsens_id_map[i] = i; ret = 0; } else { pr_err( \ "%s: Failed to get hw id for sw id %d\n", __func__, i); goto fail; } } } return ret; fail: kfree(tsens_id_map); return ret; } /* 1:enable, 0:disable */ static int vdd_restriction_apply_all(int en) { int i = 0; int en_cnt = 0; int dis_cnt = 0; int fail_cnt = 0; int ret = 0; for (i = 0; i < rails_cnt; i++) { if (rails[i].freq_req == 1 && freq_table_get) ret = vdd_restriction_apply_freq(&rails[i], en ? 0 : -1); else ret = vdd_restriction_apply_voltage(&rails[i], en ? 0 : -1); if (ret) { pr_err("Cannot set voltage for %s", rails[i].name); fail_cnt++; } else { if (en) en_cnt++; else dis_cnt++; } } /* As long as one rail is enabled, vdd rstr is enabled */ if (en && en_cnt) vdd_rstr_en.enabled = 1; else if (!en && (dis_cnt == rails_cnt)) vdd_rstr_en.enabled = 0; /* * Check fail_cnt again to make sure all of the rails are applied * restriction successfully or not */ if (fail_cnt) return -EFAULT; return ret; } static int msm_thermal_get_freq_table(void) { int ret = 0; int i = 0; table = cpufreq_frequency_get_table(0); if (table == NULL) { pr_debug("%s: error reading cpufreq table\n", KBUILD_MODNAME); ret = -EINVAL; goto fail; } while (table[i].frequency != CPUFREQ_TABLE_END) i++; limit_idx_low = 0; limit_idx_high = limit_idx = i - 1; BUG_ON(limit_idx_high <= 0 || limit_idx_high <= limit_idx_low); fail: return ret; } static int set_and_activate_threshold(uint32_t sensor_id, struct sensor_threshold *threshold) { int ret = 0; ret = sensor_set_trip(sensor_id, threshold); if (ret != 0) { pr_err("%s: Error in setting trip %d\n", KBUILD_MODNAME, threshold->trip); goto set_done; } ret = sensor_activate_trip(sensor_id, threshold, true); if (ret != 0) { pr_err("%s: Error in enabling trip %d\n", KBUILD_MODNAME, threshold->trip); goto set_done; } set_done: return ret; } static int set_threshold(uint32_t sensor_id, struct sensor_threshold *threshold) { struct tsens_device tsens_dev; int i = 0, ret = 0; long temp; if ((!threshold) || check_sensor_id(sensor_id)) { pr_err("%s: Invalid input\n", KBUILD_MODNAME); ret = -EINVAL; goto set_threshold_exit; } tsens_dev.sensor_num = sensor_id; ret = tsens_get_temp(&tsens_dev, &temp); if (ret) { pr_err("%s: Unable to read TSENS sensor %d\n", KBUILD_MODNAME, tsens_dev.sensor_num); goto set_threshold_exit; } while (i < MAX_THRESHOLD) { switch (threshold[i].trip) { case THERMAL_TRIP_CONFIGURABLE_HI: if (threshold[i].temp >= temp) { ret = set_and_activate_threshold(sensor_id, &threshold[i]); if (ret) goto set_threshold_exit; } break; case THERMAL_TRIP_CONFIGURABLE_LOW: if (threshold[i].temp <= temp) { ret = set_and_activate_threshold(sensor_id, &threshold[i]); if (ret) goto set_threshold_exit; } break; default: break; } i++; } set_threshold_exit: return ret; } #ifdef CONFIG_SMP static void __ref do_core_control(long temp) { int i = 0; int ret = 0; if (!core_control_enabled) return; mutex_lock(&core_control_mutex); if (msm_thermal_info.core_control_mask && temp >= msm_thermal_info.core_limit_temp_degC) { for (i = num_possible_cpus(); i > 0; i--) { if (!(msm_thermal_info.core_control_mask & BIT(i))) continue; if (cpus_offlined & BIT(i) && !cpu_online(i)) continue; pr_info("%s: Set Offline: CPU%d Temp: %ld\n", KBUILD_MODNAME, i, temp); ret = cpu_down(i); if (ret) pr_err("%s: Error %d offline core %d\n", KBUILD_MODNAME, ret, i); cpus_offlined |= BIT(i); break; } } else if (msm_thermal_info.core_control_mask && cpus_offlined && temp <= (msm_thermal_info.core_limit_temp_degC - msm_thermal_info.core_temp_hysteresis_degC)) { for (i = 0; i < num_possible_cpus(); i++) { if (!(cpus_offlined & BIT(i))) continue; cpus_offlined &= ~BIT(i); pr_info("%s: Allow Online CPU%d Temp: %ld\n", KBUILD_MODNAME, i, temp); /* * If this core is already online, then bring up the * next offlined core. */ if (cpu_online(i)) continue; ret = cpu_up(i); if (ret) pr_err("%s: Error %d online core %d\n", KBUILD_MODNAME, ret, i); break; } } mutex_unlock(&core_control_mutex); } /* Call with core_control_mutex locked */ static int __ref update_offline_cores(int val) { uint32_t cpu = 0; int ret = 0; if (!core_control_enabled) return 0; cpus_offlined = msm_thermal_info.core_control_mask & val; for_each_possible_cpu(cpu) { if (!(cpus_offlined & BIT(cpu))) continue; if (!cpu_online(cpu)) continue; ret = cpu_down(cpu); if (ret) pr_err("%s: Unable to offline cpu%d\n", KBUILD_MODNAME, cpu); } return ret; } static __ref int do_hotplug(void *data) { int ret = 0; uint32_t cpu = 0, mask = 0; if (!core_control_enabled) return -EINVAL; while (!kthread_should_stop()) { wait_for_completion(&hotplug_notify_complete); INIT_COMPLETION(hotplug_notify_complete); mask = 0; mutex_lock(&core_control_mutex); for_each_possible_cpu(cpu) { if (hotplug_enabled && cpus[cpu].hotplug_thresh_clear) { set_threshold(cpus[cpu].sensor_id, &cpus[cpu].threshold[HOTPLUG_THRESHOLD_HIGH]); cpus[cpu].hotplug_thresh_clear = false; } if (cpus[cpu].offline || cpus[cpu].user_offline) mask |= BIT(cpu); } if (mask != cpus_offlined) update_offline_cores(mask); mutex_unlock(&core_control_mutex); sysfs_notify(cc_kobj, NULL, "cpus_offlined"); } return ret; } #else static void do_core_control(long temp) { return; } static __ref int do_hotplug(void *data) { return 0; } #endif static int do_ocr(void) { struct tsens_device tsens_dev; long temp = 0; int ret = 0; int i = 0, j = 0; int auto_cnt = 0; if (!ocr_enabled) return ret; mutex_lock(&ocr_mutex); for (i = 0; i < max_tsens_num; i++) { tsens_dev.sensor_num = tsens_id_map[i]; ret = tsens_get_temp(&tsens_dev, &temp); if (ret) { pr_debug("%s: Unable to read TSENS sensor %d\n", __func__, tsens_dev.sensor_num); auto_cnt++; continue; } if (temp > msm_thermal_info.ocr_temp_degC) { if (ocr_rails[0].init != OPTIMUM_CURRENT_NR) for (j = 0; j < ocr_rail_cnt; j++) ocr_rails[j].init = OPTIMUM_CURRENT_NR; ret = ocr_set_mode_all(OPTIMUM_CURRENT_MAX); if (ret) pr_err("Error setting max optimum current\n"); goto do_ocr_exit; } else if (temp <= (msm_thermal_info.ocr_temp_degC - msm_thermal_info.ocr_temp_hyst_degC)) auto_cnt++; } if (auto_cnt == max_tsens_num || ocr_rails[0].init != OPTIMUM_CURRENT_NR) { /* 'init' not equal to OPTIMUM_CURRENT_NR means this is the ** first polling iteration after device probe. During first ** iteration, if temperature is less than the set point, clear ** the max current request made and reset the 'init'. */ if (ocr_rails[0].init != OPTIMUM_CURRENT_NR) for (j = 0; j < ocr_rail_cnt; j++) ocr_rails[j].init = OPTIMUM_CURRENT_NR; ret = ocr_set_mode_all(OPTIMUM_CURRENT_MIN); if (ret) { pr_err("Error setting min optimum current\n"); goto do_ocr_exit; } } do_ocr_exit: mutex_unlock(&ocr_mutex); return ret; } static int do_vdd_restriction(void) { struct tsens_device tsens_dev; long temp = 0; int ret = 0; int i = 0; int dis_cnt = 0; if (!vdd_rstr_enabled) return ret; if (usefreq && !freq_table_get) { if (check_freq_table()) return ret; } mutex_lock(&vdd_rstr_mutex); for (i = 0; i < max_tsens_num; i++) { tsens_dev.sensor_num = tsens_id_map[i]; ret = tsens_get_temp(&tsens_dev, &temp); if (ret) { pr_debug("%s: Unable to read TSENS sensor %d\n", __func__, tsens_dev.sensor_num); dis_cnt++; continue; } if (temp <= msm_thermal_info.vdd_rstr_temp_degC) { ret = vdd_restriction_apply_all(1); if (ret) { pr_err( \ "Enable vdd rstr votlage for all failed\n"); goto exit; } goto exit; } else if (temp > msm_thermal_info.vdd_rstr_temp_hyst_degC) dis_cnt++; } if (dis_cnt == max_tsens_num) { ret = vdd_restriction_apply_all(0); if (ret) { pr_err("Disable vdd rstr votlage for all failed\n"); goto exit; } } exit: mutex_unlock(&vdd_rstr_mutex); return ret; } static int do_psm(void) { struct tsens_device tsens_dev; long temp = 0; int ret = 0; int i = 0; int auto_cnt = 0; mutex_lock(&psm_mutex); for (i = 0; i < max_tsens_num; i++) { tsens_dev.sensor_num = tsens_id_map[i]; ret = tsens_get_temp(&tsens_dev, &temp); if (ret) { pr_debug("%s: Unable to read TSENS sensor %d\n", __func__, tsens_dev.sensor_num); auto_cnt++; continue; } /* * As long as one sensor is above the threshold, set PWM mode * on all rails, and loop stops. Set auto mode when all rails * are below thershold */ if (temp > msm_thermal_info.psm_temp_degC) { ret = psm_set_mode_all(PMIC_PWM_MODE); if (ret) { pr_err("Set pwm mode for all failed\n"); goto exit; } break; } else if (temp <= msm_thermal_info.psm_temp_hyst_degC) auto_cnt++; } if (auto_cnt == max_tsens_num) { ret = psm_set_mode_all(PMIC_AUTO_MODE); if (ret) { pr_err("Set auto mode for all failed\n"); goto exit; } } exit: mutex_unlock(&psm_mutex); return ret; } static void __ref do_freq_control(long temp) { uint32_t cpu = 0; uint32_t max_freq = cpus[cpu].limited_max_freq; if (temp >= msm_thermal_info.limit_temp_degC) { if (limit_idx == limit_idx_low) return; limit_idx -= msm_thermal_info.bootup_freq_step; if (limit_idx < limit_idx_low) limit_idx = limit_idx_low; max_freq = table[limit_idx].frequency; } else if (temp < msm_thermal_info.limit_temp_degC - msm_thermal_info.temp_hysteresis_degC) { if (limit_idx == limit_idx_high) return; limit_idx += msm_thermal_info.bootup_freq_step; if (limit_idx >= limit_idx_high) { limit_idx = limit_idx_high; max_freq = UINT_MAX; } else max_freq = table[limit_idx].frequency; } if (max_freq == cpus[cpu].limited_max_freq) return; /* Update new limits */ get_online_cpus(); for_each_possible_cpu(cpu) { if (!(msm_thermal_info.bootup_freq_control_mask & BIT(cpu))) continue; cpus[cpu].limited_max_freq = max_freq; update_cpu_freq(cpu); } put_online_cpus(); } static void __ref check_temp(struct work_struct *work) { static int limit_init; struct tsens_device tsens_dev; long temp = 0; int ret = 0; tsens_dev.sensor_num = msm_thermal_info.sensor_id; ret = tsens_get_temp(&tsens_dev, &temp); if (ret) { pr_debug("%s: Unable to read TSENS sensor %d\n", KBUILD_MODNAME, tsens_dev.sensor_num); goto reschedule; } if (!limit_init) { ret = msm_thermal_get_freq_table(); if (ret) goto reschedule; else limit_init = 1; } do_core_control(temp); do_vdd_restriction(); do_psm(); do_ocr(); do_freq_control(temp); reschedule: if (enabled) schedule_delayed_work(&check_temp_work, msecs_to_jiffies(msm_thermal_info.poll_ms)); } static int __ref msm_thermal_cpu_callback(struct notifier_block *nfb, unsigned long action, void *hcpu) { uint32_t cpu = (uint32_t)hcpu; if (action == CPU_UP_PREPARE || action == CPU_UP_PREPARE_FROZEN) { if (core_control_enabled && (msm_thermal_info.core_control_mask & BIT(cpu)) && (cpus_offlined & BIT(cpu))) { pr_debug( "%s: Preventing cpu%d from coming online.\n", KBUILD_MODNAME, cpu); return NOTIFY_BAD; } } return NOTIFY_OK; } static struct notifier_block __refdata msm_thermal_cpu_notifier = { .notifier_call = msm_thermal_cpu_callback, }; static void thermal_rtc_setup(void) { ktime_t wakeup_time; ktime_t curr_time; curr_time = alarm_get_elapsed_realtime(); wakeup_time = ktime_add_us(curr_time, (wakeup_ms * USEC_PER_MSEC)); alarm_start_range(&thermal_rtc, wakeup_time, wakeup_time); pr_debug("%s: Current Time: %ld %ld, Alarm set to: %ld %ld\n", KBUILD_MODNAME, ktime_to_timeval(curr_time).tv_sec, ktime_to_timeval(curr_time).tv_usec, ktime_to_timeval(wakeup_time).tv_sec, ktime_to_timeval(wakeup_time).tv_usec); } static void timer_work_fn(struct work_struct *work) { sysfs_notify(tt_kobj, NULL, "wakeup_ms"); } static void thermal_rtc_callback(struct alarm *al) { struct timeval ts; ts = ktime_to_timeval(alarm_get_elapsed_realtime()); schedule_work(&timer_work); pr_debug("%s: Time on alarm expiry: %ld %ld\n", KBUILD_MODNAME, ts.tv_sec, ts.tv_usec); } static int hotplug_notify(enum thermal_trip_type type, int temp, void *data) { struct cpu_info *cpu_node = (struct cpu_info *)data; pr_info("%s: %s reach temp threshold: %d\n", KBUILD_MODNAME, cpu_node->sensor_type, temp); if (!(msm_thermal_info.core_control_mask & BIT(cpu_node->cpu))) return 0; switch (type) { case THERMAL_TRIP_CONFIGURABLE_HI: if (!(cpu_node->offline)) cpu_node->offline = 1; break; case THERMAL_TRIP_CONFIGURABLE_LOW: if (cpu_node->offline) cpu_node->offline = 0; break; default: break; } if (hotplug_task) { cpu_node->hotplug_thresh_clear = true; complete(&hotplug_notify_complete); } else { pr_err("%s: Hotplug task is not initialized\n", KBUILD_MODNAME); } return 0; } /* Adjust cpus offlined bit based on temperature reading. */ static int hotplug_init_cpu_offlined(void) { struct tsens_device tsens_dev; long temp = 0; uint32_t cpu = 0; if (!hotplug_enabled) return 0; mutex_lock(&core_control_mutex); for_each_possible_cpu(cpu) { if (!(msm_thermal_info.core_control_mask & BIT(cpus[cpu].cpu))) continue; tsens_dev.sensor_num = cpus[cpu].sensor_id; if (tsens_get_temp(&tsens_dev, &temp)) { pr_err("%s: Unable to read TSENS sensor %d\n", KBUILD_MODNAME, tsens_dev.sensor_num); mutex_unlock(&core_control_mutex); return -EINVAL; } if (temp >= msm_thermal_info.hotplug_temp_degC) cpus[cpu].offline = 1; else if (temp <= (msm_thermal_info.hotplug_temp_degC - msm_thermal_info.hotplug_temp_hysteresis_degC)) cpus[cpu].offline = 0; } mutex_unlock(&core_control_mutex); if (hotplug_task) complete(&hotplug_notify_complete); else { pr_err("%s: Hotplug task is not initialized\n", KBUILD_MODNAME); return -EINVAL; } return 0; } static void hotplug_init(void) { uint32_t cpu = 0; struct sensor_threshold *hi_thresh = NULL, *low_thresh = NULL; if (hotplug_task) return; if (!hotplug_enabled) goto init_kthread; for_each_possible_cpu(cpu) { cpus[cpu].sensor_id = sensor_get_id((char *)cpus[cpu].sensor_type); if (!(msm_thermal_info.core_control_mask & BIT(cpus[cpu].cpu))) continue; hi_thresh = &cpus[cpu].threshold[HOTPLUG_THRESHOLD_HIGH]; low_thresh = &cpus[cpu].threshold[HOTPLUG_THRESHOLD_LOW]; hi_thresh->temp = msm_thermal_info.hotplug_temp_degC; hi_thresh->trip = THERMAL_TRIP_CONFIGURABLE_HI; low_thresh->temp = msm_thermal_info.hotplug_temp_degC - msm_thermal_info.hotplug_temp_hysteresis_degC; low_thresh->trip = THERMAL_TRIP_CONFIGURABLE_LOW; hi_thresh->notify = low_thresh->notify = hotplug_notify; hi_thresh->data = low_thresh->data = (void *)&cpus[cpu]; set_threshold(cpus[cpu].sensor_id, hi_thresh); } init_kthread: init_completion(&hotplug_notify_complete); hotplug_task = kthread_run(do_hotplug, NULL, "msm_thermal:hotplug"); if (IS_ERR(hotplug_task)) { pr_err("%s: Failed to create do_hotplug thread\n", KBUILD_MODNAME); return; } /* * Adjust cpus offlined bit when hotplug intitializes so that the new * cpus offlined state is based on hotplug threshold range */ if (hotplug_init_cpu_offlined()) kthread_stop(hotplug_task); } static __ref int do_freq_mitigation(void *data) { int ret = 0; uint32_t cpu = 0, max_freq_req = 0, min_freq_req = 0; while (!kthread_should_stop()) { wait_for_completion(&freq_mitigation_complete); INIT_COMPLETION(freq_mitigation_complete); get_online_cpus(); for_each_possible_cpu(cpu) { max_freq_req = (cpus[cpu].max_freq) ? msm_thermal_info.freq_limit : UINT_MAX; max_freq_req = min(max_freq_req, cpus[cpu].user_max_freq); min_freq_req = max(min_freq_limit, cpus[cpu].user_min_freq); if ((max_freq_req == cpus[cpu].limited_max_freq) && (min_freq_req == cpus[cpu].limited_min_freq)) goto reset_threshold; cpus[cpu].limited_max_freq = max_freq_req; cpus[cpu].limited_min_freq = min_freq_req; update_cpu_freq(cpu); reset_threshold: if (freq_mitigation_enabled && cpus[cpu].freq_thresh_clear) { set_threshold(cpus[cpu].sensor_id, &cpus[cpu].threshold[FREQ_THRESHOLD_HIGH]); cpus[cpu].freq_thresh_clear = false; } } put_online_cpus(); } return ret; } static int freq_mitigation_notify(enum thermal_trip_type type, int temp, void *data) { struct cpu_info *cpu_node = (struct cpu_info *) data; pr_debug("%s: %s reached temp threshold: %d\n", KBUILD_MODNAME, cpu_node->sensor_type, temp); if (!(msm_thermal_info.freq_mitig_control_mask & BIT(cpu_node->cpu))) return 0; switch (type) { case THERMAL_TRIP_CONFIGURABLE_HI: if (!cpu_node->max_freq) { pr_info("%s: Mitigating cpu %d frequency to %d\n", KBUILD_MODNAME, cpu_node->cpu, msm_thermal_info.freq_limit); cpu_node->max_freq = true; } break; case THERMAL_TRIP_CONFIGURABLE_LOW: if (cpu_node->max_freq) { pr_info("%s: Removing frequency mitigation for cpu%d\n", KBUILD_MODNAME, cpu_node->cpu); cpu_node->max_freq = false; } break; default: break; } if (freq_mitigation_task) { cpu_node->freq_thresh_clear = true; complete(&freq_mitigation_complete); } else { pr_err("%s: Frequency mitigation task is not initialized\n", KBUILD_MODNAME); } return 0; } static void freq_mitigation_init(void) { uint32_t cpu = 0; struct sensor_threshold *hi_thresh = NULL, *low_thresh = NULL; if (freq_mitigation_task) return; if (!freq_mitigation_enabled) goto init_freq_thread; for_each_possible_cpu(cpu) { if (!(msm_thermal_info.freq_mitig_control_mask & BIT(cpu))) continue; hi_thresh = &cpus[cpu].threshold[FREQ_THRESHOLD_HIGH]; low_thresh = &cpus[cpu].threshold[FREQ_THRESHOLD_LOW]; hi_thresh->temp = msm_thermal_info.freq_mitig_temp_degc; hi_thresh->trip = THERMAL_TRIP_CONFIGURABLE_HI; low_thresh->temp = msm_thermal_info.freq_mitig_temp_degc - msm_thermal_info.freq_mitig_temp_hysteresis_degc; low_thresh->trip = THERMAL_TRIP_CONFIGURABLE_LOW; hi_thresh->notify = low_thresh->notify = freq_mitigation_notify; hi_thresh->data = low_thresh->data = (void *)&cpus[cpu]; set_threshold(cpus[cpu].sensor_id, hi_thresh); } init_freq_thread: init_completion(&freq_mitigation_complete); freq_mitigation_task = kthread_run(do_freq_mitigation, NULL, "msm_thermal:freq_mitig"); if (IS_ERR(freq_mitigation_task)) { pr_err("%s: Failed to create frequency mitigation thread\n", KBUILD_MODNAME); return; } } int msm_thermal_set_frequency(uint32_t cpu, uint32_t freq, bool is_max) { int ret = 0; if (cpu >= num_possible_cpus()) { pr_err("%s: Invalid input\n", KBUILD_MODNAME); ret = -EINVAL; goto set_freq_exit; } if (is_max) { if (cpus[cpu].user_max_freq == freq) goto set_freq_exit; cpus[cpu].user_max_freq = freq; } else { if (cpus[cpu].user_min_freq == freq) goto set_freq_exit; cpus[cpu].user_min_freq = freq; } if (freq_mitigation_task) { complete(&freq_mitigation_complete); } else { pr_err("%s: Frequency mitigation task is not initialized\n", KBUILD_MODNAME); ret = -ESRCH; goto set_freq_exit; } set_freq_exit: return ret; } /* * We will reset the cpu frequencies limits here. The core online/offline * status will be carried over to the process stopping the msm_thermal, as * we dont want to online a core and bring in the thermal issues. */ static void __ref disable_msm_thermal(void) { uint32_t cpu = 0; /* make sure check_temp is no longer running */ cancel_delayed_work(&check_temp_work); flush_scheduled_work(); get_online_cpus(); for_each_possible_cpu(cpu) { if (cpus[cpu].limited_max_freq == UINT_MAX && cpus[cpu].limited_min_freq == 0) continue; cpus[cpu].limited_max_freq = UINT_MAX; cpus[cpu].limited_min_freq = 0; update_cpu_freq(cpu); } put_online_cpus(); } static int __ref set_enabled(const char *val, const struct kernel_param *kp) { int ret = 0; ret = param_set_bool(val, kp); if (!enabled) { disable_msm_thermal(); hotplug_init(); freq_mitigation_init(); } else pr_info("%s: no action for enabled = %d\n", KBUILD_MODNAME, enabled); pr_info("%s: enabled = %d\n", KBUILD_MODNAME, enabled); return ret; } static struct kernel_param_ops module_ops = { .set = set_enabled, .get = param_get_bool, }; module_param_cb(enabled, &module_ops, &enabled, 0644); MODULE_PARM_DESC(enabled, "enforce thermal limit on cpu"); #if defined(FEATURE_PANTECH_ECO_CPU_MODE) static int set_ecocpu(const char *val, const struct kernel_param *kp) { int ret = 0; ret = param_set_bool(val, kp); pr_info("msm_thermal: ecocpu = %d\n", ecocpu); return ret; } static struct kernel_param_ops module_ops_ecocpu = { .set = set_ecocpu, .get = param_get_bool, }; module_param_cb(ecocpu, &module_ops_ecocpu, &ecocpu, 0644); MODULE_PARM_DESC(ecocpu, "ecocpu on"); #endif /* FEATURE_PANTECH_ECO_CPU_MODE */ static ssize_t show_cc_enabled(struct kobject *kobj, struct kobj_attribute *attr, char *buf) { return snprintf(buf, PAGE_SIZE, "%d\n", core_control_enabled); } static ssize_t __ref store_cc_enabled(struct kobject *kobj, struct kobj_attribute *attr, const char *buf, size_t count) { int ret = 0; int val = 0; ret = kstrtoint(buf, 10, &val); if (ret) { pr_err("%s: Invalid input %s\n", KBUILD_MODNAME, buf); goto done_store_cc; } if (core_control_enabled == !!val) goto done_store_cc; core_control_enabled = !!val; if (core_control_enabled) { pr_info("%s: Core control enabled\n", KBUILD_MODNAME); register_cpu_notifier(&msm_thermal_cpu_notifier); if (hotplug_task) complete(&hotplug_notify_complete); else pr_err("%s: Hotplug task is not initialized\n", KBUILD_MODNAME); } else { pr_info("%s: Core control disabled\n", KBUILD_MODNAME); unregister_cpu_notifier(&msm_thermal_cpu_notifier); } done_store_cc: return count; } static ssize_t show_cpus_offlined(struct kobject *kobj, struct kobj_attribute *attr, char *buf) { return snprintf(buf, PAGE_SIZE, "%d\n", cpus_offlined); } static ssize_t __ref store_cpus_offlined(struct kobject *kobj, struct kobj_attribute *attr, const char *buf, size_t count) { int ret = 0; uint32_t val = 0; uint32_t cpu; mutex_lock(&core_control_mutex); ret = kstrtouint(buf, 10, &val); if (ret) { pr_err("%s: Invalid input %s\n", KBUILD_MODNAME, buf); goto done_cc; } if (enabled) { pr_err("%s: Ignoring request; polling thread is enabled.\n", KBUILD_MODNAME); goto done_cc; } for_each_possible_cpu(cpu) { if (!(msm_thermal_info.core_control_mask & BIT(cpu))) continue; cpus[cpu].user_offline = !!(val & BIT(cpu)); } if (hotplug_task) complete(&hotplug_notify_complete); else pr_err("%s: Hotplug task is not initialized\n", KBUILD_MODNAME); done_cc: mutex_unlock(&core_control_mutex); return count; } static __refdata struct kobj_attribute cc_enabled_attr = __ATTR(enabled, 0644, show_cc_enabled, store_cc_enabled); static __refdata struct kobj_attribute cpus_offlined_attr = __ATTR(cpus_offlined, 0644, show_cpus_offlined, store_cpus_offlined); static __refdata struct attribute *cc_attrs[] = { &cc_enabled_attr.attr, &cpus_offlined_attr.attr, NULL, }; static __refdata struct attribute_group cc_attr_group = { .attrs = cc_attrs, }; static ssize_t show_wakeup_ms(struct kobject *kobj, struct kobj_attribute *attr, char *buf) { return snprintf(buf, PAGE_SIZE, "%d\n", wakeup_ms); } static ssize_t store_wakeup_ms(struct kobject *kobj, struct kobj_attribute *attr, const char *buf, size_t count) { int ret; ret = kstrtouint(buf, 10, &wakeup_ms); if (ret) { pr_err("%s: Trying to set invalid wakeup timer\n", KBUILD_MODNAME); return ret; } if (wakeup_ms > 0) { thermal_rtc_setup(); pr_debug("%s: Timer started for %ums\n", KBUILD_MODNAME, wakeup_ms); } else { ret = alarm_cancel(&thermal_rtc); if (ret) pr_debug("%s: Timer canceled\n", KBUILD_MODNAME); else pr_debug("%s: No active timer present to cancel\n", KBUILD_MODNAME); } return count; } static __refdata struct kobj_attribute timer_attr = __ATTR(wakeup_ms, 0644, show_wakeup_ms, store_wakeup_ms); static __refdata struct attribute *tt_attrs[] = { &timer_attr.attr, NULL, }; static __refdata struct attribute_group tt_attr_group = { .attrs = tt_attrs, }; static __init int msm_thermal_add_cc_nodes(void) { struct kobject *module_kobj = NULL; int ret = 0; module_kobj = kset_find_obj(module_kset, KBUILD_MODNAME); if (!module_kobj) { pr_err("%s: cannot find kobject for module\n", KBUILD_MODNAME); ret = -ENOENT; goto done_cc_nodes; } cc_kobj = kobject_create_and_add("core_control", module_kobj); if (!cc_kobj) { pr_err("%s: cannot create core control kobj\n", KBUILD_MODNAME); ret = -ENOMEM; goto done_cc_nodes; } ret = sysfs_create_group(cc_kobj, &cc_attr_group); if (ret) { pr_err("%s: cannot create group\n", KBUILD_MODNAME); goto done_cc_nodes; } return 0; done_cc_nodes: if (cc_kobj) kobject_del(cc_kobj); return ret; } static __init int msm_thermal_add_timer_nodes(void) { struct kobject *module_kobj = NULL; int ret = 0; module_kobj = kset_find_obj(module_kset, KBUILD_MODNAME); if (!module_kobj) { pr_err("%s: cannot find kobject for module\n", KBUILD_MODNAME); ret = -ENOENT; goto failed; } tt_kobj = kobject_create_and_add("thermal_timer", module_kobj); if (!tt_kobj) { pr_err("%s: cannot create timer kobj\n", KBUILD_MODNAME); ret = -ENOMEM; goto failed; } ret = sysfs_create_group(tt_kobj, &tt_attr_group); if (ret) { pr_err("%s: cannot create group\n", KBUILD_MODNAME); goto failed; } return 0; failed: if (tt_kobj) kobject_del(tt_kobj); return ret; } int __devinit msm_thermal_init(struct msm_thermal_data *pdata) { int ret = 0; uint32_t cpu; BUG_ON(!pdata); tsens_get_max_sensor_num(&max_tsens_num); memcpy(&msm_thermal_info, pdata, sizeof(struct msm_thermal_data)); if (create_sensor_id_map()) return -EINVAL; if (check_sensor_id(msm_thermal_info.sensor_id)) return -EINVAL; enabled = 1; #if defined(FEATURE_PANTECH_ECO_CPU_MODE) ecocpu=0; #endif for_each_possible_cpu(cpu) { cpus[cpu].limited_max_freq = UINT_MAX; cpus[cpu].limited_min_freq = 0; } ret = cpufreq_register_notifier(&msm_thermal_cpufreq_notifier, CPUFREQ_POLICY_NOTIFIER); if (ret) pr_err("%s: cannot register cpufreq notifier\n", KBUILD_MODNAME); INIT_DELAYED_WORK(&check_temp_work, check_temp); schedule_delayed_work(&check_temp_work, 0); if (num_possible_cpus() > 1) register_cpu_notifier(&msm_thermal_cpu_notifier); return ret; } static int ocr_reg_init(struct platform_device *pdev) { int ret = 0; int i, j; for (i = 0; i < ocr_rail_cnt; i++) { /* Check if vdd_restriction has already initialized any * regualtor handle. If so use the same handle.*/ for (j = 0; j < rails_cnt; j++) { if (!strcmp(ocr_rails[i].name, rails[j].name)) { if (rails[j].reg == NULL) break; ocr_rails[i].phase_reg = rails[j].reg; goto reg_init; } } ocr_rails[i].phase_reg = devm_regulator_get(&pdev->dev, ocr_rails[i].name); if (IS_ERR_OR_NULL(ocr_rails[i].phase_reg)) { ret = PTR_ERR(ocr_rails[i].phase_reg); if (ret != -EPROBE_DEFER) { pr_err("%s, could not get regulator: %s\n", __func__, ocr_rails[i].name); ocr_rails[i].phase_reg = NULL; ocr_rails[i].mode = 0; ocr_rails[i].init = 0; } return ret; } reg_init: ocr_rails[i].mode = OPTIMUM_CURRENT_MIN; } return ret; } static int vdd_restriction_reg_init(struct platform_device *pdev) { int ret = 0; int i; for (i = 0; i < rails_cnt; i++) { if (rails[i].freq_req == 1) { usefreq |= BIT(i); check_freq_table(); /* * Restrict frequency by default until we have made * our first temp reading */ if (freq_table_get) ret = vdd_restriction_apply_freq(&rails[i], 0); else pr_info("%s:Defer vdd rstr freq init\n", __func__); } else { rails[i].reg = devm_regulator_get(&pdev->dev, rails[i].name); if (IS_ERR_OR_NULL(rails[i].reg)) { ret = PTR_ERR(rails[i].reg); if (ret != -EPROBE_DEFER) { pr_err( \ "%s, could not get regulator: %s\n", rails[i].name, __func__); rails[i].reg = NULL; rails[i].curr_level = -2; return ret; } return ret; } /* * Restrict votlage by default until we have made * our first temp reading */ ret = vdd_restriction_apply_voltage(&rails[i], 0); } } return ret; } static int psm_reg_init(struct platform_device *pdev) { int ret = 0; int i = 0; int j = 0; for (i = 0; i < psm_rails_cnt; i++) { psm_rails[i].reg = rpm_regulator_get(&pdev->dev, psm_rails[i].name); if (IS_ERR_OR_NULL(psm_rails[i].reg)) { ret = PTR_ERR(psm_rails[i].reg); if (ret != -EPROBE_DEFER) { pr_err("%s, could not get rpm regulator: %s\n", psm_rails[i].name, __func__); psm_rails[i].reg = NULL; goto psm_reg_exit; } return ret; } /* Apps default vote for PWM mode */ psm_rails[i].init = PMIC_PWM_MODE; ret = rpm_regulator_set_mode(psm_rails[i].reg, psm_rails[i].init); if (ret) { pr_err("%s: Cannot set PMIC PWM mode\n", __func__); return ret; } else psm_rails[i].mode = PMIC_PWM_MODE; } return ret; psm_reg_exit: if (ret) { for (j = 0; j < i; j++) { if (psm_rails[j].reg != NULL) rpm_regulator_put(psm_rails[j].reg); } } return ret; } static int msm_thermal_add_vdd_rstr_nodes(void) { struct kobject *module_kobj = NULL; struct kobject *vdd_rstr_kobj = NULL; struct kobject *vdd_rstr_reg_kobj[MAX_RAILS] = {0}; int rc = 0; int i = 0; if (!vdd_rstr_probed) { vdd_rstr_nodes_called = true; return rc; } if (vdd_rstr_probed && rails_cnt == 0) return rc; module_kobj = kset_find_obj(module_kset, KBUILD_MODNAME); if (!module_kobj) { pr_err("%s: cannot find kobject for module %s\n", __func__, KBUILD_MODNAME); rc = -ENOENT; goto thermal_sysfs_add_exit; } vdd_rstr_kobj = kobject_create_and_add("vdd_restriction", module_kobj); if (!vdd_rstr_kobj) { pr_err("%s: cannot create vdd_restriction kobject\n", __func__); rc = -ENOMEM; goto thermal_sysfs_add_exit; } rc = sysfs_create_group(vdd_rstr_kobj, &vdd_rstr_en_attribs_gp); if (rc) { pr_err("%s: cannot create kobject attribute group\n", __func__); rc = -ENOMEM; goto thermal_sysfs_add_exit; } for (i = 0; i < rails_cnt; i++) { vdd_rstr_reg_kobj[i] = kobject_create_and_add(rails[i].name, vdd_rstr_kobj); if (!vdd_rstr_reg_kobj[i]) { pr_err("%s: cannot create for kobject for %s\n", __func__, rails[i].name); rc = -ENOMEM; goto thermal_sysfs_add_exit; } rails[i].attr_gp.attrs = kzalloc(sizeof(struct attribute *) * 3, GFP_KERNEL); if (!rails[i].attr_gp.attrs) { rc = -ENOMEM; goto thermal_sysfs_add_exit; } VDD_RES_RW_ATTRIB(rails[i], rails[i].level_attr, 0, level); VDD_RES_RO_ATTRIB(rails[i], rails[i].value_attr, 1, value); rails[i].attr_gp.attrs[2] = NULL; rc = sysfs_create_group(vdd_rstr_reg_kobj[i], &rails[i].attr_gp); if (rc) { pr_err("%s: cannot create attribute group for %s\n", __func__, rails[i].name); goto thermal_sysfs_add_exit; } } return rc; thermal_sysfs_add_exit: if (rc) { for (i = 0; i < rails_cnt; i++) { kobject_del(vdd_rstr_reg_kobj[i]); kfree(rails[i].attr_gp.attrs); } if (vdd_rstr_kobj) kobject_del(vdd_rstr_kobj); } return rc; } static int msm_thermal_add_ocr_nodes(void) { struct kobject *module_kobj = NULL; struct kobject *ocr_kobj = NULL; struct kobject *ocr_reg_kobj[MAX_RAILS] = {0}; int rc = 0; int i = 0; if (!ocr_probed) { ocr_nodes_called = true; return rc; } if (ocr_probed && ocr_rail_cnt == 0) return rc; module_kobj = kset_find_obj(module_kset, KBUILD_MODNAME); if (!module_kobj) { pr_err("%s: cannot find kobject for module %s\n", __func__, KBUILD_MODNAME); rc = -ENOENT; goto ocr_node_exit; } ocr_kobj = kobject_create_and_add("opt_curr_req", module_kobj); if (!ocr_kobj) { pr_err("%s: cannot create ocr kobject\n", KBUILD_MODNAME); rc = -ENOMEM; goto ocr_node_exit; } for (i = 0; i < ocr_rail_cnt; i++) { ocr_reg_kobj[i] = kobject_create_and_add(ocr_rails[i].name, ocr_kobj); if (!ocr_reg_kobj[i]) { pr_err("%s: cannot create for kobject for %s\n", KBUILD_MODNAME, ocr_rails[i].name); rc = -ENOMEM; goto ocr_node_exit; } ocr_rails[i].attr_gp.attrs = kzalloc( \ sizeof(struct attribute *) * 2, GFP_KERNEL); if (!ocr_rails[i].attr_gp.attrs) { rc = -ENOMEM; goto ocr_node_exit; } OCR_RW_ATTRIB(ocr_rails[i], ocr_rails[i].mode_attr, 0, mode); ocr_rails[i].attr_gp.attrs[1] = NULL; rc = sysfs_create_group(ocr_reg_kobj[i], &ocr_rails[i].attr_gp); if (rc) { pr_err("%s: cannot create attribute group for %s\n", KBUILD_MODNAME, ocr_rails[i].name); goto ocr_node_exit; } } ocr_node_exit: if (rc) { for (i = 0; i < ocr_rail_cnt; i++) { if (ocr_reg_kobj[i]) kobject_del(ocr_reg_kobj[i]); if (ocr_rails[i].attr_gp.attrs) { kfree(ocr_rails[i].attr_gp.attrs); ocr_rails[i].attr_gp.attrs = NULL; } } if (ocr_kobj) kobject_del(ocr_kobj); } return rc; } static int msm_thermal_add_psm_nodes(void) { struct kobject *module_kobj = NULL; struct kobject *psm_kobj = NULL; struct kobject *psm_reg_kobj[MAX_RAILS] = {0}; int rc = 0; int i = 0; if (!psm_probed) { psm_nodes_called = true; return rc; } if (psm_probed && psm_rails_cnt == 0) return rc; module_kobj = kset_find_obj(module_kset, KBUILD_MODNAME); if (!module_kobj) { pr_err("%s: cannot find kobject for module %s\n", __func__, KBUILD_MODNAME); rc = -ENOENT; goto psm_node_exit; } psm_kobj = kobject_create_and_add("pmic_sw_mode", module_kobj); if (!psm_kobj) { pr_err("%s: cannot create psm kobject\n", KBUILD_MODNAME); rc = -ENOMEM; goto psm_node_exit; } for (i = 0; i < psm_rails_cnt; i++) { psm_reg_kobj[i] = kobject_create_and_add(psm_rails[i].name, psm_kobj); if (!psm_reg_kobj[i]) { pr_err("%s: cannot create for kobject for %s\n", KBUILD_MODNAME, psm_rails[i].name); rc = -ENOMEM; goto psm_node_exit; } psm_rails[i].attr_gp.attrs = kzalloc( \ sizeof(struct attribute *) * 2, GFP_KERNEL); if (!psm_rails[i].attr_gp.attrs) { rc = -ENOMEM; goto psm_node_exit; } PSM_RW_ATTRIB(psm_rails[i], psm_rails[i].mode_attr, 0, mode); psm_rails[i].attr_gp.attrs[1] = NULL; rc = sysfs_create_group(psm_reg_kobj[i], &psm_rails[i].attr_gp); if (rc) { pr_err("%s: cannot create attribute group for %s\n", KBUILD_MODNAME, psm_rails[i].name); goto psm_node_exit; } } return rc; psm_node_exit: if (rc) { for (i = 0; i < psm_rails_cnt; i++) { kobject_del(psm_reg_kobj[i]); kfree(psm_rails[i].attr_gp.attrs); } if (psm_kobj) kobject_del(psm_kobj); } return rc; } static int probe_vdd_rstr(struct device_node *node, struct msm_thermal_data *data, struct platform_device *pdev) { int ret = 0; int i = 0; int arr_size; char *key = NULL; struct device_node *child_node = NULL; rails = NULL; key = "qcom,vdd-restriction-temp"; ret = of_property_read_u32(node, key, &data->vdd_rstr_temp_degC); if (ret) goto read_node_fail; key = "qcom,vdd-restriction-temp-hysteresis"; ret = of_property_read_u32(node, key, &data->vdd_rstr_temp_hyst_degC); if (ret) goto read_node_fail; for_each_child_of_node(node, child_node) { rails_cnt++; } if (rails_cnt == 0) goto read_node_fail; if (rails_cnt >= MAX_RAILS) { pr_err("%s: Too many rails.\n", __func__); return -EFAULT; } rails = kzalloc(sizeof(struct rail) * rails_cnt, GFP_KERNEL); if (!rails) { pr_err("%s: Fail to allocate memory for rails.\n", __func__); return -ENOMEM; } i = 0; for_each_child_of_node(node, child_node) { key = "qcom,vdd-rstr-reg"; ret = of_property_read_string(child_node, key, &rails[i].name); if (ret) goto read_node_fail; key = "qcom,levels"; if (!of_get_property(child_node, key, &arr_size)) goto read_node_fail; rails[i].num_levels = arr_size/sizeof(__be32); if (rails[i].num_levels > sizeof(rails[i].levels)/sizeof(uint32_t)) { pr_err("%s: Array size too large\n", __func__); return -EFAULT; } ret = of_property_read_u32_array(child_node, key, rails[i].levels, rails[i].num_levels); if (ret) goto read_node_fail; key = "qcom,freq-req"; rails[i].freq_req = of_property_read_bool(child_node, key); if (rails[i].freq_req) rails[i].min_level = 0; else { key = "qcom,min-level"; ret = of_property_read_u32(child_node, key, &rails[i].min_level); if (ret) goto read_node_fail; } rails[i].curr_level = -1; rails[i].reg = NULL; i++; } if (rails_cnt) { ret = vdd_restriction_reg_init(pdev); if (ret) { pr_info("%s:Failed to get regulators. KTM continues.\n", __func__); goto read_node_fail; } vdd_rstr_enabled = true; } read_node_fail: vdd_rstr_probed = true; if (ret) { dev_info(&pdev->dev, "%s:Failed reading node=%s, key=%s. KTM continues\n", __func__, node->full_name, key); kfree(rails); rails_cnt = 0; } if (ret == -EPROBE_DEFER) vdd_rstr_probed = false; return ret; } static int probe_ocr(struct device_node *node, struct msm_thermal_data *data, struct platform_device *pdev) { int ret = 0; int j = 0; char *key = NULL; if (ocr_probed) { pr_info("%s: Nodes already probed\n", __func__); goto read_ocr_exit; } ocr_rails = NULL; key = "qti,pmic-opt-curr-temp"; ret = of_property_read_u32(node, key, &data->ocr_temp_degC); if (ret) goto read_ocr_fail; key = "qti,pmic-opt-curr-temp-hysteresis"; ret = of_property_read_u32(node, key, &data->ocr_temp_hyst_degC); if (ret) goto read_ocr_fail; key = "qti,pmic-opt-curr-regs"; ocr_rail_cnt = of_property_count_strings(node, key); ocr_rails = kzalloc(sizeof(struct psm_rail) * ocr_rail_cnt, GFP_KERNEL); if (!ocr_rails) { pr_err("%s: Fail to allocate memory for ocr rails\n", __func__); ocr_rail_cnt = 0; return -ENOMEM; } for (j = 0; j < ocr_rail_cnt; j++) { ret = of_property_read_string_index(node, key, j, &ocr_rails[j].name); if (ret) goto read_ocr_fail; ocr_rails[j].phase_reg = NULL; ocr_rails[j].init = OPTIMUM_CURRENT_MAX; } if (ocr_rail_cnt) { ret = ocr_reg_init(pdev); if (ret) { pr_info("%s:Failed to get regulators. KTM continues.\n", __func__); goto read_ocr_fail; } ocr_enabled = true; ocr_nodes_called = false; /* * Vote for max optimum current by default until we have made * our first temp reading */ if (ocr_set_mode_all(OPTIMUM_CURRENT_MAX)) pr_err("Set max optimum current failed\n"); } read_ocr_fail: ocr_probed = true; if (ret) { dev_info(&pdev->dev, "%s:Failed reading node=%s, key=%s. KTM continues\n", __func__, node->full_name, key); if (ocr_rails) kfree(ocr_rails); ocr_rails = NULL; ocr_rail_cnt = 0; } if (ret == -EPROBE_DEFER) ocr_probed = false; read_ocr_exit: return ret; } static int probe_psm(struct device_node *node, struct msm_thermal_data *data, struct platform_device *pdev) { int ret = 0; int j = 0; char *key = NULL; psm_rails = NULL; key = "qcom,pmic-sw-mode-temp"; ret = of_property_read_u32(node, key, &data->psm_temp_degC); if (ret) goto read_node_fail; key = "qcom,pmic-sw-mode-temp-hysteresis"; ret = of_property_read_u32(node, key, &data->psm_temp_hyst_degC); if (ret) goto read_node_fail; key = "qcom,pmic-sw-mode-regs"; psm_rails_cnt = of_property_count_strings(node, key); psm_rails = kzalloc(sizeof(struct psm_rail) * psm_rails_cnt, GFP_KERNEL); if (!psm_rails) { pr_err("%s: Fail to allocate memory for psm rails\n", __func__); psm_rails_cnt = 0; return -ENOMEM; } for (j = 0; j < psm_rails_cnt; j++) { ret = of_property_read_string_index(node, key, j, &psm_rails[j].name); if (ret) goto read_node_fail; } if (psm_rails_cnt) { ret = psm_reg_init(pdev); if (ret) { pr_info("%s:Failed to get regulators. KTM continues.\n", __func__); goto read_node_fail; } psm_enabled = true; } read_node_fail: psm_probed = true; if (ret) { dev_info(&pdev->dev, "%s:Failed reading node=%s, key=%s. KTM continues\n", __func__, node->full_name, key); kfree(psm_rails); psm_rails_cnt = 0; } if (ret == -EPROBE_DEFER) psm_probed = false; return ret; } static int probe_cc(struct device_node *node, struct msm_thermal_data *data, struct platform_device *pdev) { char *key = NULL; uint32_t cpu_cnt = 0; int ret = 0; uint32_t cpu = 0; if (num_possible_cpus() > 1) { core_control_enabled = 1; hotplug_enabled = 1; } key = "qcom,core-limit-temp"; ret = of_property_read_u32(node, key, &data->core_limit_temp_degC); if (ret) goto read_node_fail; key = "qcom,core-temp-hysteresis"; ret = of_property_read_u32(node, key, &data->core_temp_hysteresis_degC); if (ret) goto read_node_fail; key = "qcom,core-control-mask"; ret = of_property_read_u32(node, key, &data->core_control_mask); if (ret) goto read_node_fail; key = "qcom,hotplug-temp"; ret = of_property_read_u32(node, key, &data->hotplug_temp_degC); if (ret) goto hotplug_node_fail; key = "qcom,hotplug-temp-hysteresis"; ret = of_property_read_u32(node, key, &data->hotplug_temp_hysteresis_degC); if (ret) goto hotplug_node_fail; key = "qcom,cpu-sensors"; cpu_cnt = of_property_count_strings(node, key); if (cpu_cnt != num_possible_cpus()) { pr_err("%s: Wrong number of cpu\n", KBUILD_MODNAME); ret = -EINVAL; goto hotplug_node_fail; } for_each_possible_cpu(cpu) { cpus[cpu].cpu = cpu; cpus[cpu].offline = 0; cpus[cpu].user_offline = 0; cpus[cpu].hotplug_thresh_clear = false; ret = of_property_read_string_index(node, key, cpu, &cpus[cpu].sensor_type); if (ret) goto hotplug_node_fail; } read_node_fail: if (ret) { dev_info(&pdev->dev, "%s:Failed reading node=%s, key=%s. KTM continues\n", KBUILD_MODNAME, node->full_name, key); core_control_enabled = 0; } return ret; hotplug_node_fail: if (ret) { dev_info(&pdev->dev, "%s:Failed reading node=%s, key=%s. KTM continues\n", KBUILD_MODNAME, node->full_name, key); hotplug_enabled = 0; } return ret; } static int probe_freq_mitigation(struct device_node *node, struct msm_thermal_data *data, struct platform_device *pdev) { char *key = NULL; int ret = 0; uint32_t cpu; key = "qcom,freq-mitigation-temp"; ret = of_property_read_u32(node, key, &data->freq_mitig_temp_degc); if (ret) goto PROBE_FREQ_EXIT; key = "qcom,freq-mitigation-temp-hysteresis"; ret = of_property_read_u32(node, key, &data->freq_mitig_temp_hysteresis_degc); if (ret) goto PROBE_FREQ_EXIT; key = "qcom,freq-mitigation-value"; ret = of_property_read_u32(node, key, &data->freq_limit); if (ret) goto PROBE_FREQ_EXIT; key = "qcom,freq-mitigation-control-mask"; ret = of_property_read_u32(node, key, &data->freq_mitig_control_mask); if (ret) goto PROBE_FREQ_EXIT; freq_mitigation_enabled = 1; for_each_possible_cpu(cpu) { cpus[cpu].max_freq = false; cpus[cpu].user_max_freq = UINT_MAX; cpus[cpu].user_min_freq = 0; cpus[cpu].limited_max_freq = UINT_MAX; cpus[cpu].limited_min_freq = 0; cpus[cpu].freq_thresh_clear = false; } PROBE_FREQ_EXIT: if (ret) { dev_info(&pdev->dev, "%s:Failed reading node=%s, key=%s. KTM continues\n", __func__, node->full_name, key); freq_mitigation_enabled = 0; } return ret; } static int __devinit msm_thermal_dev_probe(struct platform_device *pdev) { int ret = 0; char *key = NULL; struct device_node *node = pdev->dev.of_node; struct msm_thermal_data data; memset(&data, 0, sizeof(struct msm_thermal_data)); key = "qcom,sensor-id"; ret = of_property_read_u32(node, key, &data.sensor_id); if (ret) goto fail; key = "qcom,poll-ms"; ret = of_property_read_u32(node, key, &data.poll_ms); if (ret) goto fail; key = "qcom,limit-temp"; ret = of_property_read_u32(node, key, &data.limit_temp_degC); if (ret) goto fail; key = "qcom,temp-hysteresis"; ret = of_property_read_u32(node, key, &data.temp_hysteresis_degC); if (ret) goto fail; key = "qcom,freq-step"; ret = of_property_read_u32(node, key, &data.bootup_freq_step); if (ret) goto fail; key = "qcom,freq-control-mask"; ret = of_property_read_u32(node, key, &data.bootup_freq_control_mask); ret = probe_cc(node, &data, pdev); ret = probe_freq_mitigation(node, &data, pdev); /* * Probe optional properties below. Call probe_psm before * probe_vdd_rstr because rpm_regulator_get has to be called * before devm_regulator_get * probe_ocr should be called after probe_vdd_rstr to reuse the * regualtor handle. calling devm_regulator_get more than once * will fail. */ ret = probe_psm(node, &data, pdev); if (ret == -EPROBE_DEFER) goto fail; ret = probe_vdd_rstr(node, &data, pdev); if (ret == -EPROBE_DEFER) goto fail; ret = probe_ocr(node, &data, pdev); if (ret == -EPROBE_DEFER) goto fail; /* * In case sysfs add nodes get called before probe function. * Need to make sure sysfs node is created again */ if (psm_nodes_called) { msm_thermal_add_psm_nodes(); psm_nodes_called = false; } if (vdd_rstr_nodes_called) { msm_thermal_add_vdd_rstr_nodes(); vdd_rstr_nodes_called = false; } if (ocr_nodes_called) { msm_thermal_add_ocr_nodes(); ocr_nodes_called = false; } msm_thermal_ioctl_init(); ret = msm_thermal_init(&data); return ret; fail: if (ret) pr_err("%s: Failed reading node=%s, key=%s\n", __func__, node->full_name, key); return ret; } static int msm_thermal_dev_exit(struct platform_device *inp_dev) { msm_thermal_ioctl_cleanup(); return 0; } static struct of_device_id msm_thermal_match_table[] = { {.compatible = "qcom,msm-thermal"}, {}, }; static struct platform_driver msm_thermal_device_driver = { .probe = msm_thermal_dev_probe, .driver = { .name = "msm-thermal", .owner = THIS_MODULE, .of_match_table = msm_thermal_match_table, }, .remove = msm_thermal_dev_exit, }; int __init msm_thermal_device_init(void) { return platform_driver_register(&msm_thermal_device_driver); } int __init msm_thermal_late_init(void) { if (num_possible_cpus() > 1) msm_thermal_add_cc_nodes(); msm_thermal_add_psm_nodes(); msm_thermal_add_vdd_rstr_nodes(); msm_thermal_add_ocr_nodes(); alarm_init(&thermal_rtc, ANDROID_ALARM_ELAPSED_REALTIME_WAKEUP, thermal_rtc_callback); INIT_WORK(&timer_work, timer_work_fn); msm_thermal_add_timer_nodes(); return 0; } late_initcall(msm_thermal_late_init);
pantech-msm8974/android_kernel_pantech_msm8974
drivers/thermal/msm_thermal.c
C
gpl-2.0
63,342
/* * Open Source Software published under the GNU Licence, Version 2.0. */ package io.github.liquec.gui.controller; import io.github.liquec.analysis.core.GuiTaskHandler; import io.github.liquec.analysis.core.LiquEcException; import io.github.liquec.analysis.session.EnrichedSessionState; import io.github.liquec.analysis.session.FileNameTool; import io.github.liquec.analysis.session.SessionState; import io.github.liquec.gui.dialogues.*; import io.github.liquec.gui.model.MainModel; import io.github.liquec.gui.model.SessionModel; import io.github.liquec.gui.services.SessionFileService; import io.github.liquec.gui.status.GuiTask; import io.github.liquec.gui.status.StatusManager; import javafx.stage.Stage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.nio.file.Path; import javax.inject.Inject; import javax.inject.Singleton; @Singleton public class GuiFileHandler { private static final Logger LOG = LoggerFactory.getLogger(GuiFileHandler.class); private Stage stage; @Inject private FileDialogueFactory fileDialogueFactory; @Inject private SessionFileService sessionFileService; @Inject private StatusManager statusManager; @Inject private MainModel model; @Inject private SessionStateHandler sessionStateHandler; @Inject private GuiTaskHandler guiTaskHandler; public void initialise(final Stage stage) { this.stage = stage; } public boolean unsavedChangesCheck() { if (model.isChangesSaved()) { return true; } else { UnsavedChangesDialogue dialogue = new UnsavedChangesDialogue(model.getSessionFile()); dialogue.showDialogue(); switch (dialogue.getUserResponse()) { case SAVE: return saveChanges(); case DISCARD: return true; default: return false; } } } public void handleNewSession() { if (statusManager.beginNewSession()) { this.processNewSession(); } } private void processNewSession() { if (unsavedChangesCheck()) { statusManager.performAction(); LOG.info("New session from '{}'"); GuiTask<EnrichedSessionState> task = new GuiTask<>( guiTaskHandler, statusManager, () -> sessionFileService.createNewSession(), this::finishOpen, e -> new LiquEcException("Error creating new LiquEc session")); guiTaskHandler.executeInBackground(task); } else { statusManager.completeAction(); } } public void processOpenOrNew(final Path file) { if (statusManager.beginOpenSession()) { guiTaskHandler.pauseThenExecuteOnGuiThread(() -> processOpenOrNewInternal(file)); } } private void processOpenOrNewInternal(final Path file) { if (unsavedChangesCheck()) { LOG.info("Opening file '{}'", file); GuiTask<EnrichedSessionState> task = new GuiTask<>( guiTaskHandler, statusManager, () -> sessionFileService.createOrOpenSession(file), this::finishOpen, e -> FileErrorTool.open(file, e)); guiTaskHandler.executeInBackground(task); } else { statusManager.completeAction(); } } public void handleOpenSession() { if (statusManager.beginOpenSession()) { guiTaskHandler.pauseThenExecuteOnGuiThread(this::processOpenSession); } } private void processOpenSession() { if (unsavedChangesCheck()) { Path file = chooseFile(FileDialogueType.OPEN_SESSION); if (file == null) { statusManager.completeAction(); } else { statusManager.performAction(file); LOG.info("New session from '{}'", file); GuiTask<EnrichedSessionState> task = new GuiTask<>( guiTaskHandler, statusManager, () -> sessionFileService.createNewSession(file), this::finishOpen, e -> FileErrorTool.open(file, e)); guiTaskHandler.executeInBackground(task); } } else { statusManager.completeAction(); } } private void finishOpen(final EnrichedSessionState enrichedState) { SessionState state = enrichedState.getState(); SessionModel sessionModel = sessionStateHandler.addSession(state); model.replaceSessionModel(sessionModel, enrichedState.getFile().orElse(null)); } public void handleSave() { if (model.hasSessionFile()) { if (statusManager.beginSaveSession()) { guiTaskHandler.pauseThenExecuteOnGuiThread(this::processSave); } } else { handleSaveAs(); } } public void handleSaveAs() { if (statusManager.beginSaveSession()) { guiTaskHandler.pauseThenExecuteOnGuiThread(this::processSaveAs); } } private void processSaveAs() { Path file = chooseFile(FileDialogueType.SAVE_SESSION); if (file == null) { statusManager.completeAction(); } else { file = FileNameTool.ensureSessionFileHasSuffix(file); model.setSessionFile(file); processSave(); } } private void processSave() { Path file = model.getSessionFile(); statusManager.performAction(file); LOG.info("Saving file '{}'", file); GuiTask<Boolean> task = new GuiTask<>( guiTaskHandler, statusManager, () -> saveFile(file, sessionStateHandler.getSessionState()), b -> model.setChangesSaved(true), e -> FileErrorTool.save(file, e) ); guiTaskHandler.executeInBackground(task); } private boolean saveFile(final Path file, final SessionState sessionState) { sessionFileService.saveSession(file, sessionState); return true; } private boolean saveChanges() { if (model.hasSessionFile()) { saveChangesInternal(); return true; } else { return saveChangesAs(); } } private boolean saveChangesAs() { Path file = chooseFile(FileDialogueType.SAVE_SESSION); if (file == null) { return false; } else { file = FileNameTool.ensureSessionFileHasSuffix(file); model.setSessionFile(file); return saveChangesInternal(); } } private boolean saveChangesInternal() { Path file = model.getSessionFile(); try { LOG.info("Saving file '{}'", file); sessionFileService.saveSession(file, sessionStateHandler.getSessionState()); model.setChangesSaved(true); return true; } catch (final RuntimeException e) { FileErrorTool.save(file, e); return false; } } private Path chooseFile(final FileDialogueType type) { FileDialogue dialogue = fileDialogueFactory.create(type, stage); dialogue.showChooser(); if (dialogue.isFileSelected()) { return dialogue.getSelectedFile(); } else { return null; } } }
LiquEc/LiquEc
gui/src/main/java/io/github/liquec/gui/controller/GuiFileHandler.java
Java
gpl-2.0
7,527
<!DOCTYPE html> <html xml:lang="en-US" lang="en-US" xmlns="http://www.w3.org/1999/xhtml"> <head lang="en-US"> <title>My Family Tree - Floyd, Robert William</title> <meta charset="UTF-8" /> <meta name ="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=1" /> <meta name ="apple-mobile-web-app-capable" content="yes" /> <meta name="generator" content="Gramps 4.2.2 http://gramps-project.org/" /> <meta name="author" content="" /> <link href="../../../images/favicon2.ico" rel="shortcut icon" type="image/x-icon" /> <link href="../../../css/narrative-screen.css" media="screen" rel="stylesheet" type="text/css" /> <link href="../../../css/narrative-print.css" media="print" rel="stylesheet" type="text/css" /> <link href="../../../css/ancestortree.css" media="screen" rel="stylesheet" type="text/css" /> </head> <body> <div id="header"> <h1 id="SiteTitle">My Family Tree</h1> </div> <div class="wrapper" id="nav" role="navigation"> <div class="container"> <ul class="menu" id="dropmenu"> <li class = "CurrentSection"><a href="../../../individuals.html" title="Individuals">Individuals</a></li> <li><a href="../../../index.html" title="Surnames">Surnames</a></li> <li><a href="../../../places.html" title="Places">Places</a></li> <li><a href="../../../sources.html" title="Sources">Sources</a></li> <li><a href="../../../media.html" title="Media">Media</a></li> <li><a href="../../../thumbnails.html" title="Thumbnails">Thumbnails</a></li> </ul> </div> </div> <div class="content" id="IndividualDetail"> <h3>Floyd, Robert William<sup><small> <a href="#sref1">1</a></small></sup></h3> <div id="summaryarea"> <table class="infolist"> <tr> <td class="ColumnAttribute">Birth Name</td> <td class="ColumnValue"> Floyd, Robert William </td> </tr> <tr> <td class="ColumnAttribute">Gramps&nbsp;ID</td> <td class="ColumnValue">I0340</td> </tr> <tr> <td class="ColumnAttribute">Gender</td> <td class="ColumnValue">male</td> </tr> </table> </div> <div class="subsection" id="events"> <h4>Events</h4> <table class="infolist eventlist"> <thead> <tr> <th class="ColumnEvent">Event</th> <th class="ColumnDate">Date</th> <th class="ColumnPlace">Place</th> <th class="ColumnDescription">Description</th> <th class="ColumnNotes">Notes</th> <th class="ColumnSources">Sources</th> </tr> </thead> <tbody> <tr> <td class="ColumnEvent"> Birth </td> <td class="ColumnDate">1950-07-27</td> <td class="ColumnPlace">&nbsp;</td> <td class="ColumnDescription"> Birth of Floyd, Robert William </td> <td class="ColumnNotes"> <div> </div> </td> <td class="ColumnSources"> &nbsp; </td> </tr> <tr> <td class="ColumnEvent"> LVG </td> <td class="ColumnDate">&nbsp;</td> <td class="ColumnPlace">&nbsp;</td> <td class="ColumnDescription"> Custom FTW5 tag to specify LIVING not specified in GEDCOM 5.5 </td> <td class="ColumnNotes"> <div> </div> </td> <td class="ColumnSources"> &nbsp; </td> </tr> </tbody> </table> </div> <div class="subsection" id="families"> <h4>Families</h4> <table class="infolist"> <tr class="BeginFamily"> <td class="ColumnType">&nbsp</td> <td class="ColumnAttribute">&nbsp</td> <td class="ColumnValue"><a href="" title="Family of Floyd, Robert William and Данилов, Kathryn Louise">Family of Floyd, Robert William and Данилов, Kathryn Louise<span class="grampsid"> [F0058]</span></a></td> </tr> <tr class="BeginFamily"> <td class="ColumnType">Married</td> <td class="ColumnAttribute">Wife</td> <td class="ColumnValue"> <a href="../../../ppl/w/w/U5XJQCO3HY1XG4HSWW.html">Данилов, Kathryn Louise<span class="grampsid"> [I0167]</span></a> </td> </tr> <tr> <td class="ColumnType">&nbsp;</td> <td class="ColumnAttribute">&nbsp;</td> <td class="ColumnValue"> <table class="infolist eventlist"> <thead> <tr> <th class="ColumnEvent">Event</th> <th class="ColumnDate">Date</th> <th class="ColumnPlace">Place</th> <th class="ColumnDescription">Description</th> <th class="ColumnNotes">Notes</th> <th class="ColumnSources">Sources</th> </tr> </thead> <tbody> <tr> <td class="ColumnEvent"> Marriage </td> <td class="ColumnDate">1977-01-08</td> <td class="ColumnPlace">&nbsp;</td> <td class="ColumnDescription"> Marriage of Floyd, Robert William and Данилов, Kathryn Louise </td> <td class="ColumnNotes"> <div> </div> </td> <td class="ColumnSources"> &nbsp; </td> </tr> </tbody> </table> </td> <tr> <td class="ColumnType">&nbsp;</td> <td class="ColumnAttribute">Children</td> <td class="ColumnValue"> <ol> <li> <a href="../../../ppl/s/o/B20KQCRX6D76SH2OS.html">Floyd, Gregory Scott<span class="grampsid"> [I0341]</span></a> </li> <li> <a href="../../../ppl/8/p/030KQCA8ZLPDRK6PP8.html">Floyd, Christopher Randall<span class="grampsid"> [I0342]</span></a> </li> <li> <a href="../../../ppl/v/1/O30KQCD0N6D10XBV1V.html">Floyd, Joan Louise<span class="grampsid"> [I0343]</span></a> </li> </ol> </td> </tr> </tr> </table> </div> <div class="subsection" id="pedigree"> <h4>Pedigree</h4> <ol class="pedigreegen"> <li> <ol> <li class="thisperson"> Floyd, Robert William <ol class="spouselist"> <li class="spouse"> <a href="../../../ppl/w/w/U5XJQCO3HY1XG4HSWW.html">Данилов, Kathryn Louise<span class="grampsid"> [I0167]</span></a> <ol> <li> <a href="../../../ppl/s/o/B20KQCRX6D76SH2OS.html">Floyd, Gregory Scott<span class="grampsid"> [I0341]</span></a> </li> <li> <a href="../../../ppl/8/p/030KQCA8ZLPDRK6PP8.html">Floyd, Christopher Randall<span class="grampsid"> [I0342]</span></a> </li> <li> <a href="../../../ppl/v/1/O30KQCD0N6D10XBV1V.html">Floyd, Joan Louise<span class="grampsid"> [I0343]</span></a> </li> </ol> </li> </ol> </li> </ol> </li> </ol> </div> <div class="subsection" id="sourcerefs"> <h4>Source References</h4> <ol> <li> <a href="../../../src/x/a/X5TJQC9JXU4RKT6VAX.html" title="Import from test2.ged" name ="sref1"> Import from test2.ged <span class="grampsid"> [S0003]</span> </a> </li> </ol> </div> </div> <div class="fullclear"></div> <div id="footer"> <p id="createdate"> Generated by <a href="http://gramps-project.org/">Gramps</a> 4.2.2 on 2015-12-25<br />Last change was the 2007-07-26 08:34:25 </p> <p id="copyright"> </p> </div> </body> </html>
belissent/testing-example-reports
gramps42/gramps/example_NAVWEB0/ppl/i/t/Q10KQC7X2FR3F83ETI.html
HTML
gpl-2.0
7,258
package org.neuclear.signers.standalone.identitylists; import org.neuclear.commons.crypto.passphraseagents.icons.IconTools; import javax.swing.*; import javax.swing.tree.DefaultTreeCellRenderer; import java.awt.*; /* * The NeuClear Project and it's libraries are * (c) 2002-2004 Antilles Software Ventures SA * For more information see: http://neuclear.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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /** * User: pelleb * Date: May 15, 2004 * Time: 4:45:21 PM */ public class IdentityTreeCellRenderer extends DefaultTreeCellRenderer { public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) { final boolean isId = value instanceof IdentityNode; super.getTreeCellRendererComponent(tree, value, sel, expanded, isId, row, hasFocus); if (isId) { IdentityNode node = (IdentityNode) value; if (leaf && (node.getType() == IdentityNode.ASSET_TYPE)) { setIcon(assetIcon); } else if (leaf && (node.getType() == IdentityNode.ID_TYPE)) { setIcon(contactIcon); } setToolTipText(node.getDigest()); setText(node.getTitle()); } else { setToolTipText(null); //no tool tip } return this; } private Icon folderIcon = IconTools.loadIcon(this.getClass(), "org/neuclear/signers/standalone/icons/bookmark_folder.png"); private Icon contactIcon = IconTools.loadIcon(this.getClass(), "org/neuclear/signers/standalone/icons/contact.png"); private Icon assetIcon = IconTools.loadIcon(this.getClass(), "org/neuclear/signers/standalone/icons/asset.png"); }
pelle/neuclear-signer
src/java/org/neuclear/signers/standalone/identitylists/IdentityTreeCellRenderer.java
Java
gpl-2.0
2,759
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_17) on Mon Jan 11 20:33:46 NZDT 2010 --> <TITLE> SimpleLinkedList </TITLE> <META NAME="date" CONTENT="2010-01-11"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="SimpleLinkedList"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="http://www.cs.waikato.ac.nz/ml/weka/" target="_blank"><FONT CLASS="NavBarFont1"><B>Weka's home</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../weka/associations/tertius/Rule.html" title="class in weka.associations.tertius"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../weka/associations/tertius/SimpleLinkedList.LinkedListInverseIterator.html" title="class in weka.associations.tertius"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../index.html?weka/associations/tertius/SimpleLinkedList.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="SimpleLinkedList.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;<A HREF="#nested_class_summary">NESTED</A>&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <!-- ======== START OF CLASS DATA ======== --> <H2> <FONT SIZE="-1"> weka.associations.tertius</FONT> <BR> Class SimpleLinkedList</H2> <PRE> java.lang.Object <IMG SRC="../../../resources/inherit.gif" ALT="extended by "><B>weka.associations.tertius.SimpleLinkedList</B> </PRE> <DL> <DT><B>All Implemented Interfaces:</B> <DD>java.io.Serializable, <A HREF="../../../weka/core/RevisionHandler.html" title="interface in weka.core">RevisionHandler</A></DD> </DL> <HR> <DL> <DT><PRE>public class <B>SimpleLinkedList</B><DT>extends java.lang.Object<DT>implements java.io.Serializable, <A HREF="../../../weka/core/RevisionHandler.html" title="interface in weka.core">RevisionHandler</A></DL> </PRE> <P> <DL> <DT><B>Version:</B></DT> <DD>$Revision: 1.6 $</DD> <DT><B>Author:</B></DT> <DD>Peter A. Flach, Nicolas Lachiche</DD> <DT><B>See Also:</B><DD><A HREF="../../../serialized-form.html#weka.associations.tertius.SimpleLinkedList">Serialized Form</A></DL> <HR> <P> <!-- ======== NESTED CLASS SUMMARY ======== --> <A NAME="nested_class_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Nested Class Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;class</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../weka/associations/tertius/SimpleLinkedList.LinkedListInverseIterator.html" title="class in weka.associations.tertius">SimpleLinkedList.LinkedListInverseIterator</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;class</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../weka/associations/tertius/SimpleLinkedList.LinkedListIterator.html" title="class in weka.associations.tertius">SimpleLinkedList.LinkedListIterator</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <!-- ======== CONSTRUCTOR SUMMARY ======== --> <A NAME="constructor_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Constructor Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><B><A HREF="../../../weka/associations/tertius/SimpleLinkedList.html#SimpleLinkedList()">SimpleLinkedList</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <!-- ========== METHOD SUMMARY =========== --> <A NAME="method_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Method Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../weka/associations/tertius/SimpleLinkedList.html#add(java.lang.Object)">add</A></B>(java.lang.Object&nbsp;o)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../weka/associations/tertius/SimpleLinkedList.html#addAll(weka.associations.tertius.SimpleLinkedList)">addAll</A></B>(<A HREF="../../../weka/associations/tertius/SimpleLinkedList.html" title="class in weka.associations.tertius">SimpleLinkedList</A>&nbsp;list)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../weka/associations/tertius/SimpleLinkedList.html#addFirst(java.lang.Object)">addFirst</A></B>(java.lang.Object&nbsp;o)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../weka/associations/tertius/SimpleLinkedList.html#clear()">clear</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;java.lang.Object</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../weka/associations/tertius/SimpleLinkedList.html#getFirst()">getFirst</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;java.lang.Object</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../weka/associations/tertius/SimpleLinkedList.html#getLast()">getLast</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;java.lang.String</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../weka/associations/tertius/SimpleLinkedList.html#getRevision()">getRevision</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Returns the revision string.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../weka/associations/tertius/SimpleLinkedList.LinkedListInverseIterator.html" title="class in weka.associations.tertius">SimpleLinkedList.LinkedListInverseIterator</A></CODE></FONT></TD> <TD><CODE><B><A HREF="../../../weka/associations/tertius/SimpleLinkedList.html#inverseIterator()">inverseIterator</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;boolean</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../weka/associations/tertius/SimpleLinkedList.html#isEmpty()">isEmpty</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../weka/associations/tertius/SimpleLinkedList.LinkedListIterator.html" title="class in weka.associations.tertius">SimpleLinkedList.LinkedListIterator</A></CODE></FONT></TD> <TD><CODE><B><A HREF="../../../weka/associations/tertius/SimpleLinkedList.html#iterator()">iterator</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../weka/associations/tertius/SimpleLinkedList.html#merge(weka.associations.tertius.SimpleLinkedList, java.util.Comparator)">merge</A></B>(<A HREF="../../../weka/associations/tertius/SimpleLinkedList.html" title="class in weka.associations.tertius">SimpleLinkedList</A>&nbsp;list, java.util.Comparator&nbsp;comp)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;java.lang.Object</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../weka/associations/tertius/SimpleLinkedList.html#removeFirst()">removeFirst</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;int</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../weka/associations/tertius/SimpleLinkedList.html#size()">size</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../weka/associations/tertius/SimpleLinkedList.html#sort(java.util.Comparator)">sort</A></B>(java.util.Comparator&nbsp;comp)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;java.lang.String</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../weka/associations/tertius/SimpleLinkedList.html#toString()">toString</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp;<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left"><B>Methods inherited from class java.lang.Object</B></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE>equals, getClass, hashCode, notify, notifyAll, wait, wait, wait</CODE></TD> </TR> </TABLE> &nbsp; <P> <!-- ========= CONSTRUCTOR DETAIL ======== --> <A NAME="constructor_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Constructor Detail</B></FONT></TH> </TR> </TABLE> <A NAME="SimpleLinkedList()"><!-- --></A><H3> SimpleLinkedList</H3> <PRE> public <B>SimpleLinkedList</B>()</PRE> <DL> </DL> <!-- ============ METHOD DETAIL ========== --> <A NAME="method_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Method Detail</B></FONT></TH> </TR> </TABLE> <A NAME="removeFirst()"><!-- --></A><H3> removeFirst</H3> <PRE> public java.lang.Object <B>removeFirst</B>()</PRE> <DL> <DD><DL> </DL> </DD> <DD><DL> </DL> </DD> </DL> <HR> <A NAME="getFirst()"><!-- --></A><H3> getFirst</H3> <PRE> public java.lang.Object <B>getFirst</B>()</PRE> <DL> <DD><DL> </DL> </DD> <DD><DL> </DL> </DD> </DL> <HR> <A NAME="getLast()"><!-- --></A><H3> getLast</H3> <PRE> public java.lang.Object <B>getLast</B>()</PRE> <DL> <DD><DL> </DL> </DD> <DD><DL> </DL> </DD> </DL> <HR> <A NAME="addFirst(java.lang.Object)"><!-- --></A><H3> addFirst</H3> <PRE> public void <B>addFirst</B>(java.lang.Object&nbsp;o)</PRE> <DL> <DD><DL> </DL> </DD> <DD><DL> </DL> </DD> </DL> <HR> <A NAME="add(java.lang.Object)"><!-- --></A><H3> add</H3> <PRE> public void <B>add</B>(java.lang.Object&nbsp;o)</PRE> <DL> <DD><DL> </DL> </DD> <DD><DL> </DL> </DD> </DL> <HR> <A NAME="addAll(weka.associations.tertius.SimpleLinkedList)"><!-- --></A><H3> addAll</H3> <PRE> public void <B>addAll</B>(<A HREF="../../../weka/associations/tertius/SimpleLinkedList.html" title="class in weka.associations.tertius">SimpleLinkedList</A>&nbsp;list)</PRE> <DL> <DD><DL> </DL> </DD> <DD><DL> </DL> </DD> </DL> <HR> <A NAME="clear()"><!-- --></A><H3> clear</H3> <PRE> public void <B>clear</B>()</PRE> <DL> <DD><DL> </DL> </DD> <DD><DL> </DL> </DD> </DL> <HR> <A NAME="isEmpty()"><!-- --></A><H3> isEmpty</H3> <PRE> public boolean <B>isEmpty</B>()</PRE> <DL> <DD><DL> </DL> </DD> <DD><DL> </DL> </DD> </DL> <HR> <A NAME="iterator()"><!-- --></A><H3> iterator</H3> <PRE> public <A HREF="../../../weka/associations/tertius/SimpleLinkedList.LinkedListIterator.html" title="class in weka.associations.tertius">SimpleLinkedList.LinkedListIterator</A> <B>iterator</B>()</PRE> <DL> <DD><DL> </DL> </DD> <DD><DL> </DL> </DD> </DL> <HR> <A NAME="inverseIterator()"><!-- --></A><H3> inverseIterator</H3> <PRE> public <A HREF="../../../weka/associations/tertius/SimpleLinkedList.LinkedListInverseIterator.html" title="class in weka.associations.tertius">SimpleLinkedList.LinkedListInverseIterator</A> <B>inverseIterator</B>()</PRE> <DL> <DD><DL> </DL> </DD> <DD><DL> </DL> </DD> </DL> <HR> <A NAME="size()"><!-- --></A><H3> size</H3> <PRE> public int <B>size</B>()</PRE> <DL> <DD><DL> </DL> </DD> <DD><DL> </DL> </DD> </DL> <HR> <A NAME="merge(weka.associations.tertius.SimpleLinkedList, java.util.Comparator)"><!-- --></A><H3> merge</H3> <PRE> public void <B>merge</B>(<A HREF="../../../weka/associations/tertius/SimpleLinkedList.html" title="class in weka.associations.tertius">SimpleLinkedList</A>&nbsp;list, java.util.Comparator&nbsp;comp)</PRE> <DL> <DD><DL> </DL> </DD> <DD><DL> </DL> </DD> </DL> <HR> <A NAME="sort(java.util.Comparator)"><!-- --></A><H3> sort</H3> <PRE> public void <B>sort</B>(java.util.Comparator&nbsp;comp)</PRE> <DL> <DD><DL> </DL> </DD> <DD><DL> </DL> </DD> </DL> <HR> <A NAME="toString()"><!-- --></A><H3> toString</H3> <PRE> public java.lang.String <B>toString</B>()</PRE> <DL> <DD><DL> <DT><B>Overrides:</B><DD><CODE>toString</CODE> in class <CODE>java.lang.Object</CODE></DL> </DD> <DD><DL> </DL> </DD> </DL> <HR> <A NAME="getRevision()"><!-- --></A><H3> getRevision</H3> <PRE> public java.lang.String <B>getRevision</B>()</PRE> <DL> <DD>Returns the revision string. <P> <DD><DL> <DT><B>Specified by:</B><DD><CODE><A HREF="../../../weka/core/RevisionHandler.html#getRevision()">getRevision</A></CODE> in interface <CODE><A HREF="../../../weka/core/RevisionHandler.html" title="interface in weka.core">RevisionHandler</A></CODE></DL> </DD> <DD><DL> <DT><B>Returns:</B><DD>the revision</DL> </DD> </DL> <!-- ========= END OF CLASS DATA ========= --> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="http://www.cs.waikato.ac.nz/ml/weka/" target="_blank"><FONT CLASS="NavBarFont1"><B>Weka's home</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../weka/associations/tertius/Rule.html" title="class in weka.associations.tertius"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../weka/associations/tertius/SimpleLinkedList.LinkedListInverseIterator.html" title="class in weka.associations.tertius"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../index.html?weka/associations/tertius/SimpleLinkedList.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="SimpleLinkedList.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;<A HREF="#nested_class_summary">NESTED</A>&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> </BODY> </HTML>
chrissalij/Wiki-Reputation-Predictor
weka/doc/weka/associations/tertius/SimpleLinkedList.html
HTML
gpl-2.0
20,838
<?php // +----------------------------------------------------------------------+ // | Copyright Incsub (http://incsub.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 | // +----------------------------------------------------------------------+ /** * Rule class responsible for BuddyPress friendship protection. * * @since 3.5 * * @category Membership * @package Model * @subpackage Rule * @subpackage Buddypress */ class Membership_Model_Rule_Buddypress_Friendship extends Membership_Model_Rule { /** * Handles rule's stuff initialization. * * @access public */ public function on_creation() { parent::on_creation(); $this->name = 'bpfriendship'; $this->label = __( 'Friend Connections', 'membership' ); $this->description = __( 'Allows the sending friendship requests to be limited to members.', 'membership' ); $this->rulearea = 'public'; } /** * Renders rule settings at access level edit form. * * @access public * @param mixed $data The data associated with this rule. */ public function admin_main( $data ) { ?><div class="level-operation" id="main-bpfriendship"> <h2 class="sidebar-name"> <?php _e( 'Friend Connections', 'membership' ); ?> <span><a href="#remove" id="remove-bpfriendship" class="removelink" title="<?php _e( "Remove Private Messaging from this rules area.", 'membership' ); ?>"> <?php _e( 'Remove', 'membership' ); ?> </a></span> </h2> <div class="inner-operation"> <p><strong><?php _e( 'Positive:', 'membership' ); ?></strong> <?php _e( 'User can send friendship requests.', 'membership' ); ?></p> <p><strong><?php _e( 'Negative:', 'membership' ); ?></strong> <?php _e( 'User is unable to send friendship requests.', 'membership' ); ?></p> <input type="hidden" name="bpfriendship[]" value="yes"> </div> </div><?php } /** * Associates negative data with this rule. * * @access public * @param mixed $data The negative data to associate with the rule. */ public function on_negative( $data ) { $this->data = $data; add_filter( 'bp_get_add_friend_button', array( $this, 'hide_add_friend_button' ) ); add_filter( 'bp_get_template_part', array( $this, 'get_friends_template' ), 10, 2 ); } /** * Adds filter to prevent friendship button rendering. * * @since 3.5 * @filter bp_get_add_friend_button * * @access public * @param array $button The button settings. * @return array The current button settings. */ public function hide_add_friend_button( $button ) { add_filter( 'bp_get_button', array( $this, 'prevent_button_rendering' ) ); return $button; } /** * Prevents button rendering. * * @since 3.5 * @filter bp_get_button * * @access public * @return boolean FALSE to prevent button rendering. */ public function prevent_button_rendering() { remove_filter( 'bp_get_button', array( $this, 'prevent_button_rendering' ) ); return false; } /** * Overrides friends template. * * @filter bp_get_template_part 10 2 * * @access public * @param array $templates Income templates. * @param string $slug The template slug. * @return array The new template for friends pages or original for else pages. */ public function get_friends_template( $templates, $slug ) { if ( $slug != 'members/single/friends' ) { return $templates; } add_action( 'bp_template_content', array( $this, 'render_protection_message' ) ); return array( 'members/single/plugins.php' ); } /** * Renders protection message. * * @action bp_template_content * * @access public */ public function render_protection_message() { if ( defined( 'MEMBERSHIP_GLOBAL_TABLES' ) && MEMBERSHIP_GLOBAL_TABLES === true ) { $MBP_options = function_exists( 'get_blog_option' ) ? get_blog_option( MEMBERSHIP_GLOBAL_MAINSITE, 'membership_bp_options', array() ) : get_option( 'membership_bp_options', array() ); } else { $MBP_options = get_option( 'membership_bp_options', array( ) ); } echo '<div id="message" class="error"><p>' . stripslashes( $MBP_options['buddypressmessage'] ) . '</p></div>'; } }
MississippiGreetings/wordpress
wp-content/plugins/membership/classes/Membership/Model/Rule/Buddypress/Friendship.php
PHP
gpl-2.0
5,300
namespace hitchbotAPI.Areas.HelpPage.ModelDescriptions { public class DictionaryModelDescription : KeyValuePairModelDescription { } }
macGRID-SRN/hitchBOT
server/hitchbotAPI/hitchbotAPI/Areas/HelpPage/ModelDescriptions/DictionaryModelDescription.cs
C#
gpl-2.0
145
/* * This file is part of CrappyDB-Server, * developed by Luca Bonmassar <luca.bonmassar at gmail.com> * * CrappyDB-Server 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. * * CrappyDB-Server 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 CrappyDB-Server. If not, see <http://www.gnu.org/licenses/>. */ package org.bonmassar.crappydb.server.storage.berkley; import org.bonmassar.crappydb.server.storage.data.DeleteItem; import org.bonmassar.crappydb.server.storage.data.Item; import org.bonmassar.crappydb.server.storage.data.Key; import com.sleepycat.persist.model.Entity; import com.sleepycat.persist.model.PrimaryKey; @Entity public class ItemEntity { @PrimaryKey private String primaryKey; private byte[] payload; private int flags; private long expiration; private boolean deleted; ItemEntity(){ //injection constructor } public ItemEntity(final Item item){ if(null == item) throw new NullPointerException(); primaryKey = item.getKey().toString(); payload = item.getData(); flags = item.getFlags(); expiration = item.getExpire(); deleted = item instanceof DeleteItem; } public Item toItem() { Item it = new Item(new Key(primaryKey), payload, flags, expiration); if(!deleted) return it; return new DeleteItem(it); } public String getPrimaryKey() { return primaryKey; } public long getExpiration() { return expiration; } public int getFlags() { return flags; } }
openmosix/crappydb
src/main/java/org/bonmassar/crappydb/server/storage/berkley/ItemEntity.java
Java
gpl-2.0
1,917
/* packet-smtp.c * Routines for SMTP packet disassembly * * $Id: packet-smtp.c 50472 2013-07-09 20:35:26Z mmann $ * * Copyright (c) 2000 by Richard Sharpe <rsharpe@ns.aus.com> * * Added RFC 4954 SMTP Authentication * Michael Mann * Copyright 2012 * * Wireshark - Network traffic analyzer * By Gerald Combs <gerald@wireshark.org> * Copyright 1999 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 <stdlib.h> #include <ctype.h> #include <glib.h> #include <epan/packet.h> #include <epan/conversation.h> #include <epan/prefs.h> #include <epan/strutil.h> #include <epan/wmem/wmem.h> #include <epan/reassemble.h> #include <epan/base64.h> #include <epan/dissectors/packet-ssl.h> /* RFC 2821 */ #define TCP_PORT_SMTP 25 #define TCP_PORT_SSL_SMTP 465 /* RFC 4409 */ #define TCP_PORT_SUBMISSION 587 static int proto_smtp = -1; static int hf_smtp_req = -1; static int hf_smtp_rsp = -1; static int hf_smtp_message = -1; static int hf_smtp_command_line = -1; static int hf_smtp_req_command = -1; static int hf_smtp_req_parameter = -1; static int hf_smtp_response = -1; static int hf_smtp_rsp_code = -1; static int hf_smtp_rsp_parameter = -1; static int hf_smtp_username = -1; static int hf_smtp_password = -1; static int hf_smtp_data_fragments = -1; static int hf_smtp_data_fragment = -1; static int hf_smtp_data_fragment_overlap = -1; static int hf_smtp_data_fragment_overlap_conflicts = -1; static int hf_smtp_data_fragment_multiple_tails = -1; static int hf_smtp_data_fragment_too_long_fragment = -1; static int hf_smtp_data_fragment_error = -1; static int hf_smtp_data_fragment_count = -1; static int hf_smtp_data_reassembled_in = -1; static int hf_smtp_data_reassembled_length = -1; static int ett_smtp = -1; static int ett_smtp_cmdresp = -1; static gint ett_smtp_data_fragment = -1; static gint ett_smtp_data_fragments = -1; static gboolean stmp_decryption_enabled = FALSE; /* desegmentation of SMTP command and response lines */ static gboolean smtp_desegment = TRUE; static gboolean smtp_data_desegment = TRUE; static reassembly_table smtp_data_reassembly_table; static const fragment_items smtp_data_frag_items = { /* Fragment subtrees */ &ett_smtp_data_fragment, &ett_smtp_data_fragments, /* Fragment fields */ &hf_smtp_data_fragments, &hf_smtp_data_fragment, &hf_smtp_data_fragment_overlap, &hf_smtp_data_fragment_overlap_conflicts, &hf_smtp_data_fragment_multiple_tails, &hf_smtp_data_fragment_too_long_fragment, &hf_smtp_data_fragment_error, &hf_smtp_data_fragment_count, /* Reassembled in field */ &hf_smtp_data_reassembled_in, /* Reassembled length field */ &hf_smtp_data_reassembled_length, /* Reassembled data field */ NULL, /* Tag */ "DATA fragments" }; static dissector_handle_t ssl_handle; static dissector_handle_t imf_handle; static dissector_handle_t ntlmssp_handle; /* * A CMD is an SMTP command, MESSAGE is the message portion, and EOM is the * last part of a message */ #define SMTP_PDU_CMD 0 #define SMTP_PDU_MESSAGE 1 #define SMTP_PDU_EOM 2 struct smtp_proto_data { guint16 pdu_type; guint16 conversation_id; gboolean more_frags; }; /* * State information stored with a conversation. */ typedef enum { SMTP_STATE_READING_CMDS, /* reading commands */ SMTP_STATE_READING_DATA, /* reading message data */ SMTP_STATE_AWAITING_STARTTLS_RESPONSE /* sent STARTTLS, awaiting response */ } smtp_state_t; typedef enum { SMTP_AUTH_STATE_NONE, /* No authentication seen or used */ SMTP_AUTH_STATE_START, /* Authentication started, waiting for username */ SMTP_AUTH_STATE_USERNAME_REQ, /* Received username request from server */ SMTP_AUTH_STATE_USERNAME_RSP, /* Received username response from client */ SMTP_AUTH_STATE_PASSWORD_REQ, /* Received password request from server */ SMTP_AUTH_STATE_PASSWORD_RSP, /* Received password request from server */ SMTP_AUTH_STATE_PLAIN_START_REQ, /* Received AUTH PLAIN command from client*/ SMTP_AUTH_STATE_PLAIN_CRED_REQ, /* Received AUTH PLAIN command including creds from client*/ SMTP_AUTH_STATE_PLAIN_REQ, /* Received AUTH PLAIN request from server */ SMTP_AUTH_STATE_PLAIN_RSP, /* Received AUTH PLAIN response from client */ SMTP_AUTH_STATE_NTLM_REQ, /* Received ntlm negotiate request from client */ SMTP_AUTH_STATE_NTLM_CHALLANGE, /* Received ntlm challange request from server */ SMTP_AUTH_STATE_NTLM_RSP, /* Received ntlm auth request from client */ SMTP_AUTH_STATE_SUCCESS, /* Password received, authentication successful, start decoding */ SMTP_AUTH_STATE_FAILED, /* authentication failed, no decoding */ } smtp_auth_state_t; struct smtp_session_state { smtp_state_t smtp_state; /* Current state */ smtp_auth_state_t auth_state; /* Current authentication state */ /* Values that need to be saved because state machine can't be used during tree dissection */ guint32 first_auth_frame; /* First frame involving authentication. */ guint32 username_frame; /* Frame containing client username */ guint32 password_frame; /* Frame containing client password */ guint32 last_auth_frame; /* Last frame involving authentication. */ gboolean crlf_seen; /* Have we seen a CRLF on the end of a packet */ gboolean data_seen; /* Have we seen a DATA command yet */ guint32 msg_read_len; /* Length of BDAT message read so far */ guint32 msg_tot_len; /* Total length of BDAT message */ gboolean msg_last; /* Is this the last BDAT chunk */ guint32 last_nontls_frame; /* last non-TLS frame; 0 if not known or no TLS */ guint32 username_cmd_frame; /* AUTH command contains username */ guint32 user_pass_cmd_frame; /* AUTH command contains username and password */ guint32 user_pass_frame; /* Frame contains username and password */ guint32 ntlm_req_frame; /* Frame containing NTLM request */ guint32 ntlm_cha_frame; /* Frame containing NTLM challange. */ guint32 ntlm_rsp_frame; /* Frame containing NTLM response. */ }; /* * See * * http://support.microsoft.com/default.aspx?scid=kb;[LN];812455 * * for the Exchange extensions. */ static const struct { const char *command; int len; } commands[] = { { "STARTTLS", 8 }, /* RFC 2487 */ { "X-EXPS", 6 }, /* Microsoft Exchange */ { "X-LINK2STATE", 12 }, /* Microsoft Exchange */ { "XEXCH50", 7 } /* Microsoft Exchange */ }; #define NCOMMANDS (sizeof commands / sizeof commands[0]) /* The following were copied from RFC 2821 */ static const value_string response_codes_vs[] = { { 211, "System status, or system help reply" }, { 214, "Help message" }, { 220, "<domain> Service ready" }, { 221, "<domain> Service closing transmission channel" }, { 235, "Authentication successful" }, { 250, "Requested mail action okay, completed" }, { 251, "User not local; will forward to <forward-path>" }, { 252, "Cannot VRFY user, but will accept message and attempt delivery" }, { 334, "AUTH input" }, { 354, "Start mail input; end with <CRLF>.<CRLF>" }, { 421, "<domain> Service not available, closing transmission channel" }, { 432, "A password transition is needed" }, { 450, "Requested mail action not taken: mailbox unavailable" }, { 451, "Requested action aborted: local error in processing" }, { 452, "Requested action not taken: insufficient system storage" }, { 454, "Temporary authenticaion failed" }, { 500, "Syntax error, command unrecognized" }, { 501, "Syntax error in parameters or arguments" }, { 502, "Command not implemented" }, { 503, "Bad sequence of commands" }, { 504, "Command parameter not implemented" }, { 530, "Authentication required" }, { 534, "Authentication mechanism is too weak" }, { 535, "Authentication credentials invalid" }, { 538, "Encryption required for requested authentication mechanism" }, { 550, "Requested action not taken: mailbox unavailable" }, { 551, "User not local; please try <forward-path>" }, { 552, "Requested mail action aborted: exceeded storage allocation" }, { 553, "Requested action not taken: mailbox name not allowed" }, { 554, "Transaction failed" }, { 0, NULL } }; static value_string_ext response_codes_vs_ext = VALUE_STRING_EXT_INIT(response_codes_vs); static gboolean line_is_smtp_command(const guchar *command, int commandlen) { size_t i; /* * To quote RFC 821, "Command codes are four alphabetic * characters". * * However, there are some SMTP extensions that involve commands * longer than 4 characters and/or that contain non-alphabetic * characters; we treat them specially. * * XXX - should we just have a table of known commands? Or would * that fail to catch some extensions we don't know about? */ if (commandlen == 4 && g_ascii_isalpha(command[0]) && g_ascii_isalpha(command[1]) && g_ascii_isalpha(command[2]) && g_ascii_isalpha(command[3])) { /* standard 4-alphabetic command */ return TRUE; } /* * Check the list of non-4-alphabetic commands. */ for (i = 0; i < NCOMMANDS; i++) { if (commandlen == commands[i].len && g_ascii_strncasecmp(command, commands[i].command, commands[i].len) == 0) return TRUE; } return FALSE; } static void dissect_smtp_data(tvbuff_t *tvb, int offset, proto_tree *smtp_tree) { gint next_offset; if (smtp_tree) { while (tvb_offset_exists(tvb, offset)) { /* * Find the end of the line. */ tvb_find_line_end(tvb, offset, -1, &next_offset, FALSE); /* * Put this line. */ proto_tree_add_item(smtp_tree, hf_smtp_message, tvb, offset, next_offset - offset, ENC_ASCII|ENC_NA); /* * Step to the next line. */ offset = next_offset; } } } static void dissect_ntlm_auth(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, const char *line) { tvbuff_t *ntlm_tvb; ntlm_tvb = base64_to_tvb(tvb, line); if(tvb_strneql(ntlm_tvb, 0, "NTLMSSP", 7) == 0) { add_new_data_source(pinfo, ntlm_tvb, "NTLMSSP Data"); call_dissector(ntlmssp_handle, ntlm_tvb, pinfo, tree); } } static void decode_plain_auth(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, gint a_offset, int a_linelen) { gint returncode; gint length_user1; gint length_user2; gint length_pass; guint8 *decrypt = NULL; decrypt = tvb_get_ephemeral_string(tvb, a_offset, a_linelen); if (stmp_decryption_enabled) { returncode = (gint)epan_base64_decode(decrypt); if (returncode) { length_user1 = (gint)strlen(decrypt); if (returncode >= (length_user1 + 1)) { length_user2 = (gint)strlen(decrypt + length_user1 + 1); proto_tree_add_string(tree, hf_smtp_username, tvb, a_offset, a_linelen, decrypt + length_user1 + 1); col_append_fstr(pinfo->cinfo, COL_INFO, "User: %s", decrypt + length_user1 + 1); if (returncode >= (length_user1 + 1 + length_user2 + 1)) { length_pass = (gint)strlen(decrypt + length_user1 + length_user2 + 2); proto_tree_add_string(tree, hf_smtp_password, tvb, a_offset, length_pass, decrypt + length_user1 + length_user2 + 2); col_append_str(pinfo->cinfo, COL_INFO, " "); col_append_fstr(pinfo->cinfo, COL_INFO, " Pass: %s", decrypt + length_user1 + length_user2 + 2); } } } } else { proto_tree_add_string(tree, hf_smtp_username, tvb, a_offset, a_linelen, decrypt); proto_tree_add_string(tree, hf_smtp_password, tvb, a_offset, a_linelen, decrypt); col_append_str(pinfo->cinfo, COL_INFO, decrypt); } } static void dissect_smtp(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree) { struct smtp_proto_data *spd_frame_data; proto_tree *smtp_tree = NULL; proto_tree *cmdresp_tree = NULL; proto_item *ti, *hidden_item; int offset = 0; int request = 0; conversation_t *conversation; struct smtp_session_state *session_state; const guchar *line, *linep, *lineend; guint32 code; int linelen = 0; gint length_remaining; gboolean eom_seen = FALSE; gint next_offset; gint loffset = 0; int cmdlen; fragment_data *frag_msg = NULL; tvbuff_t *next_tvb; guint8 *decrypt = NULL; guint8 *base64_string = NULL; guint8 line_code[3]; /* As there is no guarantee that we will only see frames in the * the SMTP conversation once, and that we will see them in * order - in Wireshark, the user could randomly click on frames * in the conversation in any order in which they choose - we * have to store information with each frame indicating whether * it contains commands or data or an EOM indication. * * XXX - what about frames that contain *both*? TCP is a * byte-stream protocol, and there are no guarantees that * TCP segment boundaries will correspond to SMTP commands * or EOM indications. * * We only need that for the client->server stream; responses * are easy to manage. * * If we have per frame data, use that, else, we must be on the first * pass, so we figure it out on the first pass. */ /* * Find or create the conversation for this. */ conversation = find_or_create_conversation(pinfo); /* * Is there a request structure attached to this conversation? */ session_state = (struct smtp_session_state *)conversation_get_proto_data(conversation, proto_smtp); if (!session_state) { /* * No - create one and attach it. */ session_state = (struct smtp_session_state *)wmem_alloc0(wmem_file_scope(), sizeof(struct smtp_session_state)); session_state->smtp_state = SMTP_STATE_READING_CMDS; session_state->auth_state = SMTP_AUTH_STATE_NONE; session_state->msg_last = TRUE; conversation_add_proto_data(conversation, proto_smtp, session_state); } /* Are we doing TLS? * FIXME In my understanding of RFC 2487 client and server can send SMTP cmds * after a rejected TLS negotiation */ if (session_state->last_nontls_frame != 0 && pinfo->fd->num > session_state->last_nontls_frame) { guint16 save_can_desegment; guint32 save_last_nontls_frame; /* This is TLS, not raw SMTP. TLS can desegment */ save_can_desegment = pinfo->can_desegment; pinfo->can_desegment = pinfo->saved_can_desegment; /* Make sure the SSL dissector will not be called again after decryption */ save_last_nontls_frame = session_state->last_nontls_frame; session_state->last_nontls_frame = 0; call_dissector(ssl_handle, tvb, pinfo, tree); pinfo->can_desegment = save_can_desegment; session_state->last_nontls_frame = save_last_nontls_frame; return; } /* Is this a request or a response? */ request = pinfo->destport == pinfo->match_uint; /* * Is there any data attached to this frame? */ spd_frame_data = (struct smtp_proto_data *)p_get_proto_data(pinfo->fd, proto_smtp, 0); if (!spd_frame_data) { /* * No frame data. */ if (request) { /* * Create a frame data structure and attach it to the packet. */ spd_frame_data = (struct smtp_proto_data *)wmem_alloc0(wmem_file_scope(), sizeof(struct smtp_proto_data)); spd_frame_data->conversation_id = conversation->index; spd_frame_data->more_frags = TRUE; p_add_proto_data(pinfo->fd, proto_smtp, 0, spd_frame_data); } /* * Get the first line from the buffer. * * Note that "tvb_find_line_end()" will, if it doesn't return * -1, return a value that is not longer than what's in the buffer, * and "tvb_find_line_end()" will always return a value that is not * longer than what's in the buffer, so the "tvb_get_ptr()" call * won't throw an exception. */ loffset = offset; while (tvb_offset_exists(tvb, loffset)) { linelen = tvb_find_line_end(tvb, loffset, -1, &next_offset, smtp_desegment && pinfo->can_desegment); if (linelen == -1) { if (offset == loffset) { /* * We didn't find a line ending, and we're doing desegmentation; * tell the TCP dissector where the data for this message starts * in the data it handed us, and tell it we need more bytes */ pinfo->desegment_offset = loffset; pinfo->desegment_len = DESEGMENT_ONE_MORE_SEGMENT; return; } else { linelen = tvb_length_remaining(tvb, loffset); next_offset = loffset + linelen; } } /* * Check whether or not this packet is an end of message packet * We should look for CRLF.CRLF and they may be split. * We have to keep in mind that we may see what we want on * two passes through here ... */ if (session_state->smtp_state == SMTP_STATE_READING_DATA) { /* * The order of these is important ... We want to avoid * cases where there is a CRLF at the end of a packet and a * .CRLF at the beginning of the same packet. */ if ((session_state->crlf_seen && tvb_strneql(tvb, loffset, ".\r\n", 3) == 0) || tvb_strneql(tvb, loffset, "\r\n.\r\n", 5) == 0) eom_seen = TRUE; length_remaining = tvb_length_remaining(tvb, loffset); if (length_remaining == tvb_reported_length_remaining(tvb, loffset) && tvb_strneql(tvb, loffset + length_remaining - 2, "\r\n", 2) == 0) session_state->crlf_seen = TRUE; else session_state->crlf_seen = FALSE; } /* * OK, Check if we have seen a DATA request. We do it here for * simplicity, but we have to be careful below. */ if (request) { if (session_state->smtp_state == SMTP_STATE_READING_DATA) { /* * This is message data. */ if (eom_seen) { /* Seen the EOM */ /* * EOM. * Everything that comes after it is commands. */ spd_frame_data->pdu_type = SMTP_PDU_EOM; session_state->smtp_state = SMTP_STATE_READING_CMDS; break; } else { /* * Message data with no EOM. */ spd_frame_data->pdu_type = SMTP_PDU_MESSAGE; if (session_state->msg_tot_len > 0) { /* * We are handling a BDAT message. * Check if we have reached end of the data chunk. */ session_state->msg_read_len += tvb_length_remaining(tvb, loffset); if (session_state->msg_read_len == session_state->msg_tot_len) { /* * We have reached end of BDAT data chunk. * Everything that comes after this is commands. */ session_state->smtp_state = SMTP_STATE_READING_CMDS; if (session_state->msg_last) { /* * We have found the LAST data chunk. * The message can now be reassembled. */ spd_frame_data->more_frags = FALSE; } break; /* no need to go through the remaining lines */ } } } } else { /* * This is commands - unless the capture started in the * middle of a session, and we're in the middle of data. * * Commands are not necessarily 4 characters; look * for a space or the end of the line to see where * the putative command ends. */ if ((session_state->auth_state != SMTP_AUTH_STATE_NONE) && (pinfo->fd->num >= session_state->first_auth_frame) && ((session_state->last_auth_frame == 0) || (pinfo->fd->num <= session_state->last_auth_frame))) { decrypt = tvb_get_ephemeral_string(tvb, loffset, linelen); if ((stmp_decryption_enabled) && (epan_base64_decode(decrypt) > 0)) { line = decrypt; } else { line = tvb_get_ptr(tvb, loffset, linelen); } } else { line = tvb_get_ptr(tvb, loffset, linelen); } linep = line; lineend = line + linelen; while (linep < lineend && *linep != ' ') linep++; cmdlen = (int)(linep - line); if (line_is_smtp_command(line, cmdlen)) { if (g_ascii_strncasecmp(line, "DATA", 4) == 0) { /* * DATA command. * This is a command, but everything that comes after it, * until an EOM, is data. */ spd_frame_data->pdu_type = SMTP_PDU_CMD; session_state->smtp_state = SMTP_STATE_READING_DATA; session_state->data_seen = TRUE; } else if (g_ascii_strncasecmp(line, "BDAT", 4) == 0) { /* * BDAT command. * This is a command, but everything that comes after it, * until given length is received, is data. */ guint32 msg_len; msg_len = (guint32)strtoul (line+5, NULL, 10); spd_frame_data->pdu_type = SMTP_PDU_CMD; session_state->data_seen = TRUE; session_state->msg_tot_len += msg_len; if (msg_len == 0) { /* No data to read, next will be a command */ session_state->smtp_state = SMTP_STATE_READING_CMDS; } else { session_state->smtp_state = SMTP_STATE_READING_DATA; } if (g_ascii_strncasecmp(line+linelen-4, "LAST", 4) == 0) { /* * This is the last data chunk. */ session_state->msg_last = TRUE; if (msg_len == 0) { /* * No more data to expect. * The message can now be reassembled. */ spd_frame_data->more_frags = FALSE; } } else { session_state->msg_last = FALSE; } } else if ((g_ascii_strncasecmp(line, "AUTH LOGIN", 10) == 0) && (linelen <= 11)) { /* * AUTH LOGIN command. * Username is in a seperate frame */ spd_frame_data->pdu_type = SMTP_PDU_CMD; session_state->smtp_state = SMTP_STATE_READING_CMDS; session_state->auth_state = SMTP_AUTH_STATE_START; session_state->first_auth_frame = pinfo->fd->num; } else if ((g_ascii_strncasecmp(line, "AUTH LOGIN", 10) == 0) && (linelen > 11)) { /* * AUTH LOGIN command. * Username follows the 'AUTH LOGIN' string */ spd_frame_data->pdu_type = SMTP_PDU_CMD; session_state->smtp_state = SMTP_STATE_READING_CMDS; session_state->auth_state = SMTP_AUTH_STATE_USERNAME_RSP; session_state->first_auth_frame = pinfo->fd->num; session_state->username_cmd_frame = pinfo->fd->num; } else if ((g_ascii_strncasecmp(line, "AUTH PLAIN", 10) == 0) && (linelen <= 11)) { /* * AUTH PLAIN command. * Username and Password is in one seperate frame */ spd_frame_data->pdu_type = SMTP_PDU_CMD; session_state->smtp_state = SMTP_STATE_READING_CMDS; session_state->auth_state = SMTP_AUTH_STATE_PLAIN_START_REQ; session_state->first_auth_frame = pinfo->fd->num; } else if ((g_ascii_strncasecmp(line, "AUTH PLAIN", 10) == 0) && (linelen > 11)) { /* * AUTH PLAIN command. * Username and Password follows the 'AUTH PLAIN' string */ spd_frame_data->pdu_type = SMTP_PDU_CMD; session_state->smtp_state = SMTP_STATE_READING_CMDS; session_state->auth_state = SMTP_AUTH_STATE_PLAIN_CRED_REQ; session_state->first_auth_frame = pinfo->fd->num; session_state->user_pass_cmd_frame = pinfo->fd->num; } else if ((g_ascii_strncasecmp(line, "AUTH NTLM", 9) == 0) && (linelen > 10)) { /* * AUTH NTLM command with nlmssp request */ spd_frame_data->pdu_type = SMTP_PDU_CMD; session_state->smtp_state = SMTP_STATE_READING_CMDS; session_state->auth_state = SMTP_AUTH_STATE_NTLM_REQ; session_state->ntlm_req_frame = pinfo->fd->num; } else if (g_ascii_strncasecmp(line, "STARTTLS", 8) == 0) { /* * STARTTLS command. * This is a command, but if the response is 220, * everything after the response is TLS. */ session_state->smtp_state = SMTP_STATE_AWAITING_STARTTLS_RESPONSE; spd_frame_data->pdu_type = SMTP_PDU_CMD; } else { /* * Regular command. */ spd_frame_data->pdu_type = SMTP_PDU_CMD; } } else if (session_state->auth_state == SMTP_AUTH_STATE_USERNAME_REQ) { session_state->auth_state = SMTP_AUTH_STATE_USERNAME_RSP; session_state->username_frame = pinfo->fd->num; } else if (session_state->auth_state == SMTP_AUTH_STATE_PASSWORD_REQ) { session_state->auth_state = SMTP_AUTH_STATE_PASSWORD_RSP; session_state->password_frame = pinfo->fd->num; } else if (session_state->auth_state == SMTP_AUTH_STATE_PLAIN_REQ) { session_state->auth_state = SMTP_AUTH_STATE_PLAIN_RSP; session_state->user_pass_frame = pinfo->fd->num; } else if (session_state->auth_state == SMTP_AUTH_STATE_NTLM_CHALLANGE) { session_state->auth_state = SMTP_AUTH_STATE_NTLM_RSP; session_state->ntlm_rsp_frame = pinfo->fd->num; } else { /* * Assume it's message data. */ spd_frame_data->pdu_type = session_state->data_seen ? SMTP_PDU_MESSAGE : SMTP_PDU_CMD; } } } /* * Step past this line. */ loffset = next_offset; } } /* * From here, we simply add items to the tree and info to the info * fields ... */ col_set_str(pinfo->cinfo, COL_PROTOCOL, "SMTP"); col_clear(pinfo->cinfo, COL_INFO); if (tree) { /* Build the tree info ... */ ti = proto_tree_add_item(tree, proto_smtp, tvb, offset, -1, ENC_NA); smtp_tree = proto_item_add_subtree(ti, ett_smtp); } if (request) { /* * Check out whether or not we can see a command in there ... * What we are looking for is not data_seen and the word DATA * and not eom_seen. * * We will see DATA and session_state->data_seen when we process the * tree view after we have seen a DATA packet when processing * the packet list pane. * * On the first pass, we will not have any info on the packets * On second and subsequent passes, we will. */ switch (spd_frame_data->pdu_type) { case SMTP_PDU_MESSAGE: /* Column Info */ length_remaining = tvb_length_remaining(tvb, offset); col_set_str(pinfo->cinfo, COL_INFO, smtp_data_desegment ? "C: DATA fragment" : "C: Message Body"); col_append_fstr(pinfo->cinfo, COL_INFO, ", %d byte%s", length_remaining, plurality (length_remaining, "", "s")); if (smtp_data_desegment) { frag_msg = fragment_add_seq_next(&smtp_data_reassembly_table, tvb, 0, pinfo, spd_frame_data->conversation_id, NULL, tvb_length(tvb), spd_frame_data->more_frags); } else { /* * Message body. * Put its lines into the protocol tree, a line at a time. */ dissect_smtp_data(tvb, offset, smtp_tree); } break; case SMTP_PDU_EOM: /* * End-of-message-body indicator. * * XXX - what about stuff after the first line? * Unlikely, as the client should wait for a response to the * DATA command this terminates before sending another * request, but we should probably handle it. */ col_set_str(pinfo->cinfo, COL_INFO, "C: ."); proto_tree_add_text(smtp_tree, tvb, offset, linelen, "C: ."); if (smtp_data_desegment) { /* add final data segment */ if (loffset) fragment_add_seq_next(&smtp_data_reassembly_table, tvb, 0, pinfo, spd_frame_data->conversation_id, NULL, loffset, spd_frame_data->more_frags); /* terminate the desegmentation */ frag_msg = fragment_end_seq_next(&smtp_data_reassembly_table, pinfo, spd_frame_data->conversation_id, NULL); } break; case SMTP_PDU_CMD: /* * Command. * * XXX - what about stuff after the first line? * Unlikely, as the client should wait for a response to the * previous command before sending another request, but we * should probably handle it. */ loffset = offset; while (tvb_offset_exists(tvb, loffset)) { /* * Find the end of the line. */ linelen = tvb_find_line_end(tvb, loffset, -1, &next_offset, FALSE); /* Column Info */ if (loffset == offset) col_append_str(pinfo->cinfo, COL_INFO, "C: "); else col_append_str(pinfo->cinfo, COL_INFO, " | "); hidden_item = proto_tree_add_boolean(smtp_tree, hf_smtp_req, tvb, 0, 0, TRUE); PROTO_ITEM_SET_HIDDEN(hidden_item); if (session_state->username_frame == pinfo->fd->num) { if (decrypt == NULL) { /* This line wasn't already decrypted through the state machine */ decrypt = tvb_get_ephemeral_string(tvb, loffset, linelen); if (stmp_decryption_enabled) { if (epan_base64_decode(decrypt) == 0) { /* Go back to the original string */ decrypt = tvb_get_ephemeral_string(tvb, loffset, linelen); } } } proto_tree_add_string(smtp_tree, hf_smtp_username, tvb, loffset, linelen, decrypt); col_append_fstr(pinfo->cinfo, COL_INFO, "User: %s", decrypt); } else if (session_state->password_frame == pinfo->fd->num) { if (decrypt == NULL) { /* This line wasn't already decrypted through the state machine */ decrypt = tvb_get_ephemeral_string(tvb, loffset, linelen); if (stmp_decryption_enabled) { if (epan_base64_decode(decrypt) == 0) { /* Go back to the original string */ decrypt = tvb_get_ephemeral_string(tvb, loffset, linelen); } } } proto_tree_add_string(smtp_tree, hf_smtp_password, tvb, loffset, linelen, decrypt); col_append_fstr(pinfo->cinfo, COL_INFO, "Pass: %s", decrypt); } else if (session_state->ntlm_rsp_frame == pinfo->fd->num) { decrypt = tvb_get_ephemeral_string(tvb, loffset, linelen); if (stmp_decryption_enabled) { if (epan_base64_decode(decrypt) == 0) { /* Go back to the original string */ decrypt = tvb_get_ephemeral_string(tvb, loffset, linelen); col_append_str(pinfo->cinfo, COL_INFO, decrypt); proto_tree_add_item(smtp_tree, hf_smtp_command_line, tvb, loffset, linelen, ENC_ASCII|ENC_NA); } else { base64_string = tvb_get_ephemeral_string(tvb, loffset, linelen); dissect_ntlm_auth(tvb, pinfo, smtp_tree, base64_string); } } else { col_append_str(pinfo->cinfo, COL_INFO, decrypt); proto_tree_add_item(smtp_tree, hf_smtp_command_line, tvb, loffset, linelen, ENC_ASCII|ENC_NA); } } else if (session_state->user_pass_frame == pinfo->fd->num) { decode_plain_auth(tvb, pinfo, smtp_tree, loffset, linelen); } else { if (linelen >= 4) cmdlen = 4; else cmdlen = linelen; /* * Put the command line into the protocol tree. */ ti = proto_tree_add_item(smtp_tree, hf_smtp_command_line, tvb, loffset, next_offset - loffset, ENC_ASCII|ENC_NA); cmdresp_tree = proto_item_add_subtree(ti, ett_smtp_cmdresp); proto_tree_add_item(cmdresp_tree, hf_smtp_req_command, tvb, loffset, cmdlen, ENC_ASCII|ENC_NA); if ((linelen > 5) && (session_state->username_cmd_frame == pinfo->fd->num) ) { proto_tree_add_item(cmdresp_tree, hf_smtp_req_parameter, tvb, loffset + 5, linelen - 5, ENC_ASCII|ENC_NA); if (decrypt == NULL) { /* This line wasn't already decrypted through the state machine */ decrypt = tvb_get_ephemeral_string(tvb, loffset + 11, linelen - 11); if (stmp_decryption_enabled) { if (epan_base64_decode(decrypt) == 0) { /* Go back to the original string */ decrypt = tvb_get_ephemeral_string(tvb, loffset + 11, linelen - 11); } } } proto_tree_add_string(cmdresp_tree, hf_smtp_username, tvb, loffset + 11, linelen - 11, decrypt); col_append_str(pinfo->cinfo, COL_INFO, tvb_get_ephemeral_string(tvb, loffset, 11)); col_append_fstr(pinfo->cinfo, COL_INFO, "User: %s", decrypt); } else if ((linelen > 5) && (session_state->ntlm_req_frame == pinfo->fd->num) ) { proto_tree_add_item(cmdresp_tree, hf_smtp_req_parameter, tvb, loffset + 5, linelen - 5, ENC_ASCII|ENC_NA); decrypt = tvb_get_ephemeral_string(tvb, loffset + 10, linelen - 10); if (stmp_decryption_enabled) { if (epan_base64_decode(decrypt) == 0) { /* Go back to the original string */ decrypt = tvb_get_ephemeral_string(tvb, loffset + 10, linelen - 10); col_append_str(pinfo->cinfo, COL_INFO, tvb_get_ephemeral_string(tvb, loffset, 10)); col_append_str(pinfo->cinfo, COL_INFO, decrypt); } else { base64_string = tvb_get_ephemeral_string(tvb, loffset + 10, linelen - 10); col_append_str(pinfo->cinfo, COL_INFO, tvb_get_ephemeral_string(tvb, loffset, 10)); dissect_ntlm_auth(tvb, pinfo, cmdresp_tree, base64_string); } } else { col_append_str(pinfo->cinfo, COL_INFO, tvb_get_ephemeral_string(tvb, loffset, 10)); col_append_str(pinfo->cinfo, COL_INFO, decrypt); } } else if ((linelen > 5) && (session_state->user_pass_cmd_frame == pinfo->fd->num) ) { proto_tree_add_item(cmdresp_tree, hf_smtp_req_parameter, tvb, loffset + 5, linelen - 5, ENC_ASCII|ENC_NA); col_append_str(pinfo->cinfo, COL_INFO, tvb_get_ephemeral_string(tvb, loffset, 11)); decode_plain_auth(tvb, pinfo, cmdresp_tree, loffset + 11, linelen - 11); } else if (linelen > 5) { proto_tree_add_item(cmdresp_tree, hf_smtp_req_parameter, tvb, loffset + 5, linelen - 5, ENC_ASCII|ENC_NA); col_append_str(pinfo->cinfo, COL_INFO, tvb_get_ephemeral_string(tvb, loffset, linelen)); } else { col_append_str(pinfo->cinfo, COL_INFO, tvb_get_ephemeral_string(tvb, loffset, linelen)); } if (smtp_data_desegment && !spd_frame_data->more_frags) { /* terminate the desegmentation */ frag_msg = fragment_end_seq_next(&smtp_data_reassembly_table, pinfo, spd_frame_data->conversation_id, NULL); } } /* * Step past this line. */ loffset = next_offset; } } if (smtp_data_desegment) { next_tvb = process_reassembled_data(tvb, offset, pinfo, "Reassembled SMTP", frag_msg, &smtp_data_frag_items, NULL, smtp_tree); if (next_tvb) { /* XXX: this is presumptuous - we may have negotiated something else */ if (imf_handle) { call_dissector(imf_handle, next_tvb, pinfo, tree); } else { /* * Message body. * Put its lines into the protocol tree, a line at a time. */ dissect_smtp_data(tvb, offset, smtp_tree); } pinfo->fragmented = FALSE; } else { pinfo->fragmented = TRUE; } } } else { /* * Process the response, a line at a time, until we hit a line * that doesn't have a continuation indication on it. */ if (tree) { hidden_item = proto_tree_add_boolean(smtp_tree, hf_smtp_rsp, tvb, 0, 0, TRUE); PROTO_ITEM_SET_HIDDEN(hidden_item); } loffset = offset; while (tvb_offset_exists(tvb, offset)) { /* * Find the end of the line. */ linelen = tvb_find_line_end(tvb, offset, -1, &next_offset, FALSE); if (loffset == offset) col_append_str(pinfo->cinfo, COL_INFO, "S: "); else col_append_str(pinfo->cinfo, COL_INFO, " | "); if (tree) { /* * Put it into the protocol tree. */ ti = proto_tree_add_item(smtp_tree, hf_smtp_response, tvb, offset, next_offset - offset, ENC_ASCII|ENC_NA); cmdresp_tree = proto_item_add_subtree(ti, ett_smtp_cmdresp); } else cmdresp_tree = NULL; if (linelen >= 3) { line_code[0] = tvb_get_guint8(tvb, offset); line_code[1] = tvb_get_guint8(tvb, offset+1); line_code[2] = tvb_get_guint8(tvb, offset+2); if (isdigit(line_code[0]) && isdigit(line_code[1]) && isdigit(line_code[2])) { /* * We have a 3-digit response code. */ code = (line_code[0] - '0')*100 + (line_code[1] - '0')*10 + (line_code[2] - '0'); /* * If we're awaiting the response to a STARTTLS code, this * is it - if it's 220, all subsequent traffic will * be TLS, otherwise we're back to boring old SMTP. */ if (session_state->smtp_state == SMTP_STATE_AWAITING_STARTTLS_RESPONSE) { if (code == 220) { /* This is the last non-TLS frame. */ session_state->last_nontls_frame = pinfo->fd->num; } session_state->smtp_state = SMTP_STATE_READING_CMDS; } if (code == 334) { switch(session_state->auth_state) { case SMTP_AUTH_STATE_START: session_state->auth_state = SMTP_AUTH_STATE_USERNAME_REQ; break; case SMTP_AUTH_STATE_USERNAME_RSP: session_state->auth_state = SMTP_AUTH_STATE_PASSWORD_REQ; break; case SMTP_AUTH_STATE_PLAIN_REQ: session_state->auth_state = SMTP_AUTH_STATE_PLAIN_RSP; break; case SMTP_AUTH_STATE_PLAIN_START_REQ: session_state->auth_state = SMTP_AUTH_STATE_PLAIN_REQ; break; case SMTP_AUTH_STATE_NTLM_REQ: session_state->auth_state = SMTP_AUTH_STATE_NTLM_CHALLANGE; break; case SMTP_AUTH_STATE_NONE: case SMTP_AUTH_STATE_USERNAME_REQ: case SMTP_AUTH_STATE_PASSWORD_REQ: case SMTP_AUTH_STATE_PASSWORD_RSP: case SMTP_AUTH_STATE_PLAIN_RSP: case SMTP_AUTH_STATE_PLAIN_CRED_REQ: case SMTP_AUTH_STATE_NTLM_RSP: case SMTP_AUTH_STATE_NTLM_CHALLANGE: case SMTP_AUTH_STATE_SUCCESS: case SMTP_AUTH_STATE_FAILED: /* ignore */ break; } } else if ((session_state->auth_state == SMTP_AUTH_STATE_PASSWORD_RSP) || ( session_state->auth_state == SMTP_AUTH_STATE_PLAIN_RSP) || ( session_state->auth_state == SMTP_AUTH_STATE_NTLM_RSP) || ( session_state->auth_state == SMTP_AUTH_STATE_PLAIN_CRED_REQ) ) { if (code == 235) { session_state->auth_state = SMTP_AUTH_STATE_SUCCESS; } else { session_state->auth_state = SMTP_AUTH_STATE_FAILED; } session_state->last_auth_frame = pinfo->fd->num; } /* * Put the response code and parameters into the protocol tree. */ proto_tree_add_uint(cmdresp_tree, hf_smtp_rsp_code, tvb, offset, 3, code); decrypt = NULL; if (linelen >= 4) { if ((stmp_decryption_enabled) && (code == 334)) { decrypt = tvb_get_ephemeral_string(tvb, offset + 4, linelen - 4); if (epan_base64_decode(decrypt) > 0) { if (g_ascii_strncasecmp(decrypt, "NTLMSSP", 7) == 0) { base64_string = tvb_get_ephemeral_string(tvb, loffset + 4, linelen - 4); col_append_fstr(pinfo->cinfo, COL_INFO, "%d ", code); proto_tree_add_string(cmdresp_tree, hf_smtp_rsp_parameter, tvb, offset + 4, linelen - 4, (const char*)base64_string); dissect_ntlm_auth(tvb, pinfo, cmdresp_tree, base64_string); } else { proto_tree_add_string(cmdresp_tree, hf_smtp_rsp_parameter, tvb, offset + 4, linelen - 4, (const char*)decrypt); col_append_fstr(pinfo->cinfo, COL_INFO, "%d %s", code, decrypt); } } else { decrypt = NULL; } } if (decrypt == NULL) { proto_tree_add_item(cmdresp_tree, hf_smtp_rsp_parameter, tvb, offset + 4, linelen - 4, ENC_ASCII|ENC_NA); col_append_fstr(pinfo->cinfo, COL_INFO, "%d %s", code, tvb_get_ephemeral_string(tvb, offset + 4, linelen - 4)); } } else { col_append_str(pinfo->cinfo, COL_INFO, tvb_get_ephemeral_string(tvb, offset, linelen)); } } } /* * Step past this line. */ offset = next_offset; } } } static void smtp_data_reassemble_init (void) { reassembly_table_init(&smtp_data_reassembly_table, &addresses_ports_reassembly_table_functions); } /* Register all the bits needed by the filtering engine */ void proto_register_smtp(void) { static hf_register_info hf[] = { { &hf_smtp_req, { "Request", "smtp.req", FT_BOOLEAN, BASE_NONE, NULL, 0x0, NULL, HFILL }}, { &hf_smtp_rsp, { "Response", "smtp.rsp", FT_BOOLEAN, BASE_NONE, NULL, 0x0, NULL, HFILL }}, { &hf_smtp_message, { "Message", "smtp.message", FT_STRING, BASE_NONE, NULL, 0x0, NULL, HFILL }}, { &hf_smtp_command_line, { "Command Line", "smtp.command_line", FT_STRING, BASE_NONE, NULL, 0x0, NULL, HFILL }}, { &hf_smtp_req_command, { "Command", "smtp.req.command", FT_STRING, BASE_NONE, NULL, 0x0, NULL, HFILL }}, { &hf_smtp_req_parameter, { "Request parameter", "smtp.req.parameter", FT_STRING, BASE_NONE, NULL, 0x0, NULL, HFILL }}, { &hf_smtp_response, { "Response", "smtp.response", FT_STRING, BASE_NONE, NULL, 0x0, NULL, HFILL }}, { &hf_smtp_rsp_code, { "Response code", "smtp.response.code", FT_UINT32, BASE_DEC|BASE_EXT_STRING, &response_codes_vs_ext, 0x0, NULL, HFILL }}, { &hf_smtp_rsp_parameter, { "Response parameter", "smtp.rsp.parameter", FT_STRING, BASE_NONE, NULL, 0x0, NULL, HFILL }}, { &hf_smtp_username, { "Username", "smtp.auth.username", FT_STRING, BASE_NONE, NULL, 0x0, NULL, HFILL }}, { &hf_smtp_password, { "Password", "smtp.auth.password", FT_STRING, BASE_NONE, NULL, 0x0, NULL, HFILL }}, /* Fragment entries */ { &hf_smtp_data_fragments, { "DATA fragments", "smtp.data.fragments", FT_NONE, BASE_NONE, NULL, 0x00, "Message fragments", HFILL } }, { &hf_smtp_data_fragment, { "DATA fragment", "smtp.data.fragment", FT_FRAMENUM, BASE_NONE, NULL, 0x00, "Message fragment", HFILL } }, { &hf_smtp_data_fragment_overlap, { "DATA fragment overlap", "smtp.data.fragment.overlap", FT_BOOLEAN, BASE_NONE, NULL, 0x0, "Message fragment overlap", HFILL } }, { &hf_smtp_data_fragment_overlap_conflicts, { "DATA fragment overlapping with conflicting data", "smtp.data.fragment.overlap.conflicts", FT_BOOLEAN, BASE_NONE, NULL, 0x0, "Message fragment overlapping with conflicting data", HFILL } }, { &hf_smtp_data_fragment_multiple_tails, { "DATA has multiple tail fragments", "smtp.data.fragment.multiple_tails", FT_BOOLEAN, BASE_NONE, NULL, 0x0, "Message has multiple tail fragments", HFILL } }, { &hf_smtp_data_fragment_too_long_fragment, { "DATA fragment too long", "smtp.data.fragment.too_long_fragment", FT_BOOLEAN, BASE_NONE, NULL, 0x0, "Message fragment too long", HFILL } }, { &hf_smtp_data_fragment_error, { "DATA defragmentation error", "smtp.data.fragment.error", FT_FRAMENUM, BASE_NONE, NULL, 0x00, "Message defragmentation error", HFILL } }, { &hf_smtp_data_fragment_count, { "DATA fragment count", "smtp.data.fragment.count", FT_UINT32, BASE_DEC, NULL, 0x00, NULL, HFILL } }, { &hf_smtp_data_reassembled_in, { "Reassembled DATA in frame", "smtp.data.reassembled.in", FT_FRAMENUM, BASE_NONE, NULL, 0x00, "This DATA fragment is reassembled in this frame", HFILL } }, { &hf_smtp_data_reassembled_length, { "Reassembled DATA length", "smtp.data.reassembled.length", FT_UINT32, BASE_DEC, NULL, 0x00, "The total length of the reassembled payload", HFILL } }, }; static gint *ett[] = { &ett_smtp, &ett_smtp_cmdresp, &ett_smtp_data_fragment, &ett_smtp_data_fragments, }; module_t *smtp_module; proto_smtp = proto_register_protocol("Simple Mail Transfer Protocol", "SMTP", "smtp"); proto_register_field_array(proto_smtp, hf, array_length(hf)); proto_register_subtree_array(ett, array_length(ett)); register_init_routine (&smtp_data_reassemble_init); /* Allow dissector to find be found by name. */ register_dissector("smtp", dissect_smtp, proto_smtp); /* Preferences */ smtp_module = prefs_register_protocol(proto_smtp, NULL); prefs_register_bool_preference(smtp_module, "desegment_lines", "Reassemble SMTP command and response lines\nspanning multiple TCP segments", "Whether the SMTP dissector should reassemble command and response lines" " spanning multiple TCP segments. To use this option, you must also enable " "\"Allow subdissectors to reassemble TCP streams\" in the TCP protocol settings.", &smtp_desegment); prefs_register_bool_preference(smtp_module, "desegment_data", "Reassemble SMTP DATA commands spanning multiple TCP segments", "Whether the SMTP dissector should reassemble DATA command and lines" " spanning multiple TCP segments. To use this option, you must also enable " "\"Allow subdissectors to reassemble TCP streams\" in the TCP protocol settings.", &smtp_data_desegment); prefs_register_bool_preference(smtp_module, "decryption", "Decrypt AUTH parameters", "Whether the SMTP dissector should decrypt AUTH parameters", &stmp_decryption_enabled); } /* The registration hand-off routine */ void proto_reg_handoff_smtp(void) { dissector_handle_t smtp_handle; smtp_handle = find_dissector("smtp"); dissector_add_uint("tcp.port", TCP_PORT_SMTP, smtp_handle); ssl_dissector_add(TCP_PORT_SSL_SMTP, "smtp", TRUE); dissector_add_uint("tcp.port", TCP_PORT_SUBMISSION, smtp_handle); /* find the IMF dissector */ imf_handle = find_dissector("imf"); /* find the SSL dissector */ ssl_handle = find_dissector("ssl"); /* find the NTLM dissector */ ntlmssp_handle = find_dissector("ntlmssp"); } /* * Editor modelines - http://www.wireshark.org/tools/modelines.html * * Local variables: * c-basic-offset: 2 * tab-width: 8 * indent-tabs-mode: nil * End: * * vi: set shiftwidth=2 tabstop=8 expandtab: * :indentSize=2:tabSize=8:noTabs=true */
P1sec/LTE_monitor_c2xx
wireshark/epan/dissectors/packet-smtp.c
C
gpl-2.0
52,078
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_GFX_ANIMATION_THROB_ANIMATION_H_ #define UI_GFX_ANIMATION_THROB_ANIMATION_H_ #include "ui/gfx/animation/slide_animation.h" namespace gfx { class GFX_EXPORT ThrobAnimation : public SlideAnimation { public: explicit ThrobAnimation(AnimationDelegate* target); virtual ~ThrobAnimation() {} void StartThrobbing(int cycles_til_stop); void SetThrobDuration(int duration) { throb_duration_ = duration; } virtual void Reset() OVERRIDE; virtual void Reset(double value) OVERRIDE; virtual void Show() OVERRIDE; virtual void Hide() OVERRIDE; virtual void SetSlideDuration(int duration) OVERRIDE; void set_cycles_remaining(int value) { cycles_remaining_ = value; } int cycles_remaining() const { return cycles_remaining_; } protected: virtual void Step(base::TimeTicks time_now) OVERRIDE; private: void ResetForSlide(); int slide_duration_; int throb_duration_; int cycles_remaining_; bool throbbing_; DISALLOW_COPY_AND_ASSIGN(ThrobAnimation); }; } #endif
qtekfun/htcDesire820Kernel
external/chromium_org/ui/gfx/animation/throb_animation.h
C
gpl-2.0
1,220
/* * linux/fs/exec.c * * Copyright (C) 1991, 1992 Linus Torvalds */ /* * #!-checking implemented by tytso. */ /* * Demand-loading implemented 01.12.91 - no need to read anything but * the header into memory. The inode of the executable is put into * "current->executable", and page faults do the actual loading. Clean. * * Once more I can proudly say that linux stood up to being changed: it * was less than 2 hours work to get demand-loading completely implemented. * * Demand loading changed July 1993 by Eric Youngdale. Use mmap instead, * current->executable is only used by the procfs. This allows a dispatch * table to check for several different types of binary formats. We keep * trying until we recognize the file or we run out of supported binary * formats. */ #include <linux/slab.h> #include <linux/file.h> #include <linux/mman.h> #include <linux/a.out.h> #include <linux/stat.h> #include <linux/fcntl.h> #include <linux/smp_lock.h> #include <linux/init.h> #include <linux/pagemap.h> #include <linux/highmem.h> #include <linux/spinlock.h> #include <linux/key.h> #include <linux/personality.h> #include <linux/binfmts.h> #include <linux/swap.h> #include <linux/utsname.h> #include <linux/module.h> #include <linux/namei.h> #include <linux/proc_fs.h> #include <linux/ptrace.h> #include <linux/mount.h> #include <linux/security.h> #include <linux/syscalls.h> #include <linux/rmap.h> #include <linux/tsacct_kern.h> #include <linux/cn_proc.h> #include <linux/audit.h> #include <asm/uaccess.h> #include <asm/mmu_context.h> #ifdef CONFIG_KMOD #include <linux/kmod.h> #endif int core_uses_pid; char core_pattern[128] = "core"; int suid_dumpable = 0; EXPORT_SYMBOL(suid_dumpable); /* The maximal length of core_pattern is also specified in sysctl.c */ static struct linux_binfmt *formats; static DEFINE_RWLOCK(binfmt_lock); int register_binfmt(struct linux_binfmt * fmt) { struct linux_binfmt ** tmp = &formats; if (!fmt) return -EINVAL; if (fmt->next) return -EBUSY; write_lock(&binfmt_lock); while (*tmp) { if (fmt == *tmp) { write_unlock(&binfmt_lock); return -EBUSY; } tmp = &(*tmp)->next; } fmt->next = formats; formats = fmt; write_unlock(&binfmt_lock); return 0; } EXPORT_SYMBOL(register_binfmt); int unregister_binfmt(struct linux_binfmt * fmt) { struct linux_binfmt ** tmp = &formats; write_lock(&binfmt_lock); while (*tmp) { if (fmt == *tmp) { *tmp = fmt->next; write_unlock(&binfmt_lock); return 0; } tmp = &(*tmp)->next; } write_unlock(&binfmt_lock); return -EINVAL; } EXPORT_SYMBOL(unregister_binfmt); static inline void put_binfmt(struct linux_binfmt * fmt) { module_put(fmt->module); } /* * Note that a shared library must be both readable and executable due to * security reasons. * * Also note that we take the address to load from from the file itself. */ asmlinkage long sys_uselib(const char __user * library) { struct file * file; struct nameidata nd; int error; error = __user_path_lookup_open(library, LOOKUP_FOLLOW, &nd, FMODE_READ|FMODE_EXEC); if (error) goto out; error = -EINVAL; if (!S_ISREG(nd.dentry->d_inode->i_mode)) goto exit; error = vfs_permission(&nd, MAY_READ | MAY_EXEC); if (error) goto exit; file = nameidata_to_filp(&nd, O_RDONLY); error = PTR_ERR(file); if (IS_ERR(file)) goto out; error = -ENOEXEC; if(file->f_op) { struct linux_binfmt * fmt; read_lock(&binfmt_lock); for (fmt = formats ; fmt ; fmt = fmt->next) { if (!fmt->load_shlib) continue; if (!try_module_get(fmt->module)) continue; read_unlock(&binfmt_lock); error = fmt->load_shlib(file); read_lock(&binfmt_lock); put_binfmt(fmt); if (error != -ENOEXEC) break; } read_unlock(&binfmt_lock); } fput(file); out: return error; exit: release_open_intent(&nd); path_release(&nd); goto out; } /* * count() counts the number of strings in array ARGV. */ static int count(char __user * __user * argv, int max) { int i = 0; if (argv != NULL) { for (;;) { char __user * p; if (get_user(p, argv)) return -EFAULT; if (!p) break; argv++; if(++i > max) return -E2BIG; cond_resched(); } } return i; } /* * 'copy_strings()' copies argument/environment strings from user * memory to free pages in kernel mem. These are in a format ready * to be put directly into the top of new user memory. */ static int copy_strings(int argc, char __user * __user * argv, struct linux_binprm *bprm) { struct page *kmapped_page = NULL; char *kaddr = NULL; int ret; while (argc-- > 0) { char __user *str; int len; unsigned long pos; if (get_user(str, argv+argc) || !(len = strnlen_user(str, bprm->p))) { ret = -EFAULT; goto out; } if (bprm->p < len) { ret = -E2BIG; goto out; } bprm->p -= len; /* XXX: add architecture specific overflow check here. */ pos = bprm->p; while (len > 0) { int i, new, err; int offset, bytes_to_copy; struct page *page; offset = pos % PAGE_SIZE; i = pos/PAGE_SIZE; page = bprm->page[i]; new = 0; if (!page) { page = alloc_page(GFP_HIGHUSER); bprm->page[i] = page; printk("%s bprm->page[%d]=0x%08x pfn=0x%08x\n",__FUNCTION__,i,bprm->page[i],page_to_pfn(page)); if (!page) { ret = -ENOMEM; goto out; } new = 1; } if (page != kmapped_page) { if (kmapped_page) kunmap(kmapped_page); kmapped_page = page; kaddr = kmap(kmapped_page); } if (new && offset) memset(kaddr, 0, offset); bytes_to_copy = PAGE_SIZE - offset; if (bytes_to_copy > len) { bytes_to_copy = len; if (new) memset(kaddr+offset+len, 0, PAGE_SIZE-offset-len); } err = copy_from_user(kaddr+offset, str, bytes_to_copy); if (err) { ret = -EFAULT; goto out; } pos += bytes_to_copy; str += bytes_to_copy; len -= bytes_to_copy; } } ret = 0; printk("%s bprm->p=0x%08x\n",__FUNCTION__,bprm->p); out: if (kmapped_page) kunmap(kmapped_page); return ret; } /* * Like copy_strings, but get argv and its values from kernel memory. */ int copy_strings_kernel(int argc,char ** argv, struct linux_binprm *bprm) { int r; mm_segment_t oldfs = get_fs(); set_fs(KERNEL_DS); r = copy_strings(argc, (char __user * __user *)argv, bprm); set_fs(oldfs); return r; } EXPORT_SYMBOL(copy_strings_kernel); #ifdef CONFIG_MMU /* * This routine is used to map in a page into an address space: needed by * execve() for the initial stack and environment pages. * * vma->vm_mm->mmap_sem is held for writing. */ void install_arg_page(struct vm_area_struct *vma, struct page *page, unsigned long address) { struct mm_struct *mm = vma->vm_mm; pte_t * pte; spinlock_t *ptl; if (unlikely(anon_vma_prepare(vma))) goto out; flush_dcache_page(page); pte = get_locked_pte(mm, address, &ptl); if (!pte) goto out; if (!pte_none(*pte)) { pte_unmap_unlock(pte, ptl); goto out; } inc_mm_counter(mm, anon_rss); lru_cache_add_active(page); set_pte_at(mm, address, pte, pte_mkdirty(pte_mkwrite(mk_pte( page, vma->vm_page_prot)))); page_add_new_anon_rmap(page, vma, address); pte_unmap_unlock(pte, ptl); /* no need for flush_tlb */ return; out: __free_page(page); force_sig(SIGKILL, current); } #define EXTRA_STACK_VM_PAGES 20 /* random */ int setup_arg_pages(struct linux_binprm *bprm, unsigned long stack_top, int executable_stack) { unsigned long stack_base; struct vm_area_struct *mpnt; struct mm_struct *mm = current->mm; int i, ret; long arg_size; #ifdef CONFIG_STACK_GROWSUP /* Move the argument and environment strings to the bottom of the * stack space. */ int offset, j; char *to, *from; /* Start by shifting all the pages down */ i = 0; for (j = 0; j < MAX_ARG_PAGES; j++) { struct page *page = bprm->page[j]; if (!page) continue; bprm->page[i++] = page; } /* Now move them within their pages */ offset = bprm->p % PAGE_SIZE; to = kmap(bprm->page[0]); for (j = 1; j < i; j++) { memmove(to, to + offset, PAGE_SIZE - offset); from = kmap(bprm->page[j]); memcpy(to + PAGE_SIZE - offset, from, offset); kunmap(bprm->page[j - 1]); to = from; } memmove(to, to + offset, PAGE_SIZE - offset); kunmap(bprm->page[j - 1]); /* Limit stack size to 1GB */ stack_base = current->signal->rlim[RLIMIT_STACK].rlim_max; if (stack_base > (1 << 30)) stack_base = 1 << 30; stack_base = PAGE_ALIGN(stack_top - stack_base); /* Adjust bprm->p to point to the end of the strings. */ bprm->p = stack_base + PAGE_SIZE * i - offset; mm->arg_start = stack_base; arg_size = i << PAGE_SHIFT; /* zero pages that were copied above */ while (i < MAX_ARG_PAGES) bprm->page[i++] = NULL; #else stack_base = arch_align_stack(stack_top - MAX_ARG_PAGES*PAGE_SIZE); stack_base = PAGE_ALIGN(stack_base); bprm->p += stack_base; printk("%s bprm->p=0x%08x stack_base=%08x\n",__FUNCTION__,bprm->p,stack_base); mm->arg_start = bprm->p; arg_size = stack_top - (PAGE_MASK & (unsigned long) mm->arg_start); #endif arg_size += EXTRA_STACK_VM_PAGES * PAGE_SIZE; if (bprm->loader) bprm->loader += stack_base; bprm->exec += stack_base; mpnt = kmem_cache_alloc(vm_area_cachep, SLAB_KERNEL); if (!mpnt) return -ENOMEM; memset(mpnt, 0, sizeof(*mpnt)); down_write(&mm->mmap_sem); { mpnt->vm_mm = mm; #ifdef CONFIG_STACK_GROWSUP mpnt->vm_start = stack_base; mpnt->vm_end = stack_base + arg_size; #else mpnt->vm_end = stack_top; mpnt->vm_start = mpnt->vm_end - arg_size; #endif /* Adjust stack execute permissions; explicitly enable * for EXSTACK_ENABLE_X, disable for EXSTACK_DISABLE_X * and leave alone (arch default) otherwise. */ if (unlikely(executable_stack == EXSTACK_ENABLE_X)) mpnt->vm_flags = VM_STACK_FLAGS | VM_EXEC; else if (executable_stack == EXSTACK_DISABLE_X) mpnt->vm_flags = VM_STACK_FLAGS & ~VM_EXEC; else mpnt->vm_flags = VM_STACK_FLAGS; mpnt->vm_flags |= mm->def_flags; mpnt->vm_page_prot = protection_map[mpnt->vm_flags & 0x7]; if ((ret = insert_vm_struct(mm, mpnt))) { up_write(&mm->mmap_sem); kmem_cache_free(vm_area_cachep, mpnt); return ret; } mm->stack_vm = mm->total_vm = vma_pages(mpnt); } for (i = 0 ; i < MAX_ARG_PAGES ; i++) { struct page *page = bprm->page[i]; if (page) { bprm->page[i] = NULL; install_arg_page(mpnt, page, stack_base); } stack_base += PAGE_SIZE; } up_write(&mm->mmap_sem); return 0; } EXPORT_SYMBOL(setup_arg_pages); #define free_arg_pages(bprm) do { } while (0) #else static inline void free_arg_pages(struct linux_binprm *bprm) { int i; for (i = 0; i < MAX_ARG_PAGES; i++) { if (bprm->page[i]) __free_page(bprm->page[i]); bprm->page[i] = NULL; } } #endif /* CONFIG_MMU */ struct file *open_exec(const char *name) { struct nameidata nd; int err; struct file *file; err = path_lookup_open(AT_FDCWD, name, LOOKUP_FOLLOW, &nd, FMODE_READ|FMODE_EXEC); file = ERR_PTR(err); if (!err) { struct inode *inode = nd.dentry->d_inode; file = ERR_PTR(-EACCES); if (!(nd.mnt->mnt_flags & MNT_NOEXEC) && S_ISREG(inode->i_mode)) { int err = vfs_permission(&nd, MAY_EXEC); file = ERR_PTR(err); if (!err) { file = nameidata_to_filp(&nd, O_RDONLY); if (!IS_ERR(file)) { err = deny_write_access(file); if (err) { fput(file); file = ERR_PTR(err); } } out: return file; } } release_open_intent(&nd); path_release(&nd); } goto out; } EXPORT_SYMBOL(open_exec); int kernel_read(struct file *file, unsigned long offset, char *addr, unsigned long count) { mm_segment_t old_fs; loff_t pos = offset; int result; old_fs = get_fs(); set_fs(get_ds()); /* The cast to a user pointer is valid due to the set_fs() */ result = vfs_read(file, (void __user *)addr, count, &pos); set_fs(old_fs); return result; } EXPORT_SYMBOL(kernel_read); static int exec_mmap(struct mm_struct *mm) { struct task_struct *tsk; struct mm_struct * old_mm, *active_mm; /* Notify parent that we're no longer interested in the old VM */ tsk = current; old_mm = current->mm; mm_release(tsk, old_mm); if (old_mm) { /* * Make sure that if there is a core dump in progress * for the old mm, we get out and die instead of going * through with the exec. We must hold mmap_sem around * checking core_waiters and changing tsk->mm. The * core-inducing thread will increment core_waiters for * each thread whose ->mm == old_mm. */ down_read(&old_mm->mmap_sem); if (unlikely(old_mm->core_waiters)) { up_read(&old_mm->mmap_sem); return -EINTR; } } task_lock(tsk); active_mm = tsk->active_mm; tsk->mm = mm; tsk->active_mm = mm; activate_mm(active_mm, mm); task_unlock(tsk); arch_pick_mmap_layout(mm); if (old_mm) { up_read(&old_mm->mmap_sem); BUG_ON(active_mm != old_mm); mmput(old_mm); return 0; } mmdrop(active_mm); return 0; } /* * This function makes sure the current process has its own signal table, * so that flush_signal_handlers can later reset the handlers without * disturbing other processes. (Other processes might share the signal * table via the CLONE_SIGHAND option to clone().) */ static int de_thread(struct task_struct *tsk) { struct signal_struct *sig = tsk->signal; struct sighand_struct *newsighand, *oldsighand = tsk->sighand; spinlock_t *lock = &oldsighand->siglock; struct task_struct *leader = NULL; int count; /* * If we don't share sighandlers, then we aren't sharing anything * and we can just re-use it all. */ if (atomic_read(&oldsighand->count) <= 1) { BUG_ON(atomic_read(&sig->count) != 1); exit_itimers(sig); return 0; } newsighand = kmem_cache_alloc(sighand_cachep, GFP_KERNEL); if (!newsighand) return -ENOMEM; if (thread_group_empty(tsk)) goto no_thread_group; /* * Kill all other threads in the thread group. * We must hold tasklist_lock to call zap_other_threads. */ read_lock(&tasklist_lock); spin_lock_irq(lock); if (sig->flags & SIGNAL_GROUP_EXIT) { /* * Another group action in progress, just * return so that the signal is processed. */ spin_unlock_irq(lock); read_unlock(&tasklist_lock); kmem_cache_free(sighand_cachep, newsighand); return -EAGAIN; } /* * child_reaper ignores SIGKILL, change it now. * Reparenting needs write_lock on tasklist_lock, * so it is safe to do it under read_lock. */ if (unlikely(tsk->group_leader == child_reaper)) child_reaper = tsk; zap_other_threads(tsk); read_unlock(&tasklist_lock); /* * Account for the thread group leader hanging around: */ count = 1; if (!thread_group_leader(tsk)) { count = 2; /* * The SIGALRM timer survives the exec, but needs to point * at us as the new group leader now. We have a race with * a timer firing now getting the old leader, so we need to * synchronize with any firing (by calling del_timer_sync) * before we can safely let the old group leader die. */ sig->tsk = tsk; spin_unlock_irq(lock); if (hrtimer_cancel(&sig->real_timer)) hrtimer_restart(&sig->real_timer); spin_lock_irq(lock); } while (atomic_read(&sig->count) > count) { sig->group_exit_task = tsk; sig->notify_count = count; __set_current_state(TASK_UNINTERRUPTIBLE); spin_unlock_irq(lock); schedule(); spin_lock_irq(lock); } sig->group_exit_task = NULL; sig->notify_count = 0; spin_unlock_irq(lock); /* * At this point all other threads have exited, all we have to * do is to wait for the thread group leader to become inactive, * and to assume its PID: */ if (!thread_group_leader(tsk)) { /* * Wait for the thread group leader to be a zombie. * It should already be zombie at this point, most * of the time. */ leader = tsk->group_leader; while (leader->exit_state != EXIT_ZOMBIE) yield(); /* * The only record we have of the real-time age of a * process, regardless of execs it's done, is start_time. * All the past CPU time is accumulated in signal_struct * from sister threads now dead. But in this non-leader * exec, nothing survives from the original leader thread, * whose birth marks the true age of this process now. * When we take on its identity by switching to its PID, we * also take its birthdate (always earlier than our own). */ tsk->start_time = leader->start_time; write_lock_irq(&tasklist_lock); BUG_ON(leader->tgid != tsk->tgid); BUG_ON(tsk->pid == tsk->tgid); /* * An exec() starts a new thread group with the * TGID of the previous thread group. Rehash the * two threads with a switched PID, and release * the former thread group leader: */ /* Become a process group leader with the old leader's pid. * The old leader becomes a thread of the this thread group. * Note: The old leader also uses this pid until release_task * is called. Odd but simple and correct. */ detach_pid(tsk, PIDTYPE_PID); tsk->pid = leader->pid; attach_pid(tsk, PIDTYPE_PID, tsk->pid); transfer_pid(leader, tsk, PIDTYPE_PGID); transfer_pid(leader, tsk, PIDTYPE_SID); list_replace_rcu(&leader->tasks, &tsk->tasks); tsk->group_leader = tsk; leader->group_leader = tsk; tsk->exit_signal = SIGCHLD; BUG_ON(leader->exit_state != EXIT_ZOMBIE); leader->exit_state = EXIT_DEAD; write_unlock_irq(&tasklist_lock); } /* * There may be one thread left which is just exiting, * but it's safe to stop telling the group to kill themselves. */ sig->flags = 0; no_thread_group: exit_itimers(sig); if (leader) release_task(leader); BUG_ON(atomic_read(&sig->count) != 1); if (atomic_read(&oldsighand->count) == 1) { /* * Now that we nuked the rest of the thread group, * it turns out we are not sharing sighand any more either. * So we can just keep it. */ kmem_cache_free(sighand_cachep, newsighand); } else { /* * Move our state over to newsighand and switch it in. */ atomic_set(&newsighand->count, 1); memcpy(newsighand->action, oldsighand->action, sizeof(newsighand->action)); write_lock_irq(&tasklist_lock); spin_lock(&oldsighand->siglock); spin_lock_nested(&newsighand->siglock, SINGLE_DEPTH_NESTING); rcu_assign_pointer(tsk->sighand, newsighand); recalc_sigpending(); spin_unlock(&newsighand->siglock); spin_unlock(&oldsighand->siglock); write_unlock_irq(&tasklist_lock); if (atomic_dec_and_test(&oldsighand->count)) kmem_cache_free(sighand_cachep, oldsighand); } BUG_ON(!thread_group_leader(tsk)); return 0; } /* * These functions flushes out all traces of the currently running executable * so that a new one can be started */ static void flush_old_files(struct files_struct * files) { long j = -1; struct fdtable *fdt; spin_lock(&files->file_lock); for (;;) { unsigned long set, i; j++; i = j * __NFDBITS; fdt = files_fdtable(files); if (i >= fdt->max_fds || i >= fdt->max_fdset) break; set = fdt->close_on_exec->fds_bits[j]; if (!set) continue; fdt->close_on_exec->fds_bits[j] = 0; spin_unlock(&files->file_lock); for ( ; set ; i++,set >>= 1) { if (set & 1) { sys_close(i); } } spin_lock(&files->file_lock); } spin_unlock(&files->file_lock); } void get_task_comm(char *buf, struct task_struct *tsk) { /* buf must be at least sizeof(tsk->comm) in size */ task_lock(tsk); strncpy(buf, tsk->comm, sizeof(tsk->comm)); task_unlock(tsk); } void set_task_comm(struct task_struct *tsk, char *buf) { task_lock(tsk); strlcpy(tsk->comm, buf, sizeof(tsk->comm)); task_unlock(tsk); } int flush_old_exec(struct linux_binprm * bprm) { char * name; int i, ch, retval; struct files_struct *files; char tcomm[sizeof(current->comm)]; /* * Make sure we have a private signal table and that * we are unassociated from the previous thread group. */ retval = de_thread(current); if (retval) goto out; /* * Make sure we have private file handles. Ask the * fork helper to do the work for us and the exit * helper to do the cleanup of the old one. */ files = current->files; /* refcounted so safe to hold */ retval = unshare_files(); if (retval) goto out; /* * Release all of the old mmap stuff */ retval = exec_mmap(bprm->mm); if (retval) goto mmap_failed; bprm->mm = NULL; /* We're using it now */ /* This is the point of no return */ put_files_struct(files); current->sas_ss_sp = current->sas_ss_size = 0; if (current->euid == current->uid && current->egid == current->gid) current->mm->dumpable = 1; else current->mm->dumpable = suid_dumpable; name = bprm->filename; /* Copies the binary name from after last slash */ for (i=0; (ch = *(name++)) != '\0';) { if (ch == '/') i = 0; /* overwrite what we wrote */ else if (i < (sizeof(tcomm) - 1)) tcomm[i++] = ch; } tcomm[i] = '\0'; set_task_comm(current, tcomm); current->flags &= ~PF_RANDOMIZE; flush_thread(); /* Set the new mm task size. We have to do that late because it may * depend on TIF_32BIT which is only updated in flush_thread() on * some architectures like powerpc */ current->mm->task_size = TASK_SIZE; if (bprm->e_uid != current->euid || bprm->e_gid != current->egid || file_permission(bprm->file, MAY_READ) || (bprm->interp_flags & BINPRM_FLAGS_ENFORCE_NONDUMP)) { suid_keys(current); current->mm->dumpable = suid_dumpable; } /* An exec changes our domain. We are no longer part of the thread group */ current->self_exec_id++; flush_signal_handlers(current, 0); flush_old_files(current->files); return 0; mmap_failed: reset_files_struct(current, files); out: return retval; } EXPORT_SYMBOL(flush_old_exec); /* * Fill the binprm structure from the inode. * Check permissions, then read the first 128 (BINPRM_BUF_SIZE) bytes */ int prepare_binprm(struct linux_binprm *bprm) { int mode; struct inode * inode = bprm->file->f_dentry->d_inode; int retval; mode = inode->i_mode; if (bprm->file->f_op == NULL) return -EACCES; bprm->e_uid = current->euid; bprm->e_gid = current->egid; if(!(bprm->file->f_vfsmnt->mnt_flags & MNT_NOSUID)) { /* Set-uid? */ if (mode & S_ISUID) { current->personality &= ~PER_CLEAR_ON_SETID; bprm->e_uid = inode->i_uid; } /* Set-gid? */ /* * If setgid is set but no group execute bit then this * is a candidate for mandatory locking, not a setgid * executable. */ if ((mode & (S_ISGID | S_IXGRP)) == (S_ISGID | S_IXGRP)) { current->personality &= ~PER_CLEAR_ON_SETID; bprm->e_gid = inode->i_gid; } } /* fill in binprm security blob */ retval = security_bprm_set(bprm); if (retval) return retval; memset(bprm->buf,0,BINPRM_BUF_SIZE); return kernel_read(bprm->file,0,bprm->buf,BINPRM_BUF_SIZE); } EXPORT_SYMBOL(prepare_binprm); static int unsafe_exec(struct task_struct *p) { int unsafe = 0; if (p->ptrace & PT_PTRACED) { if (p->ptrace & PT_PTRACE_CAP) unsafe |= LSM_UNSAFE_PTRACE_CAP; else unsafe |= LSM_UNSAFE_PTRACE; } if (atomic_read(&p->fs->count) > 1 || atomic_read(&p->files->count) > 1 || atomic_read(&p->sighand->count) > 1) unsafe |= LSM_UNSAFE_SHARE; return unsafe; } void compute_creds(struct linux_binprm *bprm) { int unsafe; if (bprm->e_uid != current->uid) suid_keys(current); exec_keys(current); task_lock(current); unsafe = unsafe_exec(current); security_bprm_apply_creds(bprm, unsafe); task_unlock(current); security_bprm_post_apply_creds(bprm); } EXPORT_SYMBOL(compute_creds); void remove_arg_zero(struct linux_binprm *bprm) { if (bprm->argc) { unsigned long offset; char * kaddr; struct page *page; offset = bprm->p % PAGE_SIZE; goto inside; while (bprm->p++, *(kaddr+offset++)) { if (offset != PAGE_SIZE) continue; offset = 0; kunmap_atomic(kaddr, KM_USER0); inside: page = bprm->page[bprm->p/PAGE_SIZE]; kaddr = kmap_atomic(page, KM_USER0); } kunmap_atomic(kaddr, KM_USER0); bprm->argc--; } } EXPORT_SYMBOL(remove_arg_zero); /* * cycle the list of binary formats handler, until one recognizes the image */ int search_binary_handler(struct linux_binprm *bprm,struct pt_regs *regs) { int try,retval; struct linux_binfmt *fmt; #ifdef __alpha__ /* handle /sbin/loader.. */ { struct exec * eh = (struct exec *) bprm->buf; if (!bprm->loader && eh->fh.f_magic == 0x183 && (eh->fh.f_flags & 0x3000) == 0x3000) { struct file * file; unsigned long loader; allow_write_access(bprm->file); fput(bprm->file); bprm->file = NULL; loader = PAGE_SIZE*MAX_ARG_PAGES-sizeof(void *); file = open_exec("/sbin/loader"); retval = PTR_ERR(file); if (IS_ERR(file)) return retval; /* Remember if the application is TASO. */ bprm->sh_bang = eh->ah.entry < 0x100000000UL; bprm->file = file; bprm->loader = loader; retval = prepare_binprm(bprm); if (retval<0) return retval; /* should call search_binary_handler recursively here, but it does not matter */ } } #endif retval = security_bprm_check(bprm); if (retval) return retval; /* kernel module loader fixup */ /* so we don't try to load run modprobe in kernel space. */ set_fs(USER_DS); retval = audit_bprm(bprm); if (retval) return retval; retval = -ENOENT; for (try=0; try<2; try++) { read_lock(&binfmt_lock); for (fmt = formats ; fmt ; fmt = fmt->next) { int (*fn)(struct linux_binprm *, struct pt_regs *) = fmt->load_binary; if (!fn) continue; if (!try_module_get(fmt->module)) continue; read_unlock(&binfmt_lock); retval = fn(bprm, regs); if (retval >= 0) { put_binfmt(fmt); allow_write_access(bprm->file); if (bprm->file) fput(bprm->file); bprm->file = NULL; current->did_exec = 1; proc_exec_connector(current); return retval; } read_lock(&binfmt_lock); put_binfmt(fmt); if (retval != -ENOEXEC || bprm->mm == NULL) break; if (!bprm->file) { read_unlock(&binfmt_lock); return retval; } } read_unlock(&binfmt_lock); if (retval != -ENOEXEC || bprm->mm == NULL) { break; #ifdef CONFIG_KMOD }else{ #define printable(c) (((c)=='\t') || ((c)=='\n') || (0x20<=(c) && (c)<=0x7e)) if (printable(bprm->buf[0]) && printable(bprm->buf[1]) && printable(bprm->buf[2]) && printable(bprm->buf[3])) break; /* -ENOEXEC */ request_module("binfmt-%04x", *(unsigned short *)(&bprm->buf[2])); #endif } } return retval; } EXPORT_SYMBOL(search_binary_handler); /* * sys_execve() executes a new program. */ int do_execve(char * filename, char __user *__user *argv, char __user *__user *envp, struct pt_regs * regs) { struct linux_binprm *bprm; struct file *file; int retval; int i; retval = -ENOMEM; bprm = kzalloc(sizeof(*bprm), GFP_KERNEL); if (!bprm) goto out_ret; file = open_exec(filename); retval = PTR_ERR(file); if (IS_ERR(file)) goto out_kfree; sched_exec(); bprm->p = PAGE_SIZE*MAX_ARG_PAGES-sizeof(void *); printk("%s bprm->p=0x%08x\n",__FUNCTION__,bprm->p); bprm->file = file; bprm->filename = filename; bprm->interp = filename; bprm->mm = mm_alloc(); retval = -ENOMEM; if (!bprm->mm) goto out_file; retval = init_new_context(current, bprm->mm); if (retval < 0) goto out_mm; bprm->argc = count(argv, bprm->p / sizeof(void *)); if ((retval = bprm->argc) < 0) goto out_mm; bprm->envc = count(envp, bprm->p / sizeof(void *)); if ((retval = bprm->envc) < 0) goto out_mm; retval = security_bprm_alloc(bprm); if (retval) goto out; retval = prepare_binprm(bprm); if (retval < 0) goto out; retval = copy_strings_kernel(1, &bprm->filename, bprm); if (retval < 0) goto out; bprm->exec = bprm->p; retval = copy_strings(bprm->envc, envp, bprm); if (retval < 0) goto out; retval = copy_strings(bprm->argc, argv, bprm); if (retval < 0) goto out; retval = search_binary_handler(bprm,regs); if (retval >= 0) { free_arg_pages(bprm); /* execve success */ security_bprm_free(bprm); acct_update_integrals(current); kfree(bprm); return retval; } out: /* Something went wrong, return the inode and free the argument pages*/ for (i = 0 ; i < MAX_ARG_PAGES ; i++) { struct page * page = bprm->page[i]; if (page) __free_page(page); } if (bprm->security) security_bprm_free(bprm); out_mm: if (bprm->mm) mmdrop(bprm->mm); out_file: if (bprm->file) { allow_write_access(bprm->file); fput(bprm->file); } out_kfree: kfree(bprm); out_ret: return retval; } int set_binfmt(struct linux_binfmt *new) { struct linux_binfmt *old = current->binfmt; if (new) { if (!try_module_get(new->module)) return -1; } current->binfmt = new; if (old) module_put(old->module); return 0; } EXPORT_SYMBOL(set_binfmt); #define CORENAME_MAX_SIZE 64 /* format_corename will inspect the pattern parameter, and output a * name into corename, which must have space for at least * CORENAME_MAX_SIZE bytes plus one byte for the zero terminator. */ static void format_corename(char *corename, const char *pattern, long signr) { const char *pat_ptr = pattern; char *out_ptr = corename; char *const out_end = corename + CORENAME_MAX_SIZE; int rc; int pid_in_pattern = 0; /* Repeat as long as we have more pattern to process and more output space */ while (*pat_ptr) { if (*pat_ptr != '%') { if (out_ptr == out_end) goto out; *out_ptr++ = *pat_ptr++; } else { switch (*++pat_ptr) { case 0: goto out; /* Double percent, output one percent */ case '%': if (out_ptr == out_end) goto out; *out_ptr++ = '%'; break; /* pid */ case 'p': pid_in_pattern = 1; rc = snprintf(out_ptr, out_end - out_ptr, "%d", current->tgid); if (rc > out_end - out_ptr) goto out; out_ptr += rc; break; /* uid */ case 'u': rc = snprintf(out_ptr, out_end - out_ptr, "%d", current->uid); if (rc > out_end - out_ptr) goto out; out_ptr += rc; break; /* gid */ case 'g': rc = snprintf(out_ptr, out_end - out_ptr, "%d", current->gid); if (rc > out_end - out_ptr) goto out; out_ptr += rc; break; /* signal that caused the coredump */ case 's': rc = snprintf(out_ptr, out_end - out_ptr, "%ld", signr); if (rc > out_end - out_ptr) goto out; out_ptr += rc; break; /* UNIX time of coredump */ case 't': { struct timeval tv; do_gettimeofday(&tv); rc = snprintf(out_ptr, out_end - out_ptr, "%lu", tv.tv_sec); if (rc > out_end - out_ptr) goto out; out_ptr += rc; break; } /* hostname */ case 'h': down_read(&uts_sem); rc = snprintf(out_ptr, out_end - out_ptr, "%s", utsname()->nodename); up_read(&uts_sem); if (rc > out_end - out_ptr) goto out; out_ptr += rc; break; /* executable */ case 'e': rc = snprintf(out_ptr, out_end - out_ptr, "%s", current->comm); if (rc > out_end - out_ptr) goto out; out_ptr += rc; break; default: break; } ++pat_ptr; } } /* Backward compatibility with core_uses_pid: * * If core_pattern does not include a %p (as is the default) * and core_uses_pid is set, then .%pid will be appended to * the filename */ if (!pid_in_pattern && (core_uses_pid || atomic_read(&current->mm->mm_users) != 1)) { rc = snprintf(out_ptr, out_end - out_ptr, ".%d", current->tgid); if (rc > out_end - out_ptr) goto out; out_ptr += rc; } out: *out_ptr = 0; } static void zap_process(struct task_struct *start) { struct task_struct *t; start->signal->flags = SIGNAL_GROUP_EXIT; start->signal->group_stop_count = 0; t = start; do { if (t != current && t->mm) { t->mm->core_waiters++; sigaddset(&t->pending.signal, SIGKILL); signal_wake_up(t, 1); } } while ((t = next_thread(t)) != start); } static inline int zap_threads(struct task_struct *tsk, struct mm_struct *mm, int exit_code) { struct task_struct *g, *p; unsigned long flags; int err = -EAGAIN; spin_lock_irq(&tsk->sighand->siglock); if (!(tsk->signal->flags & SIGNAL_GROUP_EXIT)) { tsk->signal->group_exit_code = exit_code; zap_process(tsk); err = 0; } spin_unlock_irq(&tsk->sighand->siglock); if (err) return err; if (atomic_read(&mm->mm_users) == mm->core_waiters + 1) goto done; rcu_read_lock(); for_each_process(g) { if (g == tsk->group_leader) continue; p = g; do { if (p->mm) { if (p->mm == mm) { /* * p->sighand can't disappear, but * may be changed by de_thread() */ lock_task_sighand(p, &flags); zap_process(p); unlock_task_sighand(p, &flags); } break; } } while ((p = next_thread(p)) != g); } rcu_read_unlock(); done: return mm->core_waiters; } static int coredump_wait(int exit_code) { struct task_struct *tsk = current; struct mm_struct *mm = tsk->mm; struct completion startup_done; struct completion *vfork_done; int core_waiters; init_completion(&mm->core_done); init_completion(&startup_done); mm->core_startup_done = &startup_done; core_waiters = zap_threads(tsk, mm, exit_code); up_write(&mm->mmap_sem); if (unlikely(core_waiters < 0)) goto fail; /* * Make sure nobody is waiting for us to release the VM, * otherwise we can deadlock when we wait on each other */ vfork_done = tsk->vfork_done; if (vfork_done) { tsk->vfork_done = NULL; complete(vfork_done); } if (core_waiters) wait_for_completion(&startup_done); fail: BUG_ON(mm->core_waiters); return core_waiters; } /* for systems with sizeof(void*) == 4: */ #define MAPS_LINE_FORMAT4 KERN_ERR "%08lx-%08lx %s %08lx %02x:%02x %lu %s\n" /* for systems with sizeof(void*) == 8: */ #define MAPS_LINE_FORMAT8 KERN_ERR "%016lx-%016lx %s %016lx %02x:%02x %lu %s\n" #define MAPS_LINE_FORMAT (sizeof(void*) == 4 ? MAPS_LINE_FORMAT4 : MAPS_LINE_FORMAT8) int do_coredump(long signr, int exit_code, struct pt_regs * regs) { char corename[CORENAME_MAX_SIZE + 1]; struct mm_struct *mm = current->mm; struct linux_binfmt * binfmt; struct inode * inode; struct file * file; int retval = 0; int fsuid = current->fsuid; int flag = 0; int ispipe = 0; #ifdef CONFIG_COREDUMP_PRINTK int32_t *stack=NULL; int lines=0; char output_buf[80]; char *output = output_buf; int32_t value = 0; printk(KERN_ERR "%s[%d] killed because of sig - %ld", current->comm, current->pid, signr); /* TODO * print out mmaps. */ /* * We print out the stack. We start by pointing the stack before the * call to do_coredump. Note that we are assuming the kernel stack is * the same as the user stack when we are calling do_coredump. */ printk("\n"); printk(KERN_ERR"STACK DUMP:\n"); for (lines=0,stack=(int32_t *)user_stack(regs);(lines < 10) && (stack <= (int32_t *)current->mm->start_stack);lines++) { /* print out the address */ output+=snprintf(output, 79-(output-output_buf), "0x%08x: ", (unsigned)stack); /* now print out the stack contents */ for (;(stack <= (int32_t*)current->mm->start_stack) && (79-(output-output_buf) > sizeof("FFFF0000 "));stack++) { copy_from_user(&value, stack, sizeof(int32_t)); output += snprintf(output, 79-(output-output_buf), "%08x ", value); } output--; *output++ = '\n'; *output = '\0'; printk(KERN_ERR "%s", output_buf); output = output_buf; } show_regs(regs); #ifdef CONFIG_MMU { struct mm_struct *mm=NULL; struct vm_area_struct *map; char buf[PAGE_SIZE]={0}; int flags=0; char *line; dev_t dev = 0; unsigned long ino = 0; mm = current->mm; if (mm) atomic_inc(&mm->mm_users); if (!mm) goto finished; down_read(&mm->mmap_sem); map = mm->mmap; while (map) { char str[5]; if (map->vm_file != NULL) { dev = map->vm_file->f_dentry->d_inode->i_sb->s_dev; ino = map->vm_file->f_dentry->d_inode->i_ino; line = d_path(map->vm_file->f_dentry, map->vm_file->f_vfsmnt, buf, sizeof(buf)); } else { line=NULL; } flags = map->vm_flags; str[0] = flags & VM_READ ? 'r' : '-'; str[1] = flags & VM_WRITE ? 'w' : '-'; str[2] = flags & VM_EXEC ? 'x' : '-'; str[3] = flags & VM_MAYSHARE ? 's' : 'p'; str[4] = 0; printk(MAPS_LINE_FORMAT, map->vm_start, map->vm_end, str, map->vm_pgoff << PAGE_SHIFT, MAJOR(dev), MINOR(dev), ino, line?line:""); map = map->vm_next; } up_read(&mm->mmap_sem); mmput(mm); } #else /* * How do we find base address of shared libs?? */ #endif finished: #endif binfmt = current->binfmt; if (!binfmt || !binfmt->core_dump) goto fail; down_write(&mm->mmap_sem); if (!mm->dumpable) { up_write(&mm->mmap_sem); goto fail; } /* * We cannot trust fsuid as being the "true" uid of the * process nor do we know its entire history. We only know it * was tainted so we dump it as root in mode 2. */ if (mm->dumpable == 2) { /* Setuid core dump mode */ flag = O_EXCL; /* Stop rewrite attacks */ current->fsuid = 0; /* Dump root private */ } mm->dumpable = 0; retval = coredump_wait(exit_code); if (retval < 0) goto fail; /* * Clear any false indication of pending signals that might * be seen by the filesystem code called to write the core file. */ clear_thread_flag(TIF_SIGPENDING); if (current->signal->rlim[RLIMIT_CORE].rlim_cur < binfmt->min_coredump) goto fail_unlock; /* * lock_kernel() because format_corename() is controlled by sysctl, which * uses lock_kernel() */ lock_kernel(); format_corename(corename, core_pattern, signr); unlock_kernel(); if (corename[0] == '|') { /* SIGPIPE can happen, but it's just never processed */ if(call_usermodehelper_pipe(corename+1, NULL, NULL, &file)) { printk(KERN_INFO "Core dump to %s pipe failed\n", corename); goto fail_unlock; } ispipe = 1; } else file = filp_open(corename, O_CREAT | 2 | O_NOFOLLOW | O_LARGEFILE, 0600); if (IS_ERR(file)) goto fail_unlock; inode = file->f_dentry->d_inode; if (inode->i_nlink > 1) goto close_fail; /* multiple links - don't dump */ if (!ispipe && d_unhashed(file->f_dentry)) goto close_fail; /* AK: actually i see no reason to not allow this for named pipes etc., but keep the previous behaviour for now. */ if (!ispipe && !S_ISREG(inode->i_mode)) goto close_fail; if (!file->f_op) goto close_fail; if (!file->f_op->write) goto close_fail; if (!ispipe && do_truncate(file->f_dentry, 0, 0, file) != 0) goto close_fail; retval = binfmt->core_dump(signr, regs, file); if (retval) current->signal->group_exit_code |= 0x80; close_fail: filp_close(file, NULL); fail_unlock: current->fsuid = fsuid; complete_all(&mm->core_done); fail: return retval; }
Voskrese/mipsonqemu
linux-2.6.x/fs/exec.c
C
gpl-2.0
38,701
/* This file is part of BGSLibrary. BGSLibrary 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. BGSLibrary 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 BGSLibrary. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include <iostream> #include <cv.h> #include <highgui.h> #include "IBGS.h" class WeightedMovingMeanBGS : public IBGS { private: bool firstTime; cv::Mat img_input_prev_1; cv::Mat img_input_prev_2; bool enableWeight; bool enableThreshold; int threshold; bool showOutput; bool showBackground; public: WeightedMovingMeanBGS(); ~WeightedMovingMeanBGS(); void process(const cv::Mat &img_input, cv::Mat &img_output, cv::Mat &img_bgmodel); private: void saveConfig(); void loadConfig(); };
Skythunder/ARPool
ARPool/package_bgs/WeightedMovingMeanBGS.h
C
gpl-2.0
1,174
<?php /* Plugin Name: Easy Mashable Social Box Plugin URI: http://www.incrediblogger.net/wordpress/plugins/easy-mashable-social-bar-plugin-recoded-cleaned/ Description: This beautiful <a href="http://www.incrediblogger.net/wordpress/plugins/easy-mashable-social-bar-plugin-recoded-cleaned/" target="_blank"><strong>Easy Mashable Social Box</strong></a> wordpress plugin is inspired by Mashable.com, coded by <a href="http://www.incrediblogger.net/" target="_blank"><strong>IncrediBlogger</strong></a>. Original plugin coded by InspiredMagz. This version is free from any hidden links. Every setting of this plugin can be set on the widget page section. Just drag-and-drop the widget to the sidebar. If you are facing any problem with this widget or bug, please drop me a comment at this link, <a href="http://www.incrediblogger.net/wordpress/plugins/easy-mashable-social-bar-plugin-recoded-cleaned/" target="_blank"><strong>Easy Mashable Social Box plugin</strong></a>. Version: 1.1.4 Author: Prasenjit Author URI: http://www.incrediblogger.net/ License: GPLv2 */ class incredibloggermashable extends WP_Widget { function incredibloggermashable() { $widget_ops = array('classname' => 'incredibloggermashable', 'description' => __('Display your social profiles on sidebar. This is Easy Mashable Social Box plugin by IncrediBlogger')); $control_ops = array('width' => 250, 'height' => 350); $this->WP_Widget('incredibloggermashable', __('Easy Mashable Social Box'), $widget_ops, $control_ops); } function head() { $siteurl = get_option('siteurl'); $url = $siteurl . '/wp-content/plugins/' . basename(dirname(__FILE__)) . '/styles.css'; echo "<link rel='stylesheet' type='text/css' href='$url' />\n"; } function widget( $args, $instance ) { extract($args); $feedburner_id = $instance['feedburner_id']; $twitter_id = $instance['twitter_id']; $facebook_id = $instance['facebook_id']; $feedburner_email_id = $instance['feedburner_email_id']; $googleplus_id = $instance['googleplus_id']; $widgetwidth_id = $instance['widgetwidth_id']; $fbwidth_id = $instance['fbwidth_id']; $fbheight_id = $instance['fbheight_id']; $recommend_id = $instance['recommend_id']; $emailwidth_id = $instance['emailwidth_id']; $emailtext_id = $instance['emailtext_id']; $footerurl_id = $instance['footerurl_id']; $footertext_id = $instance['footertext_id']; $fbboxcolor_id = $instance['fbboxcolor_id']; $gpluscolor_id = $instance['gpluscolor_id']; $twitcolor_id = $instance['twitcolor_id']; $emailcolor_id = $instance['emailcolor_id']; $othercolor_id = $instance['othercolor_id']; $show_add_to_circles = $instance['show_add_to_circles']; $show_google_small_badge = $instance['show_google_small_badge']; $gplus_theme = $instance['gplus_theme']; $show_fb_faces = $instance['show_fb_faces']; $show_author_credit = $instance['show_author_credit']; ?> <!--begin of social widget--> <div style="margin-bottom:10px;"> <div id="inspiredmagz-mashable-bar" style="width:<?php echo $widgetwidth_id; ?>px;"> <!-- Begin Widget --> <!-- Place this tag where you want the badge to render --> <h3>Subscribe to True Artists</h3> <?php if($show_add_to_circles == 1) { ?> <div class="fb-subscribe" style="background-color: white; padding:10px; border: 1px solid #dcdcdc; width: 278px; margin-bottom: 18px;" data-href="http://www.facebook.com/trueartistscontacts" data-show-faces="true" data-width="280"></div> <div class="g-plus" data-href="https://plus.google.com/<?php echo $googleplus_id; ?>" data-height="<?php if ($show_google_small_badge == 1) { ?>69<?php } else { ?>131<?php } ?>" data-theme="<?php if($gplus_theme == 1) {echo 'light';} else {echo 'dark';} ?>"></div> <?php } ?> <div class="fb-likebox" style="background: <?php echo $fbboxcolor_id; ?>;"> <!-- Facebook --> <iframe src="//www.facebook.com/plugins/like.php?href=<?php echo $facebook_id; ?>&amp;send=false&amp;layout=standard&amp;width=<?php echo $fbwidth_id; ?>&amp;show_faces=<?php if($show_fb_faces == 1) { echo 'true'; } else { echo 'false'; } ?>&amp;action=like&amp;colorscheme=light&amp;font&amp;height=<?php echo $fbheight_id; ?>&amp;appId=234513819928295" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:<?php echo $fbwidth_id; ?>px; height:<?php echo $fbheight_id; ?>px;"></iframe> </div> <div class="googleplus" style="background: <?php echo $gpluscolor_id; ?>;"> <!-- Google --> <span><?php echo $recommend_id; ?></span><div class="g-plusone" data-size="medium"></div> <script type="text/javascript" src="https://apis.google.com/js/plusone.js"></script> </div> <div class="twitter" style="background: <?php echo $twitcolor_id; ?>;"> <!-- Twitter --> <iframe title="" style="width: 300px; height: 20px;" class="twitter-follow-button" src="http://platform.twitter.com/widgets/follow_button.html#_=1319978796351&amp;align=&amp;button=blue&amp;id=twitter_tweet_button_0&amp;lang=en&amp;link_color=&amp;screen_name=<?php echo $twitter_id; ?>&amp;show_count=&amp;show_screen_name=&amp;text_color=" frameborder="0" scrolling="no"></iframe> </div> <div id="email-news-subscribe" style="background: <?php echo $emailcolor_id; ?>;"> <!-- Email Subscribe --> <div class="email-box"> <form action="http://feedburner.google.com/fb/a/mailverify" method="post" target="popupwindow" onsubmit="window.open('http://feedburner.google.com/fb/a/mailverify?uri=<?php echo $feedburner_id; ?>', 'popupwindow', 'scrollbars=yes,width=550,height=520');return true"> <input class="email" type="text" style="width: <?php echo $emailwidth_id; ?>px; font-size: 12px;" id="email" name="email" value="<?php echo $emailtext_id; ?>" onfocus="if(this.value==this.defaultValue)this.value='';" onblur="if(this.value=='')this.value=this.defaultValue;"> <input type="hidden" value="<?php echo $feedburner_id; ?>" name="uri"> <input type="hidden" name="loc" value="en_US"> <input class="subscribe" name="commit" type="submit" value="Subscribe"> </form> </div> </div> <div id="other-social-bar" style="background: <?php echo $othercolor_id; ?>;"> <!-- Other Social Bar --> <ul class="other-follow"> <li class="my-rss"> <a rel="nofollow" title="RSS" href="http://feeds.feedburner.com/<?php echo $feedburner_id; ?>" target="_blank">RSS Feed</a> </li> <?php if($feedburner_email_id != null && $feedburner_email_id != "") { ?> <li class="my-email"> <a rel="nofollow external" title="Email Updates" href="http://feedburner.google.com/fb/a/mailverify?uri=<?php echo $feedburner_email_id; ?>&loc=en_US" target="_blank">Email Updates</a> </li> <?php } ?> <li class="my-gplus"> <a rel="nofollow" title="Google Plus" rel="author" href="http://plus.google.com/<?php echo $googleplus_id; ?>" target="_blank">Google Plus</a> </li> </ul> </div> <div id="get-inspiredmagz" style="background: #EBEBEB;border: 1px solid #CCC;border-top: 1px solid white;padding: 1px 8px 1px 3px;text-align: right;border-image: initial;font-size:10px;font-family: "Arial","Helvetica",sans-serif;"> <?php if($show_author_credit == 1) { ?><span class="author-credit" style="font-family: Arial, Helvetica, sans-serif;"><a href="<?php echo $footerurl_id; ?>" target="_blank" title="<?php echo $footertext_id; ?>"><?php echo $footertext_id; ?> »</a></span><?php } ?></div></div> <!-- End Widget --> </div> <!--end of social widget--> <?php } function update( $new_instance, $old_instance ) { $instance = $old_instance; $instance['feedburner_id'] = $new_instance['feedburner_id']; $instance['twitter_id'] = $new_instance['twitter_id']; $instance['facebook_id'] = $new_instance['facebook_id']; $instance['feedburner_email_id'] = $new_instance['feedburner_email_id']; $instance['googleplus_id'] = $new_instance['googleplus_id']; $instance['widgetwidth_id'] = $new_instance['widgetwidth_id']; $instance['fbwidth_id'] = $new_instance['fbwidth_id']; $instance['fbheight_id'] = $new_instance['fbheight_id']; $instance['recommend_id'] = $new_instance['recommend_id']; $instance['emailwidth_id'] = $new_instance['emailwidth_id']; $instance['emailtext_id'] = $new_instance['emailtext_id']; $instance['fbboxcolor_id'] = $new_instance['fbboxcolor_id']; $instance['gpluscolor_id'] = $new_instance['gpluscolor_id']; $instance['twitcolor_id'] = $new_instance['twitcolor_id']; $instance['emailcolor_id'] = $new_instance['emailcolor_id']; $instance['othercolor_id'] = $new_instance['othercolor_id']; $instance['show_add_to_circles'] = $new_instance['show_add_to_circles']; $instance['show_google_small_badge'] = $new_instance['show_google_small_badge']; $instance['gplus_theme'] = $new_instance['gplus_theme']; $instance['show_fb_faces'] = $new_instance['show_fb_faces']; $instance['show_author_credit'] = $new_instance['show_author_credit']; return $instance; } function form( $instance ) { $instance = wp_parse_args( (array) $instance, array( 'feedburner_id' => 'Incrediblogger', 'twitter_id' => 'Incrediblogger', 'facebook_id' => 'http://www.facebook.com/pages/IncrediBlogger/187134431340419', 'fbwidth_id' => '270', 'fbheight_id' => '80', 'recommend_id' => 'Recommend on Google', 'emailwidth_id' => '140', 'emailtext_id' => 'Enter your email', 'footerurl_id' => 'http://www.incrediblogger.net/wordpress/plugins/easy-mashable-social-bar-plugin-recoded-cleaned/', 'footertext_id' => 'Get this plugin', 'fbboxcolor_id' => '#FFF', 'gpluscolor_id' => '#F5FCFE', 'twitcolor_id' => '#EEF9FD', 'emailcolor_id' => '#E3EDF4', 'othercolor_id' => '#D8E6EB', 'feedburner_email_id' => 'Incrediblogger', 'googleplus_id' => '100470876568345536294', 'widgetwidth_id' => '280', 'show_add_to_circles' => '1', 'show_fb_faces' => '1', 'show_google_small_badge' => '1', 'gplus_theme' => '1', 'show_author_credit' => '1' ) ); $feedburner_id = $instance['feedburner_id']; $twitter_id = format_to_edit($instance['twitter_id']); $facebook_id = format_to_edit($instance['facebook_id']); $feedburner_email_id = format_to_edit($instance['feedburner_email_id']); $googleplus_id = format_to_edit($instance['googleplus_id']); $widgetwidth_id = format_to_edit($instance['widgetwidth_id']); $fbwidth_id = format_to_edit($instance['fbwidth_id']); $fbheight_id = format_to_edit($instance['fbheight_id']); $recommend_id = format_to_edit($instance['recommend_id']); $emailwidth_id = format_to_edit($instance['emailwidth_id']); $emailtext_id = format_to_edit($instance['emailtext_id']); $fbboxcolor_id = format_to_edit($instance['fbboxcolor_id']); $gpluscolor_id = format_to_edit($instance['gpluscolor_id']); $twitcolor_id = format_to_edit($instance['twitcolor_id']); $emailcolor_id = format_to_edit($instance['emailcolor_id']); $othercolor_id = format_to_edit($instance['othercolor_id']); $show_add_to_circles = format_to_edit($instance['show_add_to_circles']); $show_google_small_badge = format_to_edit($instance['show_google_small_badge']); $gplus_theme = format_to_edit($instance['gplus_theme']); $show_fb_faces = format_to_edit($instance['show_fb_faces']); $show_author_credit = format_to_edit($instance['show_author_credit']); ?> <center><strong><u>Social Profiles Setting</u></strong></center><br /> <p><label for="<?php echo $this->get_field_id('feedburner_id'); ?>"><?php _e('Enter your Feedburner ID:'); ?></label> <input class="widefat" id="<?php echo $this->get_field_id('feedburner_id'); ?>" name="<?php echo $this->get_field_name('feedburner_id'); ?>" type="text" value="<?php echo $feedburner_id; ?>" /></p> <p><label for="<?php echo $this->get_field_id('twitter_id'); ?>"><?php _e('Enter your Twitter ID:'); ?></label> <input class="widefat" type="text" id="<?php echo $this->get_field_id('twitter_id'); ?>" name="<?php echo $this->get_field_name('twitter_id'); ?>" value="<?php echo $twitter_id; ?>" /></p> <p><label for="<?php echo $this->get_field_id('facebook_id'); ?>"><?php _e('Enter your Facebook URL:'); ?></label> <input class="widefat" type="text" id="<?php echo $this->get_field_id('image'); ?>" name="<?php echo $this->get_field_name('facebook_id'); ?>" value="<?php echo $facebook_id; ?>" /></p> <p><label for="<?php echo $this->get_field_id('feedburner_email_id'); ?>"><?php _e('Enter your Feedburner Email ID:'); ?></label> <input class="widefat" type="text" id="<?php echo $this->get_field_id('image'); ?>" name="<?php echo $this->get_field_name('feedburner_email_id'); ?>" value="<?php echo $feedburner_email_id; ?>" /></p> <p><label for="<?php echo $this->get_field_id('googleplus_id'); ?>"><?php _e('Enter your Google+ ID:'); ?></label> <input class="widefat" type="text" id="<?php echo $this->get_field_id('image'); ?>" name="<?php echo $this->get_field_name('googleplus_id'); ?>" value="<?php echo $googleplus_id; ?>" /></p> <center><strong><u>Other Settings</u></strong></center><br /> <p><label for="<?php echo $this->get_field_id('widgetwidth_id'); ?>"><?php _e('Widget width(px):'); ?></label> <input class="widefat" type="text" id="<?php echo $this->get_field_id('image'); ?>" name="<?php echo $this->get_field_name('widgetwidth_id'); ?>" value="<?php echo $widgetwidth_id; ?>" /></p> <p><label for="<?php echo $this->get_field_id('fbwidth_id'); ?>"><?php _e('Facebook width(px):'); ?></label> <input class="widefat" type="text" id="<?php echo $this->get_field_id('image'); ?>" name="<?php echo $this->get_field_name('fbwidth_id'); ?>" value="<?php echo $fbwidth_id; ?>" /></p> <p><label for="<?php echo $this->get_field_id('fbheight_id'); ?>"><?php _e('Facebook height(px): If Show FB faces is set to true, then please set the height to a minimum of 80'); ?></label> <input class="widefat" type="text" id="<?php echo $this->get_field_id('image'); ?>" name="<?php echo $this->get_field_name('fbheight_id'); ?>" value="<?php echo $fbheight_id; ?>" /></p> <p><label for="<?php echo $this->get_field_id('recommend_id'); ?>"><?php _e('Google recommend text:'); ?></label> <input class="widefat" type="text" id="<?php echo $this->get_field_id('image'); ?>" name="<?php echo $this->get_field_name('recommend_id'); ?>" value="<?php echo $recommend_id; ?>" /></p> <p><label for="<?php echo $this->get_field_id('emailwidth_id'); ?>"><?php _e('Subscription box width(px):'); ?></label> <input class="widefat" type="text" id="<?php echo $this->get_field_id('image'); ?>" name="<?php echo $this->get_field_name('emailwidth_id'); ?>" value="<?php echo $emailwidth_id; ?>" /></p> <p><label for="<?php echo $this->get_field_id('emailtext_id'); ?>"><?php _e('Subscription box text:'); ?></label> <input class="widefat" type="text" id="<?php echo $this->get_field_id('image'); ?>" name="<?php echo $this->get_field_name('emailtext_id'); ?>" value="<?php echo $emailtext_id; ?>" /></p> <center><strong><u>Background Color Settings</u></strong><br />[Get color code list <a href="http://html-color-codes.info/" rel="nofollow" title="Get color code list here" target="_blank"><strong>HERE</strong></a>]</center><br /> <p><label for="<?php echo $this->get_field_id('fbboxcolor_id'); ?>"><?php _e('Facebook: Default: #FFFFFF'); ?></label> <input class="widefat" type="text" id="<?php echo $this->get_field_id('image'); ?>" name="<?php echo $this->get_field_name('fbboxcolor_id'); ?>" value="<?php echo $fbboxcolor_id; ?>" /></p> <p><label for="<?php echo $this->get_field_id('gpluscolor_id'); ?>"><?php _e('Google: Default: #F5FCFE'); ?></label> <input class="widefat" type="text" id="<?php echo $this->get_field_id('image'); ?>" name="<?php echo $this->get_field_name('gpluscolor_id'); ?>" value="<?php echo $gpluscolor_id; ?>" /></p> <p><label for="<?php echo $this->get_field_id('twitcolor_id'); ?>"><?php _e('Twitter: Default: #EEF9FD'); ?></label> <input class="widefat" type="text" id="<?php echo $this->get_field_id('image'); ?>" name="<?php echo $this->get_field_name('twitcolor_id'); ?>" value="<?php echo $twitcolor_id; ?>" /></p> <p><label for="<?php echo $this->get_field_id('emailcolor_id'); ?>"><?php _e('Subscription: Default: #E3EDF4'); ?></label> <input class="widefat" type="text" id="<?php echo $this->get_field_id('image'); ?>" name="<?php echo $this->get_field_name('emailcolor_id'); ?>" value="<?php echo $emailcolor_id; ?>" /></p> <p><label for="<?php echo $this->get_field_id('othercolor_id'); ?>"><?php _e('RSS, LinkedIn, Google+: Default: #D8E6EB'); ?></label> <input class="widefat" type="text" id="<?php echo $this->get_field_id('image'); ?>" name="<?php echo $this->get_field_name('othercolor_id'); ?>" value="<?php echo $othercolor_id; ?>" /></p> <p><label for="<?php echo $this->get_field_id( 'show_add_to_circles' ); ?>">Show Add to G+ Circle Badge: Default: Yes</label> <select id="<?php echo $this->get_field_id( 'show_add_to_circles' ); ?>" name="<?php echo $this->get_field_name( 'show_add_to_circles' ); ?>"> <option value="0"<?php if ( '0' == $instance['show_add_to_circles'] ) echo 'selected="selected"'; ?>>No</option> <option value="1"<?php if ( '1' == $instance['show_add_to_circles'] ) echo 'selected="selected"'; ?>>Yes</option> </select></p> <p><label for="<?php echo $this->get_field_id( 'show_fb_faces' ); ?>">Show Facebook Faces: Default: Yes</label> <select id="<?php echo $this->get_field_id( 'show_fb_faces' ); ?>" name="<?php echo $this->get_field_name( 'show_fb_faces' ); ?>"> <option value="0"<?php if ( '0' == $instance['show_fb_faces'] ) echo 'selected="selected"'; ?>>No</option> <option value="1"<?php if ( '1' == $instance['show_fb_faces'] ) echo 'selected="selected"'; ?>>Yes</option> </select></p> <p><label for="<?php echo $this->get_field_id( 'show_google_small_badge' ); ?>">G+ Badge Style: Default: Small</label> <select id="<?php echo $this->get_field_id( 'show_google_small_badge' ); ?>" name="<?php echo $this->get_field_name( 'show_google_small_badge' ); ?>"> <option value="0"<?php if ( '0' == $instance['show_google_small_badge'] ) echo 'selected="selected"'; ?>>Standard</option> <option value="1"<?php if ( '1' == $instance['show_google_small_badge'] ) echo 'selected="selected"'; ?>>Small</option> </select></p> <p><label for="<?php echo $this->get_field_id( 'gplus_theme' ); ?>">G+ Small Badge Theme(Light/Dark) Default: Light</label> <select id="<?php echo $this->get_field_id( 'gplus_theme' ); ?>" name="<?php echo $this->get_field_name( 'gplus_theme' ); ?>"> <option value="0"<?php if ( '0' == $instance['gplus_theme'] ) echo 'selected="selected"'; ?>>Dark</option> <option value="1"<?php if ( '1' == $instance['gplus_theme'] ) echo 'selected="selected"'; ?>>Light</option> </select></p> <p><label for="<?php echo $this->get_field_id( 'show_author_credit' ); ?>">Show Author Credit: Default: Yes</label> <select id="<?php echo $this->get_field_id( 'show_author_credit' ); ?>" name="<?php echo $this->get_field_name( 'show_author_credit' ); ?>"> <option value="0"<?php if ( '0' == $instance['show_author_credit'] ) echo 'selected="selected"'; ?>>No</option> <option value="1"<?php if ( '1' == $instance['show_author_credit'] ) echo 'selected="selected"'; ?>>Yes</option> </select></p> <?php } } add_action('widgets_init', create_function('', 'return register_widget(\'incredibloggermashable\');')); add_action('wp_head', array('incredibloggermashable', 'head'));
jwachira/tablog
wp-content/plugins/easy-mashable-social-bar/Easy-Mashable-Social-Bar.php
PHP
gpl-2.0
19,594
/******************** PhyloBayes MPI. Copyright 2010-2013 Nicolas Lartillot, Nicolas Rodrigue, Daniel Stubbs, Jacques Richer. PhyloBayes 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. PhyloBayes 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 PhyloBayes. If not, see <http://www.gnu.org/licenses/>. **********************/ #ifndef CODONMUTSELSBDPSUB_H #define CODONMUTSELSBDPSUB_H #include "CodonMutSelSBDPProfileProcess.h" #include "UniformRateProcess.h" #include "GeneralPathSuffStatMatrixSubstitutionProcess.h" class CodonMutSelSBDPSubstitutionProcess : public virtual CodonMutSelSBDPProfileProcess, public virtual UniformRateProcess, public virtual GeneralPathSuffStatMatrixSubstitutionProcess { // s'inspirer de GeneralPathSuffStatGTRSubstitutionProcess // et GeneralPathSuffStatRASCATGTRSubstitutionProcess public: CodonMutSelSBDPSubstitutionProcess() {} virtual ~CodonMutSelSBDPSubstitutionProcess() {} virtual int GetNstate() {return GetNcodon();} protected: void Create() { CodonMutSelSBDPProfileProcess::Create(); UniformRateProcess::Create(); GeneralPathSuffStatMatrixSubstitutionProcess::Create(); } void Delete() { GeneralPathSuffStatMatrixSubstitutionProcess::Delete(); UniformRateProcess::Delete(); CodonMutSelSBDPProfileProcess::Delete(); } }; #endif
bayesiancook/pbmpi2
sources/CodonMutSelSBDPSubstitutionProcess.h
C
gpl-2.0
1,739
<!DOCTYPE html> <html xml:lang="en-US" lang="en-US" xmlns="http://www.w3.org/1999/xhtml"> <head lang="en-US"> <title>My Family Tree - Michaud, Anna Eva</title> <meta charset="UTF-8" /> <meta name ="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=1" /> <meta name ="apple-mobile-web-app-capable" content="yes" /> <meta name="generator" content="Gramps 4.2.2 http://gramps-project.org/" /> <meta name="author" content="" /> <link href="../../../images/favicon2.ico" rel="shortcut icon" type="image/x-icon" /> <link href="../../../css/narrative-screen.css" media="screen" rel="stylesheet" type="text/css" /> <link href="../../../css/narrative-print.css" media="print" rel="stylesheet" type="text/css" /> <link href="../../../css/ancestortree.css" media="screen" rel="stylesheet" type="text/css" /> </head> <body> <div id="header"> <h1 id="SiteTitle">My Family Tree</h1> </div> <div class="wrapper" id="nav" role="navigation"> <div class="container"> <ul class="menu" id="dropmenu"> <li class = "CurrentSection"><a href="../../../individuals.html" title="Individuals">Individuals</a></li> <li><a href="../../../index.html" title="Surnames">Surnames</a></li> <li><a href="../../../places.html" title="Places">Places</a></li> <li><a href="../../../sources.html" title="Sources">Sources</a></li> <li><a href="../../../media.html" title="Media">Media</a></li> <li><a href="../../../thumbnails.html" title="Thumbnails">Thumbnails</a></li> </ul> </div> </div> <div class="content" id="IndividualDetail"> <h3>Michaud, Anna Eva<sup><small> <a href="#sref1">1</a></small></sup></h3> <div id="summaryarea"> <table class="infolist"> <tr> <td class="ColumnAttribute">Birth Name</td> <td class="ColumnValue"> Michaud, Anna Eva </td> </tr> <tr> <td class="ColumnAttribute">Gramps&nbsp;ID</td> <td class="ColumnValue">I1324</td> </tr> <tr> <td class="ColumnAttribute">Gender</td> <td class="ColumnValue">female</td> </tr> </table> </div> <div class="subsection" id="events"> <h4>Events</h4> <table class="infolist eventlist"> <thead> <tr> <th class="ColumnEvent">Event</th> <th class="ColumnDate">Date</th> <th class="ColumnPlace">Place</th> <th class="ColumnDescription">Description</th> <th class="ColumnNotes">Notes</th> <th class="ColumnSources">Sources</th> </tr> </thead> <tbody> <tr> <td class="ColumnEvent"> Birth </td> <td class="ColumnDate">1716</td> <td class="ColumnPlace">&nbsp;</td> <td class="ColumnDescription"> Birth of Michaud, Anna Eva </td> <td class="ColumnNotes"> <div> </div> </td> <td class="ColumnSources"> &nbsp; </td> </tr> </tbody> </table> </div> <div class="subsection" id="families"> <h4>Families</h4> <table class="infolist"> <tr class="BeginFamily"> <td class="ColumnType">&nbsp</td> <td class="ColumnAttribute">&nbsp</td> <td class="ColumnValue"><a href="" title="Family of Beaulieu, Johann Adam and Michaud, Anna Eva">Family of Beaulieu, Johann Adam and Michaud, Anna Eva<span class="grampsid"> [F0438]</span></a></td> </tr> <tr class="BeginFamily"> <td class="ColumnType">Married</td> <td class="ColumnAttribute">Husband</td> <td class="ColumnValue"> <a href="../../../ppl/o/d/38KKQCVBBMX1BL3RDO.html">Beaulieu, Johann Adam<span class="grampsid"> [I1323]</span></a> </td> </tr> <tr> <td class="ColumnType">&nbsp;</td> <td class="ColumnAttribute">&nbsp;</td> <td class="ColumnValue"> <table class="infolist eventlist"> <thead> <tr> <th class="ColumnEvent">Event</th> <th class="ColumnDate">Date</th> <th class="ColumnPlace">Place</th> <th class="ColumnDescription">Description</th> <th class="ColumnNotes">Notes</th> <th class="ColumnSources">Sources</th> </tr> </thead> <tbody> <tr> <td class="ColumnEvent"> Marriage </td> <td class="ColumnDate">&nbsp;</td> <td class="ColumnPlace">&nbsp;</td> <td class="ColumnDescription"> Marriage of Beaulieu, Johann Adam and Michaud, Anna Eva </td> <td class="ColumnNotes"> <div> </div> </td> <td class="ColumnSources"> &nbsp; </td> </tr> </tbody> </table> </td> </tr> </table> </div> <div class="subsection" id="pedigree"> <h4>Pedigree</h4> <ol class="pedigreegen"> <li> <ol> <li class="thisperson"> Michaud, Anna Eva <ol class="spouselist"> <li class="spouse"> <a href="../../../ppl/o/d/38KKQCVBBMX1BL3RDO.html">Beaulieu, Johann Adam<span class="grampsid"> [I1323]</span></a> </li> </ol> </li> </ol> </li> </ol> </div> <div class="subsection" id="sourcerefs"> <h4>Source References</h4> <ol> <li> <a href="../../../src/x/a/X5TJQC9JXU4RKT6VAX.html" title="Import from test2.ged" name ="sref1"> Import from test2.ged <span class="grampsid"> [S0003]</span> </a> </li> </ol> </div> </div> <div class="fullclear"></div> <div id="footer"> <p id="createdate"> Generated by <a href="http://gramps-project.org/">Gramps</a> 4.2.2 on 2015-12-25<br />Last change was the 2007-07-26 08:34:25 </p> <p id="copyright"> </p> </div> </body> </html>
belissent/testing-example-reports
gramps42/gramps/example_NAVWEB0/ppl/q/9/O8KKQCOUKXFQRRL59Q.html
HTML
gpl-2.0
5,643
class Comment < ActiveRecord::Base after_create :create_notification belongs_to :user belongs_to :video belongs_to :commentable, polymorphic: true has_many :comments, as: :commentable has_many :notifications validates :content, presence: true before_save :format_media, :check_times def editable_by?(user) user == self.user || user == self.video.user end def check_times if self.new_record? if self.start_time == "" || self.start_time.to_i < 0 self.start_time = "0" elsif self.end_time == "" || self.end_time.to_i < 0 self.end_time = "0" end end end def format_media if self.new_record? if self.media_type == "IMAGE" self.content = "<img src='#{self.content}' class='comment-image'></img>" elsif self.media_type == "VIDEO" youtube_id = self.content.split("=").last self.content = "<iframe src='//www.youtube.com/embed/#{youtube_id}'></iframe>" end end end def find_video_parent return self.commentable if self.commentable_type == "Video" self.commentable.find_video_parent end def self.format_times(seconds) seconds = seconds.to_i min = (seconds / 60).floor.to_s if seconds % 60 == 0 sec = "00" elsif seconds % 60 < 10 sec = "0" + (seconds % 60).to_s else sec = (seconds % 60).to_s end min + ":" + sec end private def create_notification @parent = self.commentable @user = User.find_by(id: @parent.user_id) Notification.create( commentable_id: self.commentable.id, commentable_type: self.commentable_type, user_id: @user.id, comment_id: self.id, read: false ) end end
nyc-rock-doves-2015/tubeGenius
app/models/comment.rb
Ruby
gpl-2.0
1,727
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <script src="js/jquery.min.js"></script> <script type="text/javascript" src="js/js.cookie.js"></script> <title>BenchmarkTest00949</title> </head> <body> <form action="/benchmark/BenchmarkTest00949" method="POST" id="FormBenchmarkTest00949" > <div><p>Here is the image you are looking for: &nbsp</p></div> <div><img src="img/500px-Banner_stand.png" style="width: 20%; height: 20%" class="img-responsive" alt="Responsive image" onload="setCookie('vector','test',1)"></div> <div><p>This page automatically generated the cookie named vector with the value displayed below, if you want to generate a new cookie with a different value or use a specific vector, please use the text box "Value" then press the "Generate cookie" button; once you have the value you can press the "Test it!" to send the cookie.</p></div> <div><label>Parameter: cookie vector<BR> Value:</label> <input type="text" id="vector" name="vector" value="FileName"></input></div> <div><input type="button" value="Generate cookie" onclick="setCookie('vector','',1)" id="cGenerator"/></div> <br/> <div><h5 id="cValue"></h5></div> <div><input type="submit" value="Test it!" /></div> </form> </div> <script> function setCookie(cname, cvalue, exdays) { document.cookie = cname + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;'; var d = new Date(); d.setTime(d.getTime() + (exdays*24*60*60*1000)); var expires = "expires="+d.toUTCString(); if(cvalue==''){ Cookies.set(cname, document.getElementById("vector").value, { version: 1 }); }else{ Cookies.set(cname, "FileName", { version: 1 }); } document.getElementById("cValue").innerText = document.cookie; } </script> </body> </html>
ganncamp/Benchmark
src/main/webapp/BenchmarkTest00949.html
HTML
gpl-2.0
1,917
<?php namespace SMW\Test; use SMW\Serializers\QueryResultSerializer; use SMWQueryProcessor; use SMWQueryResult; use SMWDataItem as DataItem; /** * @covers \SMW\Serializers\QueryResultSerializer * * * @group SMW * @group SMWExtension * * @licence GNU GPL v2+ * @since 1.9 * * @author mwjames */ class QueryResultSerializerTest extends SemanticMediaWikiTestCase { /** * Returns the name of the class to be tested * * @return string */ public function getClass() { return '\SMW\Serializers\QueryResultSerializer'; } /** * Helper method that returns a QueryResultSerializer object * * @since 1.9 */ private function newSerializerInstance() { return new QueryResultSerializer(); } /** * @since 1.9 */ public function testConstructor() { $this->assertInstanceOf( $this->getClass(), $this->newSerializerInstance() ); } /** * @since 1.9 */ public function testSerializeOutOfBoundsException() { $this->setExpectedException( 'OutOfBoundsException' ); $instance = $this->newSerializerInstance(); $instance->serialize( 'Foo' ); } /** * @dataProvider numberDataProvider * * @since 1.9 */ public function testQueryResultSerializerOnMock( $setup, $expected ) { $results = $this->newSerializerInstance()->serialize( $setup['queryResult'] ); $this->assertInternalType( 'array' , $results ); $this->assertEquals( $expected['printrequests'], $results['printrequests'] ); } /** * @since 1.9 */ public function testQueryResultSerializerOnMockOnDIWikiPageNonTitle() { $dataItem = $this->newMockBuilder()->newObject( 'DataItem', array( 'getDIType' => DataItem::TYPE_WIKIPAGE, 'getTitle' => null ) ); $queryResult = $this->newMockBuilder()->newObject( 'QueryResult', array( 'getPrintRequests' => array(), 'getResults' => array( $dataItem ), ) ); $results = $this->newSerializerInstance()->serialize( $queryResult ); $this->assertInternalType( 'array' , $results ); $this->assertEmpty( $results['printrequests'] ); $this->assertEmpty( $results['results'] ); } /** * @return array */ public function numberDataProvider() { $provider = array(); $setup = array( array( 'printRequest' => 'Foo-1', 'typeId' => '_num', 'number' => 10, 'dataValue' => 'Quuey' ), array( 'printRequest' => 'Foo-2', 'typeId' => '_num', 'number' => 20, 'dataValue' => 'Vey' ), ); $provider[] = array( array( 'queryResult' => $this->buildMockQueryResult( $setup ) ), array( 'printrequests' => array( array( 'label' => 'Foo-1', 'typeid' => '_num', 'mode' => 2, 'format' => false ), array( 'label' => 'Foo-2', 'typeid' => '_num', 'mode' => 2, 'format' => false ) ), ) ); return $provider; } /** * @return QueryResult */ private function buildMockQueryResult( $setup ) { $printRequests = array(); $resultArray = array(); $getResults = array(); foreach ( $setup as $value ) { $printRequest = $this->newMockBuilder()->newObject( 'PrintRequest', array( 'getText' => $value['printRequest'], 'getLabel' => $value['printRequest'], 'getTypeID' => $value['typeId'], 'getOutputFormat' => false ) ); $printRequests[] = $printRequest; $getResults[] = \SMW\DIWikipage::newFromTitle( $this->newTitle( NS_MAIN, $value['printRequest'] ) ); $dataItem = $this->newMockBuilder()->newObject( 'DataItem', array( 'getDIType' => DataItem::TYPE_NUMBER, 'getNumber' => $value['number'] ) ); $dataValue = $this->newMockBuilder()->newObject( 'DataValue', array( 'DataValueType' => 'SMWNumberValue', 'getTypeID' => '_num', 'getShortWikiText' => $value['dataValue'], 'getDataItem' => $dataItem ) ); $resultArray[] = $this->newMockBuilder()->newObject( 'ResultArray', array( 'getText' => $value['printRequest'], 'getPrintRequest' => $printRequest, 'getNextDataValue' => $dataValue, 'getNextDataItem' => $dataItem, 'getContent' => $dataItem ) ); } $queryResult = $this->newMockBuilder()->newObject( 'QueryResult', array( 'getPrintRequests' => $printRequests, 'getNext' => $resultArray, 'getResults' => $getResults, 'getStore' => $this->newMockBuilder()->newObject( 'Store' ), 'getLink' => new \SMWInfolink( true, 'Lala' , 'Lula' ), 'hasFurtherResults' => true ) ); return $queryResult; } }
Tornaldo/WebIntelligence
extensions/SemanticMediaWiki/tests/phpunit/includes/serializer/QueryResultSerializerTest.php
PHP
gpl-2.0
4,430
## 5 - More services! JXaaS makes it really easy to take a Juju charm, and create an XaaS. You just have [write a manifest](../manifest.md). Let's look at some other services that ship with JXaaS. We'll switch back to running locally, with LXC. Let's start with a clean Juju install (note that this will wipe your Juju): ``` juju destroy-environment local juju init juju switch local juju bootstrap juju status ``` Let's install JXaaS using the ready-built charm: ``` juju deploy cs:~justin-fathomdb/trusty/jxaas jxaas ``` Configure JXaaS with the Juju credentials: ``` API_SECRET=`grep admin-secret ~/.juju/environments/local.jenv | cut -f 2 -d ':' | tr -d ' '` echo "API_SECRET=${API_SECRET}" juju set jxaas api-password=${API_SECRET} ``` And open JXaaS to the world: ``` juju expose jxaas ``` Let's try it out (this is a little more complicated than it was when we were running JXaaS on the host machine): ``` PUBLIC_ADDRESS=`juju status jxaas | grep public-address | cut -f 2 -d ':' | tr -d ' '` echo "PUBLIC_ADDRESS is ${PUBLIC_ADDRESS}" export JXAAS_URL=http://${PUBLIC_ADDRESS}:8080/xaas echo "export JXAAS_URL=http://${PUBLIC_ADDRESS}:8080/xaas" jxaas list-instances mysql ``` ### Postgres ``` which psql || sudo apt-get install --yes postgresql-client jxaas create-instance pg pg5 jxaas list-instances pg # Wait for instance to be ready jxaas wait pg p5 jxaas list-instances pg jxaas connect-instance pg pg5 ``` ### MongoDB ``` # Make sure the mongodb client is installed which mongo || sudo apt-get install --yes mongodb-clients jxaas create-instance mongodb mongodb5 jxaas list-instances mongodb # Wait for instance to be ready jxaas wait mongodb mongodb5 jxaas list-instances mongodb # Connect to the instance jxaas connect-instance mongodb mongodb5 ``` ### Multi-tenant MySQL Multi-tenant mysql creates instances as part of a shared MySQL instance. It allocates each instance its own database, rather than a whole database server. You will notice that this is much faster; it doesn't have to launch a new instance or install much additional software. For the second instance, it doesn't have to install _any_ additional software! ``` jxaas create-instance multimysql mm5 jxaas list-instances multimysql # Wait for instance to be ready jxaas wait multimysql mm5 jxaas list-instances multimysql jxaas list-properties multimysql mm5 db jxaas connect multimysql mm5 ``` # Summary JXaaS makes it easy to take a charm and make it an XaaS. We saw a number of services that ship with JXaaS. Next: [metrics & logs](6.md)
jxaas/jxaas
docs/tutorial/5.md
Markdown
gpl-2.0
2,570
// Copyright (C) 1994, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2007 // Free Software Foundation // // 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 2, 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 COPYING. If not, write to // the Free Software Foundation, 51 Franklin Street, Fifth Floor, // Boston, MA 02110-1301, USA. // As a special exception, you may use this file as part of a free software // library without restriction. Specifically, if other files instantiate // templates or use macros or inline enums from this file, or you compile // this file and link it with other files to produce an executable, this // file does not by itself cause the resulting executable to be covered by // the GNU General Public License. This exception does not however // invalidate any other reasons why the executable file might be covered by // the GNU General Public License. #include "tinfo.h" namespace __cxxabiv1 { __pointer_type_info:: ~__pointer_type_info () {} bool __pointer_type_info:: __is_pointer_p () const { return true; } bool __pointer_type_info:: __pointer_catch (const __pbase_type_info *thrown_type, void **thr_obj, unsigned outer) const { if (outer < 2 && *__pointee == typeid (void)) { // conversion to void return !thrown_type->__pointee->__is_function_p (); } return __pbase_type_info::__pointer_catch (thrown_type, thr_obj, outer); } }
epicsdeb/rtems-gcc-newlib
libstdc++-v3/libsupc++/pointer_type_info.cc
C++
gpl-2.0
1,929
package de.vahrson.pt; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Unit test for simple App. */ public class AppTest extends TestCase { /** * Create the test case * * @param testName name of the test case */ public AppTest( String testName ) { super( testName ); } /** * @return the suite of tests being tested */ public static Test suite() { return new TestSuite( AppTest.class ); } /** * Rigourous Test :-) */ public void testApp() { assertTrue( true ); } }
jrtex/primeTime
pt/src/test/java/de/vahrson/pt/AppTest.java
Java
gpl-2.0
641
demo-web ========
BrodyCai/demo-web
README.md
Markdown
gpl-2.0
18
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_AUTOMATION_AUTOMATION_UTIL_H_ #define CHROME_BROWSER_AUTOMATION_AUTOMATION_UTIL_H_ #pragma once #include <string> #include "base/basictypes.h" class AutomationProvider; class Browser; class DictionaryValue; class GURL; class TabContents; namespace IPC { class Message; } namespace automation_util { Browser* GetBrowserAt(int index); TabContents* GetTabContentsAt(int browser_index, int tab_index); void GetCookies(const GURL& url, TabContents* contents, int* value_size, std::string* value); void SetCookie(const GURL& url, const std::string& value, TabContents* contents, int* response_value); void DeleteCookie(const GURL& url, const std::string& cookie_name, TabContents* contents, bool* success); void GetCookiesJSON(AutomationProvider* provider, DictionaryValue* args, IPC::Message* reply_message); void DeleteCookieJSON(AutomationProvider* provider, DictionaryValue* args, IPC::Message* reply_message); void SetCookieJSON(AutomationProvider* provider, DictionaryValue* args, IPC::Message* reply_message); } #endif
qtekfun/htcDesire820Kernel
external/chromium/chrome/browser/automation/automation_util.h
C
gpl-2.0
1,502
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef SANDBOX_LINUX_SECCOMP_BPF_VERIFIER_H__ #define SANDBOX_LINUX_SECCOMP_BPF_VERIFIER_H__ #include <linux/filter.h> #include <utility> #include <vector> namespace sandbox { class SandboxBPFPolicy; class Verifier { public: static bool VerifyBPF(SandboxBPF* sandbox, const std::vector<struct sock_filter>& program, const SandboxBPFPolicy& policy, const char** err); static uint32_t EvaluateBPF(const std::vector<struct sock_filter>& program, const struct arch_seccomp_data& data, const char** err); private: DISALLOW_IMPLICIT_CONSTRUCTORS(Verifier); }; } #endif
qtekfun/htcDesire820Kernel
external/chromium_org/sandbox/linux/seccomp-bpf/verifier.h
C
gpl-2.0
932
/**************************************************************** * Copyright (C) 2005 LAMS Foundation (http://lamsfoundation.org) * ============================================================= * License Information: http://lamsfoundation.org/licensing/lams/2.0/ * * 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. * * 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 * * http://www.gnu.org/licenses/gpl.txt * **************************************************************** */ package org.lamsfoundation.lams.tool.zoom.web.controller; import javax.servlet.http.HttpServletRequest; import org.apache.log4j.Logger; import org.lamsfoundation.lams.notebook.model.NotebookEntry; import org.lamsfoundation.lams.tool.zoom.dto.ContentDTO; import org.lamsfoundation.lams.tool.zoom.dto.NotebookEntryDTO; import org.lamsfoundation.lams.tool.zoom.dto.ZoomUserDTO; import org.lamsfoundation.lams.tool.zoom.model.Zoom; import org.lamsfoundation.lams.tool.zoom.model.ZoomUser; import org.lamsfoundation.lams.tool.zoom.service.IZoomService; import org.lamsfoundation.lams.tool.zoom.util.ZoomConstants; import org.lamsfoundation.lams.tool.zoom.util.ZoomUtil; import org.lamsfoundation.lams.util.MessageService; import org.lamsfoundation.lams.util.WebUtil; import org.lamsfoundation.lams.web.util.AttributeNames; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; import org.springframework.util.MultiValueMap; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/monitoring") public class MonitoringController { private static final Logger logger = Logger.getLogger(MonitoringController.class); @Autowired private IZoomService zoomService; @Autowired @Qualifier("zoomMessageService") private MessageService messageService; @RequestMapping("/start") public String start(HttpServletRequest request) { Long toolContentID = new Long(WebUtil.readLongParam(request, AttributeNames.PARAM_TOOL_CONTENT_ID)); String contentFolderID = WebUtil.readStrParam(request, AttributeNames.PARAM_CONTENT_FOLDER_ID); Zoom zoom = zoomService.getZoomByContentId(toolContentID); if (zoom == null) { logger.error("Unable to find tool content with id :" + toolContentID); } ContentDTO contentDTO = new ContentDTO(zoom); Long currentTab = WebUtil.readLongParam(request, AttributeNames.PARAM_CURRENT_TAB, true); contentDTO.setCurrentTab(currentTab); contentDTO.setGroupedActivity(zoomService.isGroupedActivity(toolContentID)); request.setAttribute(ZoomConstants.ATTR_CONTENT_DTO, contentDTO); request.setAttribute(ZoomConstants.ATTR_CONTENT_FOLDER_ID, contentFolderID); return "pages/monitoring/monitoring"; } @RequestMapping("/openNotebook") public String openNotebook(HttpServletRequest request) { Long uid = new Long(WebUtil.readLongParam(request, ZoomConstants.PARAM_USER_UID)); ZoomUser user = zoomService.getUserByUID(uid); NotebookEntry entry = zoomService.getNotebookEntry(user.getNotebookEntryUID()); ZoomUserDTO userDTO = new ZoomUserDTO(user); userDTO.setNotebookEntryDTO(new NotebookEntryDTO(entry)); request.setAttribute(ZoomConstants.ATTR_USER_DTO, userDTO); return "pages/monitoring/notebook"; } @RequestMapping("/startMeeting") public String startMeeting(HttpServletRequest request) throws Exception { Long toolContentID = WebUtil.readLongParam(request, AttributeNames.PARAM_TOOL_CONTENT_ID, false); Zoom zoom = zoomService.getZoomByContentId(toolContentID); ContentDTO contentDTO = new ContentDTO(); contentDTO.setTitle(zoom.getTitle()); contentDTO.setInstructions(zoom.getInstructions()); request.setAttribute(ZoomConstants.ATTR_CONTENT_DTO, contentDTO); MultiValueMap<String, String> errorMap = ZoomUtil.startMeeting(zoomService, messageService, zoom, request); if (!errorMap.isEmpty()) { request.setAttribute("errorMap", errorMap); } return "pages/learning/learning"; } }
lamsfoundation/lams
lams_tool_zoom/src/java/org/lamsfoundation/lams/tool/zoom/web/controller/MonitoringController.java
Java
gpl-2.0
4,587
<?php namespace Sumo; class ModelCatalogCategory extends Model { public function addCategory($data) { $order = $this->query( "SELECT MAX(sort_order) AS max_sort_order FROM PREFIX_category AS c LEFT JOIN PREFIX_category_to_store AS cts ON cts.category_id = c.category_id WHERE parent_id = :parent_id AND store_id = :store_id", array( 'parent_id' => $data['parent_id'], 'store_id' => $data['store_id'] ) )->fetch(); if (empty($order['max_sort_order'])) { $order['max_sort_order'] = 0; } $this->query("INSERT INTO PREFIX_category SET sort_order = :order, date_added = :date", array('order' => $order['max_sort_order'] + 1, 'date' => date('Y-m-d H:i:s'))); $data['sort_order'] = $order['max_sort_order'] + 1; $category_id = $this->lastInsertId(); return $this->editCategory($category_id, $data); } public function editCategory($category_id, $data) { $this->query( "UPDATE PREFIX_category SET parent_id = :parent_id, image = :image, date_modified = :date WHERE category_id = :id", array( 'parent_id' => $data['parent_id'], 'image' => $data['image'], 'date' => date('Y-m-d H:i:s'), 'id' => $category_id ) ); $this->query("DELETE FROM PREFIX_category_to_store WHERE category_id = :id", array('id' => $category_id)); $this->query("DELETE FROM PREFIX_category_description WHERE category_id = :id", array('id' => $category_id)); $this->query("DELETE FROM PREFIX_url_alias WHERE query = :query", array('query' => 'category_id=' . $data['category_store'])); $this->query("INSERT INTO PREFIX_category_to_store SET category_id = :id, store_id = :store", array('id' => $category_id, 'store' => $data['category_store'])); foreach ($data['category_description'] as $lid => $list) { $this->query( "INSERT INTO PREFIX_category_description SET category_id = :id, language_id = :lid, name = :name, title = :title, meta_keyword = :keyword, meta_description = :meta, description = :description", array( 'id' => $category_id, 'lid' => $lid, 'name' => $list['name'], 'title' => $list['title'], 'keyword' => $list['meta_keyword'], 'meta' => $list['meta_description'], 'description' => $list['description'] ) ); Formatter::generateSeoUrl($list['name'], 'category_id', $category_id, $lid, $data['category_store']); } $paths = $this->fetchAll( "SELECT * FROM PREFIX_category_path WHERE path_id = :id ORDER BY level ASC", array('id' => $category_id) ); if (count($paths)) { foreach ($paths as $category_path) { $this->query( "DELETE FROM PREFIX_category_path WHERE category_id = :cid AND level < :level", array( 'cid' => $category_path['category_id'], 'level' => $category_path['level'], ) ); $path = array(); $nodes = $this->fetchAll( "SELECT * FROM PREFIX_category_path WHERE category_id = :id ORDER BY level ASC", array('id' => $data['parent_id']) ); foreach ($nodes as $result) { $path[] = $result['path_id']; } $nodes = $this->fetchAll( "SELECT * FROM PREFIX_category_path WHERE category_id = :id ORDER BY level ASC", array('id' => $category_path['category_id']) ); foreach ($nodes as $result) { $path[] = $result['path_id']; } $level = 0; foreach ($path as $path_id) { $this->query( "REPLACE INTO PREFIX_category_path SET category_id = :id, path_id = :path, level = :level", array( 'id' => $category_path['category_id'], 'path' => $path_id, 'level' => $level ) ); $level++; } } } else { $this->query("DELETE FROM PREFIX_category_path WHERE category_id = :id", array('id' => $category_id)); $level = 0; $query = $this->fetchAll("SELECT * FROM PREFIX_category_path WHERE category_id = :id ORDER BY level ASC", array('id' => $data['parent_id'])); foreach ($query as $result) { $this->query( "INSERT INTO PREFIX_category_path SET category_id = :id, path_id = :path, level = :level", array( 'id' => $category_id, 'path' => $result['path_id'], 'level' => $level ) ); $level++; } $this->query( "REPLACE INTO PREFIX_category_path SET category_id = :id, path_id = :path, level = :level", array( 'id' => $category_id, 'path' => $category_id, 'level' => $level ) ); } Cache::removeAll(); } public function deleteCategory($category_id) { // Reset sort_order $category_info = $this->getCategory($category_id); $this->query( "UPDATE PREFIX_category SET sort_order = sort_order - 1 WHERE sort_order > :order AND parent_id = :parent_id AND category_id IN ( SELECT category_id FROM PREFIX_category_to_store WHERE store_id = :store_id )", array( 'order' => $category_info['sort_order'], 'parent_id' => (int)$category_info['parent_id'], 'store_id' => !empty($category_info['store_id']) ? (int)$category_info['store_id'] : 0 ) ); $this->query("DELETE FROM PREFIX_category_path WHERE category_id = :id", array('id' => $category_id)); $query = $this->fetchAll("SELECT * FROM PREFIX_category_path WHERE path_id = :id", array('id' => $category_id)); foreach ($query as $result) { $this->deleteCategory($result['category_id']); } $this->query("DELETE FROM PREFIX_category WHERE category_id = :id", array('id' => $category_id)); $this->query("DELETE FROM PREFIX_category_description WHERE category_id = :id", array('id' => $category_id)); $this->query("DELETE FROM PREFIX_category_to_store WHERE category_id = :id", array('id' => $category_id)); $this->query("DELETE FROM PREFIX_product_to_category WHERE category_id = :id", array('id' => $category_id)); $this->query("DELETE FROM PREFIX_url_alias WHERE query = :query", array('query' => 'category_id='. (int)$category_id)); // Delete lonely products $this->load->model('catalog/product'); $lonelyProducts = $this->query("SELECT product_id FROM PREFIX_product WHERE product_id NOT IN (SELECT product_id FROM PREFIX_product_to_category)")->fetchAll(); foreach ($lonelyProducts as $product) { $this->model_catalog_product->deleteProduct($product['product_id']); } Cache::removeAll(); } public function moveCategoryUp($category_id) { $category_info = $this->getCategory($category_id); /* $this->query("UPDATE PREFIX_category SET sort_order = sort_order+1 WHERE parent_id = :parent AND sort_order = :order", array('order' => $category_info['sort_order'] + 1, 'parent' => $category_info['parent_id'])); $this->query("UPDATE PREFIX_category SET sort_order = sort_order-1, date_modified = :date WHERE category_id = :id", array('id' => $category_id, 'date' => date('Y-m-d H:i:s'))); */ if ($category_info['sort_order'] <= 1) { return; } $this->query( "UPDATE PREFIX_category SET sort_order = :sort_order, date_modified = :date WHERE sort_order = :old_order AND parent_id = :parent_id AND category_id IN ( SELECT category_id FROM PREFIX_category_to_store WHERE store_id = :store_id )", array( 'sort_order' => $category_info['sort_order'], 'old_order' => $category_info['sort_order'] -1, 'parent_id' => (int)$category_info['parent_id'], 'store_id' => !empty($category_info['store_id']) ? (int)$category_info['store_id'] : 0, 'date' => date('Y-m-d H:i:s') ) ); $this->query( "UPDATE PREFIX_category SET sort_order = :new_order WHERE category_id = :category", array( 'new_order' => $category_info['sort_order'] -1, 'category' => $category_id ) ); Cache::removeAll(); } public function moveCategoryDown($category_id) { $category_info = $this->getCategory($category_id); $check = $this->query( "SELECT MAX(sort_order) AS max_sort_order FROM PREFIX_category AS c, PREFIX_category_to_store AS cts WHERE c.category_id = cts.category_id AND cts.store_id = :store AND c.parent_id = :parent", array( 'store' => !empty($category_info['store_id']) ? (int)$category_info['store_id'] : 0, 'parent' => $category_info['parent_id'] ) )->fetch(); if ($category_info['sort_order'] == $check['max_sort_order']) { return; } $this->query( "UPDATE PREFIX_category SET sort_order = :sort_order, date_modified = :date WHERE sort_order = :old_order AND parent_id = :parent_id AND category_id IN ( SELECT category_id FROM PREFIX_category_to_store WHERE store_id = :store_id )", array( 'sort_order' => $category_info['sort_order'], 'old_order' => $category_info['sort_order'] +1, 'parent_id' => (int)$category_info['parent_id'], 'store_id' => !empty($category_info['store_id']) ? (int)$category_info['store_id'] : 0, 'date' => date('Y-m-d H:i:s') ) ); $this->query( "UPDATE PREFIX_category SET sort_order = :new_order WHERE category_id = :category", array( 'new_order' => $category_info['sort_order'] +1, 'category' => $category_id ) ); Cache::removeAll(); } public function updateStatus($category_id, $status = 1) { if ($status) { $check = $this->query("SELECT parent_id FROM PREFIX_category WHERE category_id = :id", array('id' => $category_id))->fetch(); if ($check['parent_id']) { $check = $this->query("SELECT status FROM PREFIX_category WHERE category_id = :id", array('id' => $check['parent_id']))->fetch(); if (!$check['status']) { return false; } } } $this->query( "UPDATE PREFIX_category SET status = :status, date_modified = :date WHERE category_id = :id", array( 'status' => $status, 'date' => date('Y-m-d H:i:s'), 'id' => $category_id ) ); if (!$status) { foreach ($this->fetchAll("SELECT category_id FROM PREFIX_category WHERE parent_id = :id", array('id' => $category_id)) as $cat) { $this->updateStatus($cat['category_id'], 0); } } Cache::removeAll(); return true; } public function getCategory($category_id) { $query = $this->query( "SELECT DISTINCT *, ( SELECT GROUP_CONCAT(cd1.name ORDER BY level SEPARATOR ' &gt; ') FROM PREFIX_category_path cp LEFT JOIN PREFIX_category_description cd1 ON (cp.path_id = cd1.category_id AND cp.category_id != cp.path_id) WHERE cp.category_id = c.category_id AND cd1.language_id = '" . (int)$this->config->get('language_id') . "' GROUP BY cp.category_id ) AS path FROM PREFIX_category AS c LEFT JOIN PREFIX_category_description AS cd2 ON (c.category_id = cd2.category_id) LEFT JOIN PREFIX_category_to_store AS cts ON (c.category_id = cts.store_id) WHERE c.category_id = '" . (int)$category_id . "' AND cd2.language_id = '" . (int)$this->config->get('language_id') . "'"); return $query->fetch(); } public function getCategories($data = array(), $total = true) { $cache = Cache::find('category'); if (is_array($cache) && count($cache)) { return $cache; } // Step 1: Select base/head categories from prefix_category $sql = " SELECT c.category_id, cts.store_id, cd.name, c.sort_order, parent_id, c.status, cd.meta_description, cd.description, cd.meta_keyword, s.name AS store_name FROM PREFIX_category AS c LEFT JOIN PREFIX_category_to_store AS cts ON cts.category_id = c.category_id LEFT JOIN PREFIX_category_description AS cd ON cd.category_id = c.category_id LEFT JOIN PREFIX_stores AS s ON s.store_id = cts.store_id WHERE parent_id = 0 AND cd.language_id = '" . (int) $this->config->get('language_id') . "' ORDER BY parent_id, sort_order"; $query = $this->fetchAll($sql); $cats = $data = array(); foreach ($query as $base) { // Step 2: Select parent categories $cats[$base['store_id']][$base['category_id']][0] = $base; $query2 = $this->fetchAll(str_replace('parent_id = 0', 'parent_id = ' . $base['category_id'], $sql)); foreach ($query2 as $list) { $cats[$base['store_id']][$base['category_id']][$list['category_id']][$list['category_id']] = $list; if ($total) { $query3 = $this->fetchAll(str_replace('parent_id = 0', 'parent_id = ' . $list['category_id'], $sql)); foreach ($query3 as $list2) { $cats[$base['store_id']][$base['category_id']][$list['category_id']][$list2['category_id']] = $list2; } } } //ksort($cats[$base['store_id']][$base['category_id']]); } //ksort($cats); foreach ($cats as $store_id => $store_cats) { $tmp = array(); foreach ($store_cats as $cat_id => $categories) { foreach ($categories as $path_id => $levels) { $tmp[] = $levels; } } $data[$store_id] = $tmp; } Cache::set('category', $data); return $data; } public function getCategoriesAsList($parentID = 0, $level = 0) { if ($parentID == 0) { $cache = Cache::find('category_as_list'); if (is_array($cache) && count($cache)) { return $cache; } } $sql = " SELECT c.category_id, cts.store_id, cd.name, c.sort_order, parent_id, c.status, cd.meta_description, cd.description, cd.meta_keyword FROM PREFIX_category AS c LEFT JOIN PREFIX_category_to_store AS cts ON cts.category_id = c.category_id LEFT JOIN PREFIX_category_description AS cd ON cd.category_id = c.category_id WHERE parent_id = " . (int)$parentID . " AND cd.language_id = '" . (int) $this->config->get('language_id') . "' ORDER BY parent_id, sort_order"; $query = $this->query($sql); $return = array(); foreach ($query->fetchAll() as $row) { $row['level'] = $level; $return[] = $row; if (($subCategories = $this->getCategoriesAsList($row['category_id'], $level + 1)) !== false) { $return = array_merge($return, $subCategories); } } if ($parentID == 0) { Cache::set('category_as_list', $return); return $return; } if (empty($return)) { return false; } return $return; } public function getCategoryDescriptions($category_id) { $data = $this->fetchAll( "SELECT cd.*, ( SELECT keyword FROM PREFIX_url_alias AS au WHERE au.query = :query AND au.language_id = cd.language_id ) AS keyword FROM PREFIX_category_description AS cd WHERE category_id = :id", array( 'query' => 'category_id=' . $category_id, 'id' => $category_id ) ); $return = array(); foreach ($data as $list) { $return[$list['language_id']] = $list; } return $return; } public function getCategoryStores($category_id) { $query = $this->query("SELECT store_id FROM PREFIX_category_to_store WHERE category_id = :id", array('id' => $category_id))->fetch(); return $query['store_id']; } public function getTotalCategories() { $query = $this->query("SELECT COUNT(*) AS total FROM PREFIX_category")->fetch(); return $query['total']; } }
wardvanderput/SumoStore
upload/admin/model/catalog/category.php
PHP
gpl-2.0
19,857
class CreateControllers < ActiveRecord::Migration def change create_table :controllers do |t| t.string :Pages t.timestamps end end end
funtimecomics/funtime_app
db/migrate/20130630041556_create_controllers.rb
Ruby
gpl-2.0
160
using ClientApplication.Controls; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace ClientApplication.Views { /// <summary> /// Interaction logic for UsersListView.xaml /// </summary> public partial class UsersListView : Window { public UsersListView() { InitializeComponent(); } private void OnKeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Escape) btnCancel.RaiseEvent(new RoutedEventArgs(ActionButton.ClickEvent, sender)); } } }
Maxikq/Library-Manager
Client/Views/UsersListView.xaml.cs
C#
gpl-2.0
869
/*! \file main.cpp \brief */ #include <stdio.h> #include <unistd.h> #include <getopt.h> #include <string> #include "main_wip_test.h" #include "helper.h" int verbose; globalArgs_t globalArgs; static const char *optString = "vh?"; static const struct option longOpts[] = { { "verbose", no_argument, NULL, 'v' }, { "help", no_argument, NULL, 'h' }, { "version", no_argument, NULL, 0 }, { "visualize", no_argument, NULL, 0 }, { "giveall", no_argument, NULL, 0 }, { "giveallequal", no_argument, NULL, 0 }, { "facets", required_argument, NULL, 0}, { "minima", required_argument, NULL, 0}, { "skipcase", required_argument, NULL, 0}, { "eps", required_argument, NULL, 0}, { "outputtofile", no_argument, NULL, 0}, { "errortofile", no_argument, NULL, 0}, { "treshold", required_argument, NULL, 0}, { "webpage", required_argument, NULL, 0}, { "elimfacets", required_argument, NULL, 0}, { "issymmetric", no_argument, NULL, 0}, { NULL, no_argument, NULL, 0 } }; void print_help(void) { printf( "Usage: densest_lattice_packings [options] [files]\n" "TODO describe file format \n" "Options are: \n" "\t [-v, --verbose] \t Produce verbose output. Can be used up to three times. \n" "\t [-h, --help] \t Output help and exit. \n" "\t [-v, --version] \t Output version and exit \n" "\t [--visualize] \t Visualizes polytopes. \n" "\t [--giveall] \t Outputs all found admissible lattices.\n" "\t [--giveallequal] \t Outputs all found admissible lattices with packing density greater or equal" " than the current greatest packing density.\n" "\t [--facets] CASE [FACETS..] \t Execute a single case. CASE must be 1,2,3 or 4 followed by 6 or 7 facet indices.\n" "\t [--minima] MINIMA \t Can only be used in combination with --facets.\n" "\t [--skipcase] CASE \t This will skip all computations for the case CASE.\n" "\t [--eps] EPS \t Specifies the smallest, positive non-zero number.\n" "\t [--outputtofile \t Additional writes all found admissible lattices to a file. \n" "\t [--errortofile \tAdditional writes all aborted cases the a file. \n " "\t [--treshold] T \tDefines a treshold for the packing density. Lattices with packing density > T will be ignored.\n" "\t [--elimfacets] (1,2) \t Try to eliminate redundant facets (for unexact data). Flag 1 tries once, 2 twice. \n" "\t [--webpage] ARG \t Write html output to ARG. \n" "\t [--issymmetric] \t If the input body is already symmetric, some calculations can be skipped. This saves some time. \n" "\t [--giveall] \t Output all admissible lattices. \n" "\t [--giveallequal] Output all admissible lattices with at least equal determinant as the current optimal lattice.\n"); } void initializePARISystem(void) { /* Initialisation of the pari system * and the three variables. */ // pari_init(1000000000,DEFAULTPREC); // TODO Use prec to adjust size // vars = cgetg(4, t_VECSMALL); // vars[1] = fetch_user_var("x"); // vars[2] = fetch_user_var("y"); // vars[3] = fetch_user_var("z"); } int main(int argc, char* argv[]) { double eps = 10E-8; int opt = 0; int singleCase = 0; int singleCase4Enum; int facetsSingleCase[7]; int longIndex; globalArgs.verbosity = 0; globalArgs.inputFiles = NULL; globalArgs.numInputFiles = 0; globalArgs.visualize = 0; globalArgs.precision = 0;//MEDDEFAULTPREC; globalArgs.giveAll = 0; globalArgs.giveAllEqual = 0; globalArgs.errorFileOut = 0; globalArgs.fileOutput = 0; globalArgs.errorFileOut = 0; globalArgs.outFile = 0; globalArgs.errorFile = 0; globalArgs.skipCases[0] = globalArgs.skipCases[1] = globalArgs.skipCases[2] = globalArgs.skipCases[3] = 0; globalArgs.densityTreshold = 1.0; globalArgs.numericalEliminateFacets = 0; globalArgs.isSymmetric = 0; initializePARISystem(); opt = getopt_long(argc, argv, optString, longOpts, &longIndex ); while( -1 != opt) { switch(opt) { case 'v': globalArgs.verbosity++; //printf("verbose\n"); break; case 'h': // intentional fall-through case '?': print_help(); return 1; break; case 0: // long options without short options if( strcmp( "version", longOpts[longIndex].name ) == 0 ) { printf("version0.0.0\n"); } else if( strcmp( "visualize", longOpts[longIndex].name ) == 0 ) { globalArgs.visualize = 1; } else if( strcmp( "giveall", longOpts[longIndex].name ) == 0 ) { globalArgs.giveAll = 1; } else if( strcmp( "giveallequal", longOpts[longIndex].name ) == 0 ) { globalArgs.giveAllEqual = 1; } else if( strcmp( "eps", longOpts[longIndex].name ) == 0 ) { eps = atof(optarg); } else if( strcmp( "treshold", longOpts[longIndex].name ) == 0 ) { globalArgs.densityTreshold = atof(optarg); } else if( strcmp( "outputtofile", longOpts[longIndex].name ) == 0 ) { globalArgs.fileOutput = 1; } else if( strcmp( "elimfacets", longOpts[longIndex].name ) == 0 ) { globalArgs.numericalEliminateFacets = atoi(optarg); } else if( strcmp( "webpage", longOpts[longIndex].name ) == 0 ) { globalArgs.webpage = 1; strcpy(globalArgs.webfile, optarg); } else if( strcmp( "issymmetric", longOpts[longIndex].name ) == 0 ) { globalArgs.isSymmetric = 1; } else if( strcmp( "errortofile", longOpts[longIndex].name ) == 0 ) { globalArgs.errorFileOut = 1; //printf(optarg); } else if( strcmp( "skipcase", longOpts[longIndex].name ) == 0 ) { int skipCase = atoi(optarg); if(skipCase > 4 || skipCase < 1) std::cout << "error; invalid argument for option 'skipCase' " << std::endl; else globalArgs.skipCases[skipCase-1] = 1; } else if( strcmp( "facets", longOpts[longIndex].name ) == 0 ) { if(sscanf(optarg, "%d", &singleCase) == EOF) { std::cout << "error; invalid argument for parameter 'case': " << optarg << std::endl; return 0; } if( singleCase <= 2) { if(sscanf(optarg, "%d %d %d %d %d %d %d", &singleCase, &facetsSingleCase[0], &facetsSingleCase[1], &facetsSingleCase[2], &facetsSingleCase[3], &facetsSingleCase[4], &facetsSingleCase[5]) == EOF) { std::cout << "error; invalid argument for parameter 'case': " << optarg << std::endl; return 0; } } else if( singleCase == 3 ) { if(sscanf(optarg, "%d %d %d %d %d %d %d %d", &singleCase, &facetsSingleCase[0], &facetsSingleCase[1], &facetsSingleCase[2], &facetsSingleCase[3], &facetsSingleCase[4], &facetsSingleCase[5], &facetsSingleCase[6]) == EOF) { std::cout << "error; invalid argument for parameter 'case': " << optarg << std::endl; return 0; } } else if( singleCase == 4 ) { if(sscanf(optarg, "%d %d %d %d %d %d %d %d %d", &singleCase, &singleCase4Enum, &facetsSingleCase[0], &facetsSingleCase[1], &facetsSingleCase[2], &facetsSingleCase[3], &facetsSingleCase[4], &facetsSingleCase[5], &facetsSingleCase[6]) == EOF) { std::cout << "error; invalid argument for parameter 'case': " << optarg << std::endl; return 0; } } } else if( strcmp( "minima", longOpts[longIndex].name ) == 0 ) { //minima = gp_read_str(optarg); //output(minima); } break; default: break; } opt = getopt_long(argc, argv, optString, longOpts, &longIndex); } globalArgs.inputFiles = argv + optind; globalArgs.numInputFiles = argc - optind; globalArgs.densityTreshold += eps; std::cout << "finished succesfully" << std::endl; return 1; }
soberg/fruitcase
src/main_wip_test.cpp
C++
gpl-2.0
9,012
/****************************************************************************** GHAAS Command Line Library V1.0 Global Hydrologic Archive and Analysis System Copyright 1994-2010, UNH - CCNY/CUNY cmThreads.c balazs.fekete@unh.edu *******************************************************************************/ #include <stdlib.h> #include <cm.h> CMthreadJob_p CMthreadJobCreate (CMthreadTeam_p team, void *commonData, size_t taskNum, CMthreadUserAllocFunc allocFunc, CMthreadUserExecFunc execFunc) { size_t taskId; int threadId; CMthreadJob_p job; if ((job = (CMthreadJob_p) malloc (sizeof (CMthreadJob_t))) == (CMthreadJob_p) NULL) { CMmsgPrint (CMmsgSysError, "Memory allocation error in %s:%d\n",__FILE__,__LINE__); return ((CMthreadJob_p) NULL); } if ((job->Tasks = (CMthreadTask_p) calloc (taskNum,sizeof (CMthreadTask_t))) == (CMthreadTask_p) NULL) { CMmsgPrint (CMmsgSysError, "Memory allocation error in %s:%d\n",__FILE__,__LINE__); free (job); return ((CMthreadJob_p) NULL); } job->TaskNum = taskNum; for (taskId = 0;taskId < job->TaskNum; ++taskId) { job->Tasks [taskId].Id = taskId; job->Tasks [taskId].Completed = false; job->Tasks [taskId].Locked = false; job->Tasks [taskId].Depend = 0; } job->LastId = job->TaskNum; job->UserFunc = execFunc; job->CommonData = (void *) commonData; if (allocFunc != (CMthreadUserAllocFunc) NULL) { job->ThreadNum = (team != (CMthreadTeam_p) NULL) && (team->ThreadNum > 1) ? team->ThreadNum : 1; if ((job->ThreadData = (void **) calloc (job->ThreadNum, sizeof (void *))) == (void **) NULL) { CMmsgPrint (CMmsgSysError, "Memory allocation error in %s:%d\n",__FILE__,__LINE__); free (job); return ((CMthreadJob_p) NULL); } for (threadId = 0;threadId < job->ThreadNum;++threadId) { if ((job->ThreadData [threadId] = allocFunc (commonData)) == (void *) NULL) { CMmsgPrint (CMmsgSysError, "Memory allocation error in %s:%d\n",__FILE__,__LINE__); for (--threadId;threadId >= 0; --threadId) free (job->ThreadData [threadId]); free (job->ThreadData); free (job); return ((CMthreadJob_p) NULL); } } } else job->ThreadData = (void **) NULL; return (job); } CMreturn CMthreadJobTaskDependence (CMthreadJob_p job, size_t taskId, size_t depend) { if (taskId > job->TaskNum) { CMmsgPrint (CMmsgAppError,"Invalid task in %s%d\n",__FILE__,__LINE__); return (CMfailed); } if (depend >= job->TaskNum) depend = job->TaskNum - 1; job->Tasks [taskId].Depend = job->Tasks [taskId].Depend > depend ? job->Tasks [taskId].Depend : depend; return (CMsucceeded); } void CMthreadJobDestroy (CMthreadJob_p job, CMthreadUserFreeFunc freeFunc) { size_t threadId; if (freeFunc != (CMthreadUserFreeFunc) NULL) { for (threadId = 0;threadId < job->ThreadNum; ++threadId) freeFunc (job->ThreadData [threadId]); } free (job->Tasks); free (job); } static void *_CMthreadWork (void *dataPtr) { CMthreadData_p data = (CMthreadData_p) dataPtr; int taskId; CMthreadTeam_p team = (CMthreadTeam_p) data->TeamPtr; CMthreadJob_p job; clock_t start = clock (); pthread_mutex_lock (&(team->Mutex)); job = (CMthreadJob_p) team->JobPtr; while (job->LastId < job->TaskNum) { for (taskId = job->LastId;taskId < job->TaskNum; ++taskId) { if (job->Tasks [taskId].Completed) { if (taskId == job->LastId) job->LastId = taskId + 1; continue; } if (job->Tasks [taskId].Locked) continue; if ((taskId >= job->Tasks [taskId].Depend) || (job->Tasks [job->Tasks [taskId].Depend].Completed)) { job->Tasks [taskId].Locked = true; if (taskId == (job->LastId - 1)) job->LastId = taskId; pthread_mutex_unlock (&(team->Mutex)); start = clock (); job->UserFunc (job->CommonData, job->ThreadData == (void **) NULL ? (void *) NULL : job->ThreadData [data->Id], taskId); data->UserTime += clock () - start + 1; data->CompletedTasks++; pthread_mutex_lock (&(team->Mutex)); job->Tasks [taskId].Locked = false; job->Tasks [taskId].Completed = true; } } pthread_mutex_unlock (&(team->Mutex)); pthread_mutex_lock (&(team->Mutex)); } data->ThreadTime += clock () - start; pthread_mutex_unlock (&(team->Mutex)); if (data->Id > 0) pthread_exit((void *) NULL); // Only slave threads need to exit. return ((void *) NULL); } CMreturn CMthreadJobExecute (CMthreadTeam_p team, CMthreadJob_p job) { int ret, taskId; size_t threadId; void *status; pthread_attr_t thread_attr; if (team != (CMthreadTeam_p) NULL) { pthread_attr_init (&thread_attr); pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_JOINABLE); team->JobPtr = (void *) job; job->LastId = 0; for (taskId = 0; taskId < job->TaskNum; ++taskId) { job->Tasks [taskId].Completed = false; job->Tasks [job->Tasks [taskId].Depend].Locked = false; // TODO printf ("Task: %4d Depend: %4d\n", (int) taskId, (int) job->Tasks [taskId].Depend); } for (threadId = 1; threadId < team->ThreadNum; ++threadId) { if ((ret = pthread_create (&(team->Threads [threadId].Thread), &thread_attr,_CMthreadWork,(void *) (team->Threads + threadId))) != 0) { CMmsgPrint (CMmsgAppError,"Thread creation returned with error [%d] in %s:%d\n",ret,__FILE__,__LINE__); free (team->Threads); free (team); return (CMfailed); } } status = _CMthreadWork (team->Threads); pthread_attr_destroy(&thread_attr); for (threadId = 1;threadId < team->ThreadNum;++threadId) pthread_join(team->Threads [threadId].Thread, &status); } else for (taskId = 0;taskId < job->TaskNum; ++taskId) job->UserFunc (job->CommonData, job->ThreadData != (void **) NULL ? job->ThreadData [0] : (void *) NULL, taskId); return (CMsucceeded); } CMthreadTeam_p CMthreadTeamCreate (size_t threadNum) { size_t threadId; CMthreadTeam_p team = (CMthreadTeam_p) NULL; if (threadNum < 2) return (team); if ((team = (CMthreadTeam_p) malloc (sizeof (CMthreadTeam_t))) == (CMthreadTeam_p) NULL) { CMmsgPrint (CMmsgSysError,"Memory Allocation error in %s:%d\n",__FILE__,__LINE__); return ((CMthreadTeam_p) NULL); } if ((team->Threads = (CMthreadData_p) calloc (threadNum, sizeof(CMthreadData_t))) == (CMthreadData_p) NULL) { CMmsgPrint (CMmsgSysError,"Memory Allocation error in %s:%d\n",__FILE__,__LINE__); free (team); return ((CMthreadTeam_p) NULL); } team->ThreadNum = threadNum; team->JobPtr = (void *) NULL; team->Time = clock (); for (threadId = 0; threadId < team->ThreadNum; ++threadId) { team->Threads [threadId].Id = threadId; team->Threads [threadId].TeamPtr = (void *) team; team->Threads [threadId].CompletedTasks = 0; team->Threads [threadId].ThreadTime = (clock_t) 0; team->Threads [threadId].UserTime = (clock_t) 0; } pthread_mutex_init (&(team->Mutex), NULL); return (team); } void CMthreadTeamDestroy (CMthreadTeam_p team, bool report) { size_t threadId, completedTasks = 0; if (team != (CMthreadTeam_p) NULL) { team->Time = clock () - team->Time; if (report) { for (threadId = 0;threadId < team->ThreadNum;++threadId) completedTasks += team->Threads [threadId].CompletedTasks; for (threadId = 0;threadId < team->ThreadNum;++threadId) if (team->Threads [threadId].CompletedTasks > 0) CMmsgPrint (CMmsgInfo,"Threads#%d completed %9d tasks (%4.1f %c of the total) User time %4.1f(%4.1f) %c\n", (int) team->Threads [threadId].Id, (int) team->Threads [threadId].CompletedTasks, (float) team->Threads [threadId].CompletedTasks * 100.0 / (float) completedTasks,'%', (float) team->Threads [threadId].UserTime * 100.0 / (float) team->Threads [threadId].ThreadTime, (float) team->Threads [threadId].UserTime * 100.0 / (float) team->Time, '%'); else CMmsgPrint (CMmsgInfo,"Threads#%d completed %9d tasks (%4.1f %c of the total) User time %4.1f(%4.1f) %c\n", (int) team->Threads [threadId].Id, (int) team->Threads [threadId].CompletedTasks, (float) 0.0, '%', (float) 0, (float) 0.0, '%'); } pthread_mutex_destroy (&(team->Mutex)); pthread_exit(NULL); free (team->Threads); free (team); } }
csdms-contrib/wbmsed
Model/CMlib/src/cmThreads.c
C
gpl-2.0
8,334
/* $Id$ */ /* * This file is part of OpenTTD. * OpenTTD 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. * OpenTTD 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 OpenTTD. If not, see <http://www.gnu.org/licenses/>. */ /** @file ai_engine.cpp Implementation of AIEngine. */ #include "ai_engine.hpp" #include "ai_cargo.hpp" #include "../../company_func.h" #include "../../company_base.h" #include "../../strings_func.h" #include "../../rail.h" #include "../../engine_base.h" #include "../../articulated_vehicles.h" #include "table/strings.h" /* static */ bool AIEngine::IsValidEngine(EngineID engine_id) { const Engine *e = ::Engine::GetIfValid(engine_id); return e != NULL && (HasBit(e->company_avail, _current_company) || ::Company::Get(_current_company)->num_engines[engine_id] > 0); } /* static */ bool AIEngine::IsBuildable(EngineID engine_id) { const Engine *e = ::Engine::GetIfValid(engine_id); return e != NULL && HasBit(e->company_avail, _current_company); } /* static */ char *AIEngine::GetName(EngineID engine_id) { if (!IsValidEngine(engine_id)) return NULL; static const int len = 64; char *engine_name = MallocT<char>(len); ::SetDParam(0, engine_id); ::GetString(engine_name, STR_ENGINE_NAME, &engine_name[len - 1]); return engine_name; } /* static */ CargoID AIEngine::GetCargoType(EngineID engine_id) { if (!IsValidEngine(engine_id)) return CT_INVALID; CargoArray cap = ::GetCapacityOfArticulatedParts(engine_id); CargoID most_cargo = CT_INVALID; uint amount = 0; for (CargoID cid = 0; cid < NUM_CARGO; cid++) { if (cap[cid] > amount) { amount = cap[cid]; most_cargo = cid; } } return most_cargo; } /* static */ bool AIEngine::CanRefitCargo(EngineID engine_id, CargoID cargo_id) { if (!IsValidEngine(engine_id)) return false; if (!AICargo::IsValidCargo(cargo_id)) return false; return HasBit(::GetUnionOfArticulatedRefitMasks(engine_id, true), cargo_id); } /* static */ bool AIEngine::CanPullCargo(EngineID engine_id, CargoID cargo_id) { if (!IsValidEngine(engine_id)) return false; if (GetVehicleType(engine_id) != AIVehicle::VT_RAIL) return false; if (!AICargo::IsValidCargo(cargo_id)) return false; return (::RailVehInfo(engine_id)->ai_passenger_only != 1) || AICargo::HasCargoClass(cargo_id, AICargo::CC_PASSENGERS); } /* static */ int32 AIEngine::GetCapacity(EngineID engine_id) { if (!IsValidEngine(engine_id)) return -1; const Engine *e = ::Engine::Get(engine_id); switch (e->type) { case VEH_ROAD: case VEH_TRAIN: { CargoArray capacities = GetCapacityOfArticulatedParts(engine_id); for (CargoID c = 0; c < NUM_CARGO; c++) { if (capacities[c] == 0) continue; return capacities[c]; } return -1; } break; case VEH_SHIP: case VEH_AIRCRAFT: return e->GetDisplayDefaultCapacity(); break; default: NOT_REACHED(); } } /* static */ int32 AIEngine::GetReliability(EngineID engine_id) { if (!IsValidEngine(engine_id)) return -1; if (GetVehicleType(engine_id) == AIVehicle::VT_RAIL && IsWagon(engine_id)) return -1; return ::ToPercent16(::Engine::Get(engine_id)->reliability); } /* static */ int32 AIEngine::GetMaxSpeed(EngineID engine_id) { if (!IsValidEngine(engine_id)) return -1; const Engine *e = ::Engine::Get(engine_id); int32 max_speed = e->GetDisplayMaxSpeed(); // km-ish/h if (e->type == VEH_AIRCRAFT) max_speed /= _settings_game.vehicle.plane_speed; return max_speed; } /* static */ Money AIEngine::GetPrice(EngineID engine_id) { if (!IsValidEngine(engine_id)) return -1; return ::Engine::Get(engine_id)->GetCost(); } /* static */ int32 AIEngine::GetMaxAge(EngineID engine_id) { if (!IsValidEngine(engine_id)) return -1; if (GetVehicleType(engine_id) == AIVehicle::VT_RAIL && IsWagon(engine_id)) return -1; return ::Engine::Get(engine_id)->GetLifeLengthInDays(); } /* static */ Money AIEngine::GetRunningCost(EngineID engine_id) { if (!IsValidEngine(engine_id)) return -1; return ::Engine::Get(engine_id)->GetRunningCost(); } /* static */ int32 AIEngine::GetPower(EngineID engine_id) { if (!IsValidEngine(engine_id)) return -1; if (GetVehicleType(engine_id) != AIVehicle::VT_RAIL && GetVehicleType(engine_id) != AIVehicle::VT_ROAD) return -1; if (IsWagon(engine_id)) return -1; return ::Engine::Get(engine_id)->GetPower(); } /* static */ int32 AIEngine::GetWeight(EngineID engine_id) { if (!IsValidEngine(engine_id)) return -1; if (GetVehicleType(engine_id) != AIVehicle::VT_RAIL && GetVehicleType(engine_id) != AIVehicle::VT_ROAD) return -1; return ::Engine::Get(engine_id)->GetDisplayWeight(); } /* static */ int32 AIEngine::GetMaxTractiveEffort(EngineID engine_id) { if (!IsValidEngine(engine_id)) return -1; if (GetVehicleType(engine_id) != AIVehicle::VT_RAIL && GetVehicleType(engine_id) != AIVehicle::VT_ROAD) return -1; if (IsWagon(engine_id)) return -1; return ::Engine::Get(engine_id)->GetDisplayMaxTractiveEffort(); } /* static */ int32 AIEngine::GetDesignDate(EngineID engine_id) { if (!IsValidEngine(engine_id)) return -1; return ::Engine::Get(engine_id)->intro_date; } /* static */ AIVehicle::VehicleType AIEngine::GetVehicleType(EngineID engine_id) { if (!IsValidEngine(engine_id)) return AIVehicle::VT_INVALID; switch (::Engine::Get(engine_id)->type) { case VEH_ROAD: return AIVehicle::VT_ROAD; case VEH_TRAIN: return AIVehicle::VT_RAIL; case VEH_SHIP: return AIVehicle::VT_WATER; case VEH_AIRCRAFT: return AIVehicle::VT_AIR; default: NOT_REACHED(); } } /* static */ bool AIEngine::IsWagon(EngineID engine_id) { if (!IsValidEngine(engine_id)) return false; if (GetVehicleType(engine_id) != AIVehicle::VT_RAIL) return false; return ::RailVehInfo(engine_id)->power == 0; } /* static */ bool AIEngine::CanRunOnRail(EngineID engine_id, AIRail::RailType track_rail_type) { if (!IsValidEngine(engine_id)) return false; if (GetVehicleType(engine_id) != AIVehicle::VT_RAIL) return false; if (!AIRail::IsRailTypeAvailable(track_rail_type)) return false; return ::IsCompatibleRail((::RailType)::RailVehInfo(engine_id)->railtype, (::RailType)track_rail_type); } /* static */ bool AIEngine::HasPowerOnRail(EngineID engine_id, AIRail::RailType track_rail_type) { if (!IsValidEngine(engine_id)) return false; if (GetVehicleType(engine_id) != AIVehicle::VT_RAIL) return false; if (!AIRail::IsRailTypeAvailable(track_rail_type)) return false; return ::HasPowerOnRail((::RailType)::RailVehInfo(engine_id)->railtype, (::RailType)track_rail_type); } /* static */ AIRoad::RoadType AIEngine::GetRoadType(EngineID engine_id) { if (!IsValidEngine(engine_id)) return AIRoad::ROADTYPE_INVALID; if (GetVehicleType(engine_id) != AIVehicle::VT_ROAD) return AIRoad::ROADTYPE_INVALID; return HasBit(::EngInfo(engine_id)->misc_flags, EF_ROAD_TRAM) ? AIRoad::ROADTYPE_TRAM : AIRoad::ROADTYPE_ROAD; } /* static */ AIRail::RailType AIEngine::GetRailType(EngineID engine_id) { if (!IsValidEngine(engine_id)) return AIRail::RAILTYPE_INVALID; if (GetVehicleType(engine_id) != AIVehicle::VT_RAIL) return AIRail::RAILTYPE_INVALID; return (AIRail::RailType)(uint)::RailVehInfo(engine_id)->railtype; } /* static */ bool AIEngine::IsArticulated(EngineID engine_id) { if (!IsValidEngine(engine_id)) return false; if (GetVehicleType(engine_id) != AIVehicle::VT_ROAD && GetVehicleType(engine_id) != AIVehicle::VT_RAIL) return false; return CountArticulatedParts(engine_id, true) != 0; } /* static */ AIAirport::PlaneType AIEngine::GetPlaneType(EngineID engine_id) { if (!IsValidEngine(engine_id)) return AIAirport::PT_INVALID; if (GetVehicleType(engine_id) != AIVehicle::VT_AIR) return AIAirport::PT_INVALID; return (AIAirport::PlaneType)::AircraftVehInfo(engine_id)->subtype; }
oshepherd/openttd-progsigs
src/ai/api/ai_engine.cpp
C++
gpl-2.0
8,051
package com.aw.builder; import org.apache.commons.lang.StringUtils; import java.math.BigDecimal; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import java.util.*; /** * User: Kaiser * Date: 31/03/2009 */ public class RPRepository { public static Connection getConection() throws Exception { DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver()); return DriverManager.getConnection ("jdbc:oracle:thin:@192.168.1.37:1521:ORCL", "SUMIDESA", "SUMIDESA"); } public static String generateSqlForColumns(String tableName) { StringBuffer sql = new StringBuffer(); sql.append(" SELECT COLUMN_NAME,DATA_LENGTH,DATA_TYPE,DATA_PRECISION,NULLABLE "); sql.append(" FROM dba_tab_columns "); sql.append(" WHERE OWNER = '" + Context.schema + "' "); sql.append(" AND TABLE_NAME='" + tableName + "' "); sql.append(" AND COLUMN_NAME NOT LIKE 'PK%' "); sql.append(" AND COLUMN_NAME NOT LIKE 'DE%' "); sql.append(" AND COLUMN_NAME NOT IN ('USUA_CREA', "); sql.append(" 'FECH_CREA', "); sql.append(" 'NUIP_CREA', "); sql.append(" 'USSO_CREA', "); sql.append(" 'NOPC_CREA', "); sql.append(" 'USUA_MODI', "); sql.append(" 'FECH_MODI', "); sql.append(" 'NUIP_MODI', "); sql.append(" 'USSO_MODI', "); sql.append(" 'NOPC_MODI')"); System.out.println(sql.toString()); return sql.toString(); } public static String generateSqlForColumnsPks(String tableName) { StringBuffer sql = new StringBuffer(); sql.append(" SELECT COLUMN_NAME,DATA_LENGTH,DATA_TYPE,DATA_PRECISION,NULLABLE "); sql.append(" FROM dba_tab_columns "); sql.append(" WHERE OWNER = '" + Context.schema + "' "); sql.append(" AND TABLE_NAME='" + tableName + "' "); sql.append(" AND COLUMN_NAME LIKE 'PK%' "); System.out.println(sql.toString()); return sql.toString(); } public static List obtenerTables(List pks) throws Exception { StringBuffer sqlIn = new StringBuffer("("); boolean x = false; for (Iterator iterator = pks.iterator(); iterator.hasNext();) { String s = (String) iterator.next(); if (x) { sqlIn.append(","); } sqlIn.append("'").append(s).append("'"); x = true; } sqlIn.append(")"); StringBuffer sql = new StringBuffer(); sql.append(" SELECT TABLE_NAME ,COLUMN_NAME FROM dba_tab_columns WHERE OWNER = '" + Context.schema + "' and COLUMN_NAME IN "); sql.append(sqlIn); Connection conn = getConection(); Statement stmt = conn.createStatement(); ResultSet rset = stmt.executeQuery(sql.toString()); List tables = new ArrayList(); while (rset.next()) { Map map = new HashMap(); map.put("tableName", StringUtils.capitalize(Tools.generateNameBase(rset.getString(1)))); map.put("varName", Tools.generateNameBase(rset.getString(1))); map.put("pkFieldName", Tools.obtenerFieldName(rset.getString(2))); map.put("fkFieldName", Tools.obtenerFieldName(rset.getString(2).replaceAll("PK", "FK"))); tables.add(map); } stmt.close(); return tables; } public static List getTableDepends(List pks) throws Exception { if (pks.size() == 0) { return new ArrayList(); } StringBuffer sqlIn = new StringBuffer("("); boolean x = false; for (Iterator iterator = pks.iterator(); iterator.hasNext();) { String s = (String) iterator.next(); if (x) { sqlIn.append(","); } sqlIn.append("'").append(s).append("'"); x = true; } sqlIn.append(")"); StringBuffer sql = new StringBuffer(); sql.append(" SELECT TABLE_NAME ,COLUMN_NAME FROM dba_tab_columns WHERE OWNER = '" + Context.schema + "' and COLUMN_NAME IN "); sql.append(sqlIn); Connection conn = getConection(); Statement stmt = conn.createStatement(); ResultSet rset = stmt.executeQuery(sql.toString()); List tables = new ArrayList(); while (rset.next()) { Map map = new HashMap(); map.put("name", "gdp" + StringUtils.capitalize(Tools.generateNameBase(rset.getString(1)))); map.put("ipNameClass", "IP" + StringUtils.capitalize(Tools.generateNameBase(rset.getString(1)))); map.put("ipName", "ip" + StringUtils.capitalize(Tools.generateNameBase(rset.getString(1)))); tables.add(map); } stmt.close(); return tables; } public static List getMasterTable() throws Exception { String sql = (" SELECT TABLE_NAME FROM ALL_TABLES WHERE OWNER = '" + Context.schema + "' "); Connection conn = getConection(); Statement stmt = conn.createStatement(); ResultSet rset = stmt.executeQuery(sql); List tables = new ArrayList(); while (rset.next()) { BNTable table = new BNTable(); table.setTableName(rset.getString(1)); table.setMasterTable(rset.getString(1).endsWith("TM")); table.setUseDetail(rset.getString(1).endsWith("TC")); table.setUserBN(hasFK(rset.getString(1))); tables.add(table); } stmt.close(); return tables; } public static boolean hasFK(String tableName) throws Exception { String sql = (" SELECT count(*) FROM dba_tab_columns WHERE OWNER = '" + Context.schema + "' and TABLE_NAME='" + tableName + "' AND COLUMN_NAME LIKE 'FK%' "); Connection conn = getConection(); Statement stmt = conn.createStatement(); ResultSet rset = stmt.executeQuery(sql); BigDecimal numero = new BigDecimal(0); while (rset.next()) { numero = rset.getBigDecimal(1); } stmt.close(); return numero.intValue() != 0; } public static String getParentTable(String tableName) throws Exception { StringBuffer sql = new StringBuffer(); sql.append("SELECT TABLE_NAME "); sql.append("FROM dba_tab_columns "); sql.append("WHERE owner = 'SEGURIDADQA2' "); sql.append(" AND table_name LIKE '%TC' "); sql.append(" AND column_name IN "); sql.append(" ( SELECT REPLACE(COLUMN_NAME,'FK_','PK_') "); sql.append(" FROM dba_tab_columns "); sql.append(" WHERE owner = 'SEGURIDADQA2' "); sql.append(" AND table_name = 'VENTA_TD' "); sql.append(" AND column_name LIKE 'FK%' "); sql.append(" )"); Connection conn = getConection(); Statement stmt = conn.createStatement(); ResultSet rset = stmt.executeQuery(sql.toString()); String parentTable = ""; while (rset.next()) { parentTable = rset.getString(1); } stmt.close(); if (parentTable.equals("")) { return "Object"; } return parentTable; } public static List generateColumns(BNTable table) throws Exception { Connection conn = RPRepository.getConection(); Statement stmt = conn.createStatement(); ResultSet rset = stmt.executeQuery(RPRepository.generateSqlForColumns(table.getTableName())); List columnas = new ArrayList(); while (rset.next()) { Map map = new HashMap(); map.put("label", Tools.getLabel(rset.getString(1))); map.put("name", Tools.obtenerFieldName(rset.getString(1))); map.put("width", rset.getBigDecimal(2).intValue() * 3); map.put("lblName", "lbl" + StringUtils.capitalize(Tools.obtenerFieldName(rset.getString(1)))); map.put("lblValue", Tools.obtenerFieldName(rset.getString(1))); map.put("txtName", "txt" + StringUtils.capitalize(Tools.obtenerFieldName(rset.getString(1)))); String type = ""; StringBuffer validation = new StringBuffer(); if (rset.getString(5).equals("Y")) { validation.append("R"); } if (rset.getString(3).startsWith("VARCHAR2")) { type = "String"; validation.append("Y").append(rset.getBigDecimal(2)); } else if (rset.getString(3).equals("NUMBER")) { if (rset.getBigDecimal(4) != null && rset.getBigDecimal(4).intValue() != 0) { type = "Long"; } else { type = "BigDecimal"; } } else if (rset.getString(3).equals("DATE")) { type = "Date"; }else if (rset.getString(3).startsWith("CHAR")) { type = "String"; } map.put("type", type); map.put("validation", validation.toString()); map.put("methodName", StringUtils.capitalize(Tools.obtenerFieldName(rset.getString(1)))); columnas.add(map); } stmt.close(); return columnas; } }
AlanGuerraQuispe/SisAtuxPerfumeria
hbm-tools/src/com/aw/builder/RPRepository.java
Java
gpl-2.0
9,798
showWord(["n. ","Gratèl, lagratèl, maladi po ki atrapan; maladi po ki bay pi. Tretman gal fasil. 2. Enfeksyon nan plant." ])
georgejhunt/HaitiDictionary.activity
data/words/gal.js
JavaScript
gpl-2.0
126
//----------------------------------------------------------------------------- // File: VerilogWireWriter.h //----------------------------------------------------------------------------- // Project: Kactus2 // Author: Esko Pekkarinen // Date: 21.08.2014 // // Description: // Class for writing a Verilog wire declaration. //----------------------------------------------------------------------------- #ifndef VERILOGWIREWRITER_H #define VERILOGWIREWRITER_H #include <Plugins/VerilogGenerator/common/Writer.h> #include "../veriloggeneratorplugin_global.h" #include <Plugins/common/HDLParser/HDLParserCommon.h> //----------------------------------------------------------------------------- //! Class for writing a Verilog wire declaration. //----------------------------------------------------------------------------- class VERILOGGENERATORPLUGIN_EXPORT VerilogWireWriter : public Writer { public: //! The constructor. VerilogWireWriter(QString name, QPair<QString, QString> bounds, QPair<QString, QString> array); //! The destructor. virtual ~VerilogWireWriter(); /*! * Writes the wire to given output. * * @param [in] output The output to write to. */ virtual void write(QTextStream& output) const; private: // Disable copying. VerilogWireWriter(VerilogWireWriter const& rhs); VerilogWireWriter& operator=(VerilogWireWriter const& rhs); /*! * Creates a Verilog wire declaration. * * @return The Verilog wire declaration for this wire. */ QString createDeclaration() const; /*! * Gets the formatted size for the wire. * * @return The formatted size. */ QString formattedSize(QPair<QString, QString> const& bounds) const; //! The wire. QString name_; QPair<QString, QString> bounds_; QPair<QString, QString> array_; }; #endif // VERILOGWIREWRITER_H
kactus2/kactus2dev
Plugins/VerilogGenerator/VerilogWireWriter/VerilogWireWriter.h
C
gpl-2.0
1,979
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %standardphrasen und schnipsel in deutsch % %dient als vorlage für alle anderen sprachen % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% \newcommand{\anrede} {Sehr geehrte Damen und Herren,} \newcommand{\anredefrau} {Sehr geehrte Frau} \newcommand{\anredeherr} {Sehr geehrter Herr} \newcommand{\nr} {Nr.} \newcommand{\datum} {Datum} \newcommand{\kundennummer} {Kunden-Nr.} \newcommand{\ansprechpartner} {Ansprechpartner} \newcommand{\bearbeiter} {Bearbeiter} \newcommand{\gruesse} {Mit freundlichen Grüßen} \newcommand{\vom} {vom} \newcommand{\von} {von} \newcommand{\seite} {Seite} \newcommand{\uebertrag} {Übertrag} \newcommand{\position} {Pos.} \newcommand{\artikelnummer} {Art.-Nr.} \newcommand{\bild} {Bild} \newcommand{\keinbild} {kein Bild} \newcommand{\menge} {Menge} \newcommand{\bezeichnung} {Bezeichung} \newcommand{\seriennummer}{Seriennummer} \newcommand{\ean}{EAN} \newcommand{\projektnummer}{Projektnummer} \newcommand{\charge}{Charge} \newcommand{\mhd}{MHD} \newcommand{\einzelpreis} {E-Preis} \newcommand{\gesamtpreis} {G-Preis} \newcommand{\nettobetrag} {Nettobetrag} \newcommand{\schlussbetrag} {Gesamtbetrag} \newcommand{\weiteraufnaechsterseite} {weiter auf der nächsten Seite ...} \newcommand{\zahlung} {Zahlungsbedingungen:} \newcommand{\textTelefon} {Tel.:} \newcommand{\textFax} {Fax:} % angebot (sales_quotion) \newcommand{\angebot} {Angebot} \newcommand{\angebotsformel} {gerne unterbreiten wir Ihnen folgendes Angebot:} \newcommand{\angebotdanke} {Wir danken für Ihre Anfrage und hoffen, Ihnen hiermit ein interessantes Angebot gemacht zu haben.} \newcommand{\angebotgueltig} {Das Angebot ist freibleibend gültig bis zum} %Danach wird das Datum eingefügt, falls das grammatisch nicht funktionieren sollte müssen wir eine ausnahme für die sprache definieren \newcommand{\angebotfragen} {Sollten Sie noch Fragen oder Änderungswünsche haben, können Sie uns gerne jederzeit unter den unten genannten Telefonnummern oder E-Mail-Adressen kontaktieren.} \newcommand{\angebotagb} {Bei der Durchführung des Auftrags gelten unsere AGB, die wir Ihnen gerne zuschicken.} % auftragbestätigung (sales_order) \newcommand{\auftragsbestaetigung} {Auftragsbestätigung} \newcommand{\auftragsnummer} {Auftrag-Nr.} \newcommand{\ihreBestellnummer} {Ihre Bestellnummer} \newcommand{\auftragsformel} {hiermit bestätigen wir Ihnen folgende Bestellpostionen:} \newcommand{\lieferungErfolgtAm} {Die Lieferung erfolgt am} %Danach wird das Datum eingefügt, falls das grammatisch nicht funktionieren sollte müssen wir eine ausnahme für die sprache definieren \newcommand{\auftragpruefen} {Bitte kontrollieren Sie alle Positionen auf Übereinstimmung mit Ihrer Bestellung! Teilen Sie Abweichungen innerhalb von 3 Tagen mit!} \newcommand{\proformarechnung} {Proforma Rechnung} % lieferschein (sales_delivery_order) \newcommand{\lieferschein} {Lieferschein} % rechnung (invoice) \newcommand{\rechnung} {Rechnung} \newcommand{\rechnungsdatum} {Rechnungsdatum} \newcommand{\ihrebestellung} {Ihr Bestellung} \newcommand{\lieferdatum} {Lieferdatum} \newcommand{\rechnungsformel} {für unsere Leistungen erlauben wir uns, folgende Positionen in Rechnung zu stellen:} \newcommand{\zwischensumme} {Zwischensumme} \newcommand{\leistungsdatumGleichRechnungsdatum} {Das Leistungsdatum entspricht, soweit nicht anders angegeben, dem Rechnungsdatum.} \newcommand{\unserebankverbindung} {Unsere Bankverbindung} \newcommand{\textKontonummer} {Kontonummer:} \newcommand{\textBank} {bei der} \newcommand{\textBankleitzahl} {BLZ:} \newcommand{\textBic} {BIC:} \newcommand{\textIban} {IBAN:} \newcommand{\unsereustid} {Unsere USt-Identifikationsnummer lautet} \newcommand{\ihreustid} {Ihre USt-Identifikationsnummer:} \newcommand{\steuerfreiEU} {Steuerfreie, innergemeinschaftliche Lieferung.} \newcommand{\steuerfreiAUS} {Steuerfreie Lieferung ins außereuropäische Ausland.} \newcommand{\textUstid} {UStId:} % gutschrift (credit_note) \newcommand{\gutschrift} {Gutschrift} \newcommand{\fuerRechnung} {für Rechnung} \newcommand{\gutschriftformel} {wir erlauben uns, Ihnen folgenden Positionen gutzuschreiben:} % sammelrechnung (statement) \newcommand{\sammelrechnung} {Sammelrechnung} \newcommand{\sammelrechnungsformel} {bitte nehmen Sie zur Kenntnis, dass folgende Rechnungen unbeglichen sind:} \newcommand{\faellig} {Fälligkeit} \newcommand{\aktuell} {aktuell} \newcommand{\asDreissig} {30} \newcommand{\asSechzig} {60} \newcommand{\asNeunzig} {90+} % zahlungserinnerung (Mahnung) \newcommand{\mahnung} {Zahlungserinnerung} \newcommand{\mahnungsformel} {man kann seine Augen nicht überall haben - offensichtlich haben Sie übersehen, die folgenden Rechnungen zu begleichen:} \newcommand{\beruecksichtigtBis} {Zahlungseingänge sind nur berücksichtigt bis zum} \newcommand{\schonGezahlt} {Sollten Sie zwischenzeitlich bezahlt haben, betrachten Sie diese Zahlungserinnerung bitte als gegenstandslos.} % zahlungserinnerung_invoice (Rechnung zur Mahnung) \newcommand{\mahnungsrechnungsformel} {hiermit stellen wir Ihnen zu o.g. \mahnung \ folgende Posten in Rechnung:} \newcommand{\posten} {Posten} \newcommand{\betrag} {Betrag} \newcommand{\bitteZahlenBis} {Bitte begleichen Sie diese Forderung bis zum} % anfrage (request_quotion) \newcommand{\anfrage} {Anfrage} \newcommand{\anfrageformel} {bitte nennen Sie uns für folgende Artikel Preis und Liefertermin:} \newcommand{\anfrageBenoetigtBis} {Wir benötigen die Lieferung bis zum} %Danach wird das Datum eingefügt, falls das grammatisch nicht funktionieren sollte müssen wir eine ausnahme für die sprache definieren \newcommand{\anfragedanke} {Im Voraus besten Dank für Ihre Bemühungen.} % bestellung/auftrag (purchase_order) \newcommand{\bestellung} {Bestellung} \newcommand{\unsereBestellnummer} {Unsere Bestellnummer} \newcommand{\bestellformel} {hiermit bestellen wir verbindlich folgende Positionen:} % einkaufslieferschein (purchase_delivery_order) \newcommand{\einkaufslieferschein} {Eingangslieferschein}
mark-sch/Finance5
templates/print/RB/deutsch.tex
TeX
gpl-2.0
6,053
<?php namespace PoPSitesWassup\PostLinkMutations; use PoP\Root\AbstractComponentTest; /** * Made abstract to disable the test */ abstract class ComponentTest extends AbstractComponentTest { }
leoloso/PoP
layers/Wassup/packages/postlink-mutations/tests/ComponentTest.php
PHP
gpl-2.0
197
/** * @file sam3x_eth.h * @brief SAM3X Ethernet MAC controller * * @section License * * Copyright (C) 2010-2013 Oryx Embedded. All rights reserved. * * This file is part of CycloneTCP Open. * * 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. * * @author Oryx Embedded (www.oryx-embedded.com) * @version 1.3.8 **/ #ifndef _SAM3X_ETH_H #define _SAM3X_ETH_H //TX buffers #define SAM3X_TX_BUFFER_COUNT 3 #define SAM3X_TX_BUFFER_SIZE 1536 //RX buffers #define SAM3X_RX_BUFFER_COUNT 72 #define SAM3X_RX_BUFFER_SIZE 128 //RMII signals #define EMAC_RMII_MASK (PIO_PB9A_EMDIO | PIO_PB8A_EMDC | \ PIO_PB7A_ERXER | PIO_PB6A_ERX1 | PIO_PB5A_ERX0 | PIO_PB4A_ERXDV | \ PIO_PB3A_ETX1 | PIO_PB2A_ETX0 | PIO_PB1A_ETXEN | PIO_PB0A_ETXCK) //TX buffer descriptor flags #define EMAC_TX_USED 0x80000000 #define EMAC_TX_WRAP 0x40000000 #define EMAC_TX_ERROR 0x20000000 #define EMAC_TX_UNDERRUN 0x10000000 #define EMAC_TX_EXHAUSTED 0x08000000 #define EMAC_TX_NO_CRC 0x00010000 #define EMAC_TX_LAST 0x00008000 #define EMAC_TX_LENGTH 0x000007FF //RX buffer descriptor flags #define EMAC_RX_ADDRESS 0xFFFFFFFC #define EMAC_RX_WRAP 0x00000002 #define EMAC_RX_OWNERSHIP 0x00000001 #define EMAC_RX_BROADCAST 0x80000000 #define EMAC_RX_MULTICAST_HASH 0x40000000 #define EMAC_RX_UNICAST_HASH 0x20000000 #define EMAC_RX_EXT_ADDR 0x10000000 #define EMAC_RX_SAR1 0x04000000 #define EMAC_RX_SAR2 0x02000000 #define EMAC_RX_SAR3 0x01000000 #define EMAC_RX_SAR4 0x00800000 #define EMAC_RX_TYPE_ID 0x00400000 #define EMAC_RX_VLAN_TAG 0x00200000 #define EMAC_RX_PRIORITY_TAG 0x00100000 #define EMAC_RX_VLAN_PRIORITY 0x000E0000 #define EMAC_RX_CFI 0x00010000 #define EMAC_RX_EOF 0x00008000 #define EMAC_RX_SOF 0x00004000 #define EMAC_RX_OFFSET 0x00003000 #define EMAC_RX_LENGTH 0x00000FFF /** * @brief Transmit buffer descriptor **/ typedef struct { uint32_t address; uint32_t status; } Sam3xTxBufferDesc; /** * @brief Receive buffer descriptor **/ typedef struct { uint32_t address; uint32_t status; } Sam3xRxBufferDesc; //SAM3X Ethernet MAC driver extern const NicDriver sam3xEthDriver; //SAM3X Ethernet MAC related functions error_t sam3xEthInit(NetInterface *interface); void sam3xEthInitBufferDesc(NetInterface *interface); void sam3xEthTick(NetInterface *interface); void sam3xEthEnableIrq(NetInterface *interface); void sam3xEthDisableIrq(NetInterface *interface); void sam3xEthRxEventHandler(NetInterface *interface); error_t sam3xEthSetMacFilter(NetInterface *interface); error_t sam3xEthSendPacket(NetInterface *interface, const ChunkedBuffer *buffer, size_t offset); uint_t sam3xEthReceivePacket(NetInterface *interface, uint8_t *buffer, uint_t size); void sam3xEthWritePhyReg(uint8_t phyAddr, uint8_t regAddr, uint16_t data); uint16_t sam3xEthReadPhyReg(uint8_t phyAddr, uint8_t regAddr); #endif
steffanw/CycloneTCP
cyclone_tcp/drivers/sam3x_eth.h
C
gpl-2.0
3,827
<?php session_start(); include 'sanitasi.php'; include 'db.php'; $kode_barang = stringdoang($_POST['kode_barang']); $jumlah_baru = angkadoang($_POST['jumlah_baru']); $query7 = $db->query("SELECT * FROM barang WHERE kode_barang = '$kode_barang'"); $data1 = mysqli_fetch_array($query7); // mencari jumlah Barang $query0 = $db->query("SELECT SUM(jumlah_barang) AS jumlah_pembelian FROM detail_pembelian WHERE kode_barang = '$data1[kode_barang]'"); $cek0 = mysqli_fetch_array($query0); $jumlah_pembelian = $cek0['jumlah_pembelian']; $query1 = $db->query("SELECT SUM(jumlah) AS jumlah_item_masuk FROM detail_item_masuk WHERE kode_barang = '$data1[kode_barang]'"); $cek1 = mysqli_fetch_array($query1); $jumlah_item_masuk = $cek1['jumlah_item_masuk']; $query2 = $db->query("SELECT SUM(jumlah_retur) AS jumlah_retur_penjualan FROM detail_retur_penjualan WHERE kode_barang = '$data1[kode_barang]'"); $cek2 = mysqli_fetch_array($query2); $jumlah_retur_penjualan = $cek2['jumlah_retur_penjualan']; $query20 = $db->query("SELECT SUM(jumlah_awal) AS jumlah_stok_awal FROM stok_awal WHERE kode_barang = '$data1[kode_barang]'"); $cek20 = mysqli_fetch_array($query20); $jumlah_stok_awal = $cek20['jumlah_stok_awal']; $query200 = $db->query("SELECT SUM(selisih_fisik) AS jumlah_fisik FROM detail_stok_opname WHERE kode_barang = '$data1[kode_barang]'"); $cek200 = mysqli_fetch_array($query200); $jumlah_fisik = $cek200['jumlah_fisik']; //total barang 1 $total_1 = $jumlah_pembelian + $jumlah_item_masuk + $jumlah_retur_penjualan + $jumlah_stok_awal + $jumlah_fisik; $query3 = $db->query("SELECT SUM(jumlah_barang) AS jumlah_penjualan FROM detail_penjualan WHERE kode_barang = '$data1[kode_barang]'"); $cek3 = mysqli_fetch_array($query3); $jumlah_penjualan = $cek3['jumlah_penjualan']; $query4 = $db->query("SELECT SUM(jumlah) AS jumlah_item_keluar FROM detail_item_keluar WHERE kode_barang = '$data1[kode_barang]'"); $cek4 = mysqli_fetch_array($query4); $jumlah_item_keluar = $cek4['jumlah_item_keluar']; $query5 = $db->query("SELECT SUM(jumlah_retur) AS jumlah_retur_pembelian FROM detail_retur_pembelian WHERE kode_barang = '$data1[kode_barang]'"); $cek5 = mysqli_fetch_array($query5); $jumlah_retur_pembelian = $cek5['jumlah_retur_pembelian']; //total barang 2 $total_2 = $jumlah_penjualan + $jumlah_item_keluar + $jumlah_retur_pembelian; $stok_barang = $total_1 - $total_2; $limit = $data1['limit_stok']; $a = $stok_barang - $jumlah_baru; if ($limit > $a) { echo '<div class="alert alert-warning"> <strong>PERHATIAN!</strong> Persediaan Barang Mencapai Batas Limit Stok, Segera Melakukan Pembelian! </div>'; } if ($stok_barang < $jumlah_baru){ echo '<div class="alert alert-danger"> <strong>PERHATIAN!</strong> Jumlah Melebihi Sisa Barang. </div>'; } else{ $id = stringdoang($_POST['id']); $jumlah_barang = angkadoang($_POST['jumlah_barang']); $harga = angkadoang($_POST['harga']); $jumlah_baru = angkadoang($_POST['jumlah_baru']); $user = $_SESSION['nama']; $subtotal = $harga * $jumlah_baru; $query00 = $db->query("SELECT * FROM tbs_penjualan WHERE id = '$id'"); $data = mysqli_fetch_array($query00); $kode = $data['kode_barang']; $nomor = $data['no_faktur']; $query = $db->prepare("UPDATE tbs_penjualan SET jumlah_barang = ?, subtotal = ? WHERE id = ?"); $query->bind_param("iis", $jumlah_baru, $subtotal, $id); $query->execute(); if (!$query) { die('Query Error : '.$db->errno. ' - '.$db->error); } else { echo '<div class="alert alert-info"> <strong>SUKSES!</strong> Penjualan Berhasil. </div>'; } $query9 = $db->query("SELECT * FROM fee_produk WHERE nama_petugas = '$user' AND kode_produk = '$kode'"); $cek9 = mysqli_fetch_array($query9); $prosentase = $cek9['jumlah_prosentase']; $nominal = $cek9['jumlah_uang']; if ($prosentase != 0) { $fee_prosentase_produk = $prosentase * $subtotal / 100; $query1 = $db->query("UPDATE tbs_fee_produk SET jumlah_fee = '$fee_prosentase_produk' WHERE nama_petugas = '$user' AND kode_produk = '$kode' AND no_faktur = '$nomor'"); } elseif ($nominal != 0) { $fee_nominal_produk = $nominal * $jumlah_baru; $query01 = $db->query("UPDATE tbs_fee_produk SET jumlah_fee = '$fee_nominal_produk' WHERE nama_petugas = '$user' AND kode_produk = '$kode' AND no_faktur = '$nomor'"); } } //Untuk Memutuskan Koneksi Ke Database mysqli_close($db); ?>
haidarafif0809/qwooxcqmkozzxce
update_tbs_pos.php
PHP
gpl-2.0
4,986
/* * Copyright (C) 2005-2011 MaNGOS <http://getmangos.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 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 "MoveMap.h" #include "Map.h" #include "Creature.h" #include "PathFinder.h" #include "Log.h" #include "DetourCommon.h" ////////////////// PathInfo ////////////////// PathInfo::PathInfo(const Unit* owner, float destX, float destY, float destZ, bool forceDest) : m_polyLength(0), m_type(PATHFIND_BLANK), m_forceDestination(forceDest), m_pointPathLimit(MAX_POINT_PATH_LENGTH), m_sourceUnit(owner), m_navMesh(NULL), m_navMeshQuery(NULL) { PathNode endPoint(destX, destY, destZ); setEndPosition(endPoint); float x,y,z; m_sourceUnit->GetPosition(x, y, z); PathNode startPoint(x, y, z); setStartPosition(startPoint); //DEBUG_FILTER_LOG(LOG_FILTER_PATHFINDING, "++ PathInfo::PathInfo for %u \n", m_sourceUnit->GetGUIDLow()); uint32 mapId = m_sourceUnit->GetMapId(); if (MMAP::MMapFactory::IsPathfindingEnabled()) { MMAP::MMapManager* mmap = MMAP::MMapFactory::createOrGetMMapManager(); m_navMesh = mmap->GetNavMesh(mapId); m_navMeshQuery = mmap->GetNavMeshQuery(mapId, m_sourceUnit->GetInstanceId()); } createFilter(); if (m_navMesh && m_navMeshQuery && HaveTile(endPoint) && !m_sourceUnit->hasUnitState(UNIT_STAT_IGNORE_PATHFINDING)) { BuildPolyPath(startPoint, endPoint); } else { BuildShortcut(); m_type = PathType(PATHFIND_NORMAL | PATHFIND_NOT_USING_PATH); } } PathInfo::~PathInfo() { //DEBUG_FILTER_LOG(LOG_FILTER_PATHFINDING, "++ PathInfo::~PathInfo() for %u \n", m_sourceUnit->GetGUIDLow()); } bool PathInfo::Update(float destX, float destY, float destZ, bool forceDest) { PathNode newDest(destX, destY, destZ); PathNode oldDest = getEndPosition(); setEndPosition(newDest); float x, y, z; m_sourceUnit->GetPosition(x, y, z); PathNode newStart(x, y, z); PathNode oldStart = getStartPosition(); setStartPosition(newStart); m_forceDestination = forceDest; //DEBUG_FILTER_LOG(LOG_FILTER_PATHFINDING, "++ PathInfo::Update() for %u \n", m_sourceUnit->GetGUIDLow()); // make sure navMesh works - we can run on map w/o mmap // check if the start and end point have a .mmtile loaded (can we pass via not loaded tile on the way?) if (!m_navMesh || !m_navMeshQuery || m_sourceUnit->hasUnitState(UNIT_STAT_IGNORE_PATHFINDING) || !HaveTile(newStart) || !HaveTile(newDest)) { BuildShortcut(); m_type = PathType(PATHFIND_NORMAL | PATHFIND_NOT_USING_PATH); return true; } updateFilter(); // check if destination moved - if not we can optimize something here // we are following old, precalculated path? float dist = m_sourceUnit->GetObjectSize(); if (inRange(oldDest, newDest, dist, dist) && m_pathPoints.size() > 2) { // our target is not moving - we just coming closer // we are moving on precalculated path - enjoy the ride //DEBUG_FILTER_LOG(LOG_FILTER_PATHFINDING, "++ PathInfo::Update:: precalculated path\n"); m_pathPoints.crop(1, 0); setNextPosition(m_pathPoints[1]); return false; } else { // target moved, so we need to update the poly path BuildPolyPath(newStart, newDest); return true; } } dtPolyRef PathInfo::getPathPolyByPosition(const dtPolyRef *polyPath, uint32 polyPathSize, const float* point, float *distance) const { if (!polyPath || !polyPathSize) return INVALID_POLYREF; dtPolyRef nearestPoly = INVALID_POLYREF; float minDist2d = FLT_MAX; float minDist3d = 0.0f; for (uint32 i = 0; i < polyPathSize; ++i) { float closestPoint[VERTEX_SIZE]; if (DT_SUCCESS != m_navMeshQuery->closestPointOnPoly(polyPath[i], point, closestPoint)) continue; float d = dtVdist2DSqr(point, closestPoint); if (d < minDist2d) { minDist2d = d; nearestPoly = polyPath[i]; minDist3d = dtVdistSqr(point, closestPoint); } if(minDist2d < 1.0f) // shortcut out - close enough for us break; } if (distance) *distance = dtSqrt(minDist3d); return (minDist2d < 3.0f) ? nearestPoly : INVALID_POLYREF; } dtPolyRef PathInfo::getPolyByLocation(const float* point, float *distance) const { // first we check the current path // if the current path doesn't contain the current poly, // we need to use the expensive navMesh.findNearestPoly dtPolyRef polyRef = getPathPolyByPosition(m_pathPolyRefs, m_polyLength, point, distance); if(polyRef != INVALID_POLYREF) return polyRef; // we don't have it in our old path // try to get it by findNearestPoly() // first try with low search box float extents[VERTEX_SIZE] = {3.0f, 5.0f, 3.0f}; // bounds of poly search area float closestPoint[VERTEX_SIZE] = {0.0f, 0.0f, 0.0f}; dtStatus result = m_navMeshQuery->findNearestPoly(point, extents, &m_filter, &polyRef, closestPoint); if(DT_SUCCESS == result && polyRef != INVALID_POLYREF) { *distance = dtVdist(closestPoint, point); return polyRef; } // still nothing .. // try with bigger search box extents[1] = 200.0f; result = m_navMeshQuery->findNearestPoly(point, extents, &m_filter, &polyRef, closestPoint); if(DT_SUCCESS == result && polyRef != INVALID_POLYREF) { *distance = dtVdist(closestPoint, point); return polyRef; } return INVALID_POLYREF; } void PathInfo::BuildPolyPath(const PathNode &startPos, const PathNode &endPos) { // *** getting start/end poly logic *** float distToStartPoly, distToEndPoly; float startPoint[VERTEX_SIZE] = {startPos.y, startPos.z, startPos.x}; float endPoint[VERTEX_SIZE] = {endPos.y, endPos.z, endPos.x}; dtPolyRef startPoly = getPolyByLocation(startPoint, &distToStartPoly); dtPolyRef endPoly = getPolyByLocation(endPoint, &distToEndPoly); // we have a hole in our mesh // make shortcut path and mark it as NOPATH ( with flying exception ) // its up to caller how he will use this info if (startPoly == INVALID_POLYREF || endPoly == INVALID_POLYREF) { //DEBUG_FILTER_LOG(LOG_FILTER_PATHFINDING, "++ BuildPolyPath :: (startPoly == 0 || endPoly == 0)\n"); BuildShortcut(); m_type = (m_sourceUnit->GetTypeId() == TYPEID_UNIT && ((Creature*)m_sourceUnit)->canFly()) ? PathType(PATHFIND_NORMAL | PATHFIND_NOT_USING_PATH) : PATHFIND_NOPATH; return; } // we may need a better number here bool farFromPoly = (distToStartPoly > 7.0f || distToEndPoly > 7.0f); if (farFromPoly) { //DEBUG_FILTER_LOG(LOG_FILTER_PATHFINDING, "++ BuildPolyPath :: farFromPoly distToStartPoly=%.3f distToEndPoly=%.3f\n", distToStartPoly, distToEndPoly); bool buildShotrcut = false; if (m_sourceUnit->GetTypeId() == TYPEID_UNIT) { Creature* owner = (Creature*)m_sourceUnit; PathNode p = (distToStartPoly > 7.0f) ? startPos : endPos; if (m_sourceUnit->GetMap()->IsUnderWater(p.x, p.y, p.z)) { //DEBUG_FILTER_LOG(LOG_FILTER_PATHFINDING, "++ BuildPolyPath :: underWater case\n"); if (owner->canSwim()) buildShotrcut = true; } else { //DEBUG_FILTER_LOG(LOG_FILTER_PATHFINDING, "++ BuildPolyPath :: flying case\n"); if (owner->canFly()) buildShotrcut = true; } } if (buildShotrcut) { BuildShortcut(); m_type = PathType(PATHFIND_NORMAL | PATHFIND_NOT_USING_PATH); return; } else { float closestPoint[VERTEX_SIZE]; // we may want to use closestPointOnPolyBoundary instead if (DT_SUCCESS == m_navMeshQuery->closestPointOnPoly(endPoly, endPoint, closestPoint)) { dtVcopy(endPoint, closestPoint); setActualEndPosition(PathNode(endPoint[2],endPoint[0],endPoint[1])); } m_type = PATHFIND_INCOMPLETE; } } // *** poly path generating logic *** // start and end are on same polygon // just need to move in straight line if (startPoly == endPoly) { //DEBUG_FILTER_LOG(LOG_FILTER_PATHFINDING, "++ BuildPolyPath :: (startPoly == endPoly)\n"); BuildShortcut(); m_pathPolyRefs[0] = startPoly; m_polyLength = 1; m_type = farFromPoly ? PATHFIND_INCOMPLETE : PATHFIND_NORMAL; //DEBUG_FILTER_LOG(LOG_FILTER_PATHFINDING, "++ BuildPolyPath :: path type %d\n", m_type); return; } // look for startPoly/endPoly in current path // TODO: we can merge it with getPathPolyByPosition() loop bool startPolyFound = false; bool endPolyFound = false; uint32 pathStartIndex, pathEndIndex; if (m_polyLength) { for (pathStartIndex = 0; pathStartIndex < m_polyLength; ++pathStartIndex) { // here to carch few bugs ASSERT(m_pathPolyRefs[pathStartIndex] != INVALID_POLYREF); if (m_pathPolyRefs[pathStartIndex] == startPoly) { startPolyFound = true; break; } } for (pathEndIndex = m_polyLength-1; pathEndIndex > pathStartIndex; --pathEndIndex) if (m_pathPolyRefs[pathEndIndex] == endPoly) { endPolyFound = true; break; } } if (startPolyFound && endPolyFound) { //DEBUG_FILTER_LOG(LOG_FILTER_PATHFINDING, "++ BuildPolyPath :: (startPolyFound && endPolyFound)\n"); // we moved along the path and the target did not move out of our old poly-path // our path is a simple subpath case, we have all the data we need // just "cut" it out m_polyLength = pathEndIndex - pathStartIndex + 1; memmove(m_pathPolyRefs, m_pathPolyRefs+pathStartIndex, m_polyLength*sizeof(dtPolyRef)); } else if (startPolyFound && !endPolyFound) { //DEBUG_FILTER_LOG(LOG_FILTER_PATHFINDING, "++ BuildPolyPath :: (startPolyFound && !endPolyFound)\n"); // we are moving on the old path but target moved out // so we have atleast part of poly-path ready m_polyLength -= pathStartIndex; // try to adjust the suffix of the path instead of recalculating entire length // at given interval the target cannot get too far from its last location // thus we have less poly to cover // sub-path of optimal path is optimal // take ~80% of the original length // TODO : play with the values here uint32 prefixPolyLength = uint32(m_polyLength*0.8f + 0.5f); memmove(m_pathPolyRefs, m_pathPolyRefs+pathStartIndex, prefixPolyLength*sizeof(dtPolyRef)); dtPolyRef suffixStartPoly = m_pathPolyRefs[prefixPolyLength-1]; // we need any point on our suffix start poly to generate poly-path, so we need last poly in prefix data float suffixEndPoint[VERTEX_SIZE]; if (DT_SUCCESS != m_navMeshQuery->closestPointOnPoly(suffixStartPoly, endPoint, suffixEndPoint)) { // we can hit offmesh connection as last poly - closestPointOnPoly() don't like that // try to recover by using prev polyref --prefixPolyLength; suffixStartPoly = m_pathPolyRefs[prefixPolyLength-1]; if (DT_SUCCESS != m_navMeshQuery->closestPointOnPoly(suffixStartPoly, endPoint, suffixEndPoint)) { // suffixStartPoly is still invalid, error state BuildShortcut(); m_type = PATHFIND_NOPATH; return; } } // generate suffix uint32 suffixPolyLength = 0; dtStatus dtResult = m_navMeshQuery->findPath( suffixStartPoly, // start polygon endPoly, // end polygon suffixEndPoint, // start position endPoint, // end position &m_filter, // polygon search filter m_pathPolyRefs + prefixPolyLength - 1, // [out] path (int*)&suffixPolyLength, MAX_PATH_LENGTH-prefixPolyLength); // max number of polygons in output path if (!suffixPolyLength || dtResult != DT_SUCCESS) { // this is probably an error state, but we'll leave it // and hopefully recover on the next Update // we still need to copy our preffix sLog->outError("%u's Path Build failed: 0 length path", m_sourceUnit->GetGUIDLow()); } //DEBUG_FILTER_LOG(LOG_FILTER_PATHFINDING, "++ m_polyLength=%u prefixPolyLength=%u suffixPolyLength=%u \n",m_polyLength, prefixPolyLength, suffixPolyLength); // new path = prefix + suffix - overlap m_polyLength = prefixPolyLength + suffixPolyLength - 1; } else { //DEBUG_FILTER_LOG(LOG_FILTER_PATHFINDING, "++ BuildPolyPath :: (!startPolyFound && !endPolyFound)\n"); // either we have no path at all -> first run // or something went really wrong -> we aren't moving along the path to the target // just generate new path // free and invalidate old path data clear(); dtStatus dtResult = m_navMeshQuery->findPath( startPoly, // start polygon endPoly, // end polygon startPoint, // start position endPoint, // end position &m_filter, // polygon search filter m_pathPolyRefs, // [out] path (int*)&m_polyLength, MAX_PATH_LENGTH); // max number of polygons in output path if (!m_polyLength || dtResult != DT_SUCCESS) { // only happens if we passed bad data to findPath(), or navmesh is messed up sLog->outError("%u's Path Build failed: 0 length path", m_sourceUnit->GetGUIDLow()); BuildShortcut(); m_type = PATHFIND_NOPATH; return; } } // by now we know what type of path we can get if (m_pathPolyRefs[m_polyLength - 1] == endPoly && !(m_type & PATHFIND_INCOMPLETE)) m_type = PATHFIND_NORMAL; else m_type = PATHFIND_INCOMPLETE; // generate the point-path out of our up-to-date poly-path BuildPointPath(startPoint, endPoint); } void PathInfo::BuildPointPath(const float *startPoint, const float *endPoint) { float pathPoints[MAX_POINT_PATH_LENGTH*VERTEX_SIZE]; uint32 pointCount = 0; dtStatus dtResult = DT_FAILURE; if (m_useStraightPath) { dtResult = m_navMeshQuery->findStraightPath( startPoint, // start position endPoint, // end position m_pathPolyRefs, // current path m_polyLength, // lenth of current path pathPoints, // [out] path corner points NULL, // [out] flags NULL, // [out] shortened path (int*)&pointCount, m_pointPathLimit); // maximum number of points/polygons to use } else { dtResult = findSmoothPath( startPoint, // start position endPoint, // end position m_pathPolyRefs, // current path m_polyLength, // length of current path pathPoints, // [out] path corner points (int*)&pointCount, m_pointPathLimit); // maximum number of points } if (pointCount < 2 || dtResult != DT_SUCCESS) { // only happens if pass bad data to findStraightPath or navmesh is broken // single point paths can be generated here // TODO : check the exact cases //DEBUG_FILTER_LOG(LOG_FILTER_PATHFINDING, "++ PathInfo::BuildPointPath FAILED! path sized %d returned\n", pointCount); sLog->outDebug("++ PathInfo::BuildPointPath FAILED! path sized %d returned\n", pointCount); BuildShortcut(); m_type = PATHFIND_NOPATH; return; } m_pathPoints.resize(pointCount); for (uint32 i = 0; i < pointCount; ++i) m_pathPoints.set(i, PathNode(pathPoints[i*VERTEX_SIZE+2], pathPoints[i*VERTEX_SIZE], pathPoints[i*VERTEX_SIZE+1])); // first point is always our current location - we need the next one setNextPosition(m_pathPoints[1]); setActualEndPosition(m_pathPoints[pointCount-1]); // force the given destination, if needed if (m_forceDestination && (!(m_type & PATHFIND_NORMAL) || !inRange(getEndPosition(), getActualEndPosition(), 1.0f, 1.0f))) { // we may want to keep partial subpath if(dist3DSqr(getActualEndPosition(), getEndPosition()) < 0.3f * dist3DSqr(getStartPosition(), getEndPosition())) { setActualEndPosition(getEndPosition()); m_pathPoints.set(m_pathPoints.size()-1, getEndPosition()); } else { setActualEndPosition(getEndPosition()); BuildShortcut(); } m_type = PathType(PATHFIND_NORMAL | PATHFIND_NOT_USING_PATH); } } void PathInfo::BuildShortcut() { //DEBUG_FILTER_LOG(LOG_FILTER_PATHFINDING, "++ BuildShortcut :: making shortcut\n"); clear(); // make two point path, our curr pos is the start, and dest is the end m_pathPoints.resize(2); // set start and a default next position m_pathPoints.set(0, getStartPosition()); m_pathPoints.set(1, getActualEndPosition()); setNextPosition(getActualEndPosition()); m_type = PATHFIND_SHORTCUT; } void PathInfo::createFilter() { uint16 includeFlags = 0; uint16 excludeFlags = 0; if (m_sourceUnit->GetTypeId() == TYPEID_UNIT) { Creature* creature = (Creature*)m_sourceUnit; if (creature->canWalk()) includeFlags |= NAV_GROUND; // walk // creatures don't take environmental damage if (creature->canSwim()) includeFlags |= (NAV_WATER | NAV_MAGMA | NAV_SLIME); // swim } else if (m_sourceUnit->GetTypeId() == TYPEID_PLAYER) { // perfect support not possible, just stay 'safe' includeFlags |= (NAV_GROUND | NAV_WATER); } m_filter.setIncludeFlags(includeFlags); m_filter.setExcludeFlags(excludeFlags); updateFilter(); } void PathInfo::updateFilter() { // allow creatures to cheat and use different movement types if they are moved // forcefully into terrain they can't normally move in if (m_sourceUnit->IsInWater() || m_sourceUnit->IsUnderWater()) { uint16 includedFlags = m_filter.getIncludeFlags(); includedFlags |= getNavTerrain(m_sourceUnit->GetPositionX(), m_sourceUnit->GetPositionY(), m_sourceUnit->GetPositionZ()); m_filter.setIncludeFlags(includedFlags); } } NavTerrain PathInfo::getNavTerrain(float x, float y, float z) { LiquidData data; m_sourceUnit->GetMap()->getLiquidStatus(x, y, z, MAP_ALL_LIQUIDS, &data); switch (data.type) { case MAP_LIQUID_TYPE_WATER: case MAP_LIQUID_TYPE_OCEAN: return NAV_WATER; case MAP_LIQUID_TYPE_MAGMA: return NAV_MAGMA; case MAP_LIQUID_TYPE_SLIME: return NAV_SLIME; default: return NAV_GROUND; } } bool PathInfo::HaveTile(const PathNode &p) const { int tx, ty; float point[VERTEX_SIZE] = {p.y, p.z, p.x}; m_navMesh->calcTileLoc(point, &tx, &ty); return (m_navMesh->getTileAt(tx, ty) != NULL); } uint32 PathInfo::fixupCorridor(dtPolyRef* path, uint32 npath, uint32 maxPath, const dtPolyRef* visited, uint32 nvisited) { int32 furthestPath = -1; int32 furthestVisited = -1; // Find furthest common polygon. for (int32 i = npath-1; i >= 0; --i) { bool found = false; for (int32 j = nvisited-1; j >= 0; --j) { if (path[i] == visited[j]) { furthestPath = i; furthestVisited = j; found = true; } } if (found) break; } // If no intersection found just return current path. if (furthestPath == -1 || furthestVisited == -1) return npath; // Concatenate paths. // Adjust beginning of the buffer to include the visited. uint32 req = nvisited - furthestVisited; uint32 orig = uint32(furthestPath+1) < npath ? furthestPath+1 : npath; uint32 size = npath > orig ? npath-orig : 0; if (req+size > maxPath) size = maxPath-req; if (size) memmove(path+req, path+orig, size*sizeof(dtPolyRef)); // Store visited for (uint32 i = 0; i < req; ++i) path[i] = visited[(nvisited-1)-i]; return req+size; } bool PathInfo::getSteerTarget(const float* startPos, const float* endPos, float minTargetDist, const dtPolyRef* path, uint32 pathSize, float* steerPos, unsigned char& steerPosFlag, dtPolyRef& steerPosRef) { // Find steer target. static const uint32 MAX_STEER_POINTS = 3; float steerPath[MAX_STEER_POINTS*VERTEX_SIZE]; unsigned char steerPathFlags[MAX_STEER_POINTS]; dtPolyRef steerPathPolys[MAX_STEER_POINTS]; uint32 nsteerPath = 0; dtStatus dtResult = m_navMeshQuery->findStraightPath(startPos, endPos, path, pathSize, steerPath, steerPathFlags, steerPathPolys, (int*)&nsteerPath, MAX_STEER_POINTS); if (!nsteerPath || DT_SUCCESS != dtResult) return false; // Find vertex far enough to steer to. uint32 ns = 0; while (ns < nsteerPath) { // Stop at Off-Mesh link or when point is further than slop away. if ((steerPathFlags[ns] & DT_STRAIGHTPATH_OFFMESH_CONNECTION) || !inRangeYZX(&steerPath[ns*VERTEX_SIZE], startPos, minTargetDist, 1000.0f)) break; ns++; } // Failed to find good point to steer to. if (ns >= nsteerPath) return false; dtVcopy(steerPos, &steerPath[ns*VERTEX_SIZE]); steerPos[1] = startPos[1]; // keep Z value steerPosFlag = steerPathFlags[ns]; steerPosRef = steerPathPolys[ns]; return true; } dtStatus PathInfo::findSmoothPath(const float* startPos, const float* endPos, const dtPolyRef* polyPath, uint32 polyPathSize, float* smoothPath, int* smoothPathSize, uint32 maxSmoothPathSize) { *smoothPathSize = 0; uint32 nsmoothPath = 0; dtPolyRef polys[MAX_PATH_LENGTH]; memcpy(polys, polyPath, sizeof(dtPolyRef)*polyPathSize); uint32 npolys = polyPathSize; float iterPos[VERTEX_SIZE], targetPos[VERTEX_SIZE]; if(DT_SUCCESS != m_navMeshQuery->closestPointOnPolyBoundary(polys[0], startPos, iterPos)) return DT_FAILURE; if(DT_SUCCESS != m_navMeshQuery->closestPointOnPolyBoundary(polys[npolys-1], endPos, targetPos)) return DT_FAILURE; dtVcopy(&smoothPath[nsmoothPath*VERTEX_SIZE], iterPos); nsmoothPath++; // Move towards target a small advancement at a time until target reached or // when ran out of memory to store the path. while (npolys && nsmoothPath < maxSmoothPathSize) { // Find location to steer towards. float steerPos[VERTEX_SIZE]; unsigned char steerPosFlag; dtPolyRef steerPosRef = INVALID_POLYREF; if (!getSteerTarget(iterPos, targetPos, SMOOTH_PATH_SLOP, polys, npolys, steerPos, steerPosFlag, steerPosRef)) break; bool endOfPath = (steerPosFlag & DT_STRAIGHTPATH_END); bool offMeshConnection = (steerPosFlag & DT_STRAIGHTPATH_OFFMESH_CONNECTION); // Find movement delta. float delta[VERTEX_SIZE]; dtVsub(delta, steerPos, iterPos); float len = dtSqrt(dtVdot(delta,delta)); // If the steer target is end of path or off-mesh link, do not move past the location. if ((endOfPath || offMeshConnection) && len < SMOOTH_PATH_STEP_SIZE) len = 1.0f; else len = SMOOTH_PATH_STEP_SIZE / len; float moveTgt[VERTEX_SIZE]; dtVmad(moveTgt, iterPos, delta, len); // Move float result[VERTEX_SIZE]; const static uint32 MAX_VISIT_POLY = 16; dtPolyRef visited[MAX_VISIT_POLY]; uint32 nvisited = 0; m_navMeshQuery->moveAlongSurface(polys[0], iterPos, moveTgt, &m_filter, result, visited, (int*)&nvisited, MAX_VISIT_POLY); npolys = fixupCorridor(polys, npolys, MAX_PATH_LENGTH, visited, nvisited); m_navMeshQuery->getPolyHeight(polys[0], result, &result[1]); result[1] += 0.5f; dtVcopy(iterPos, result); // Handle end of path and off-mesh links when close enough. if (endOfPath && inRangeYZX(iterPos, steerPos, SMOOTH_PATH_SLOP, 1.0f)) { // Reached end of path. dtVcopy(iterPos, targetPos); if (nsmoothPath < maxSmoothPathSize) { dtVcopy(&smoothPath[nsmoothPath*VERTEX_SIZE], iterPos); nsmoothPath++; } break; } else if (offMeshConnection && inRangeYZX(iterPos, steerPos, SMOOTH_PATH_SLOP, 1.0f)) { // Advance the path up to and over the off-mesh connection. dtPolyRef prevRef = INVALID_POLYREF; dtPolyRef polyRef = polys[0]; uint32 npos = 0; while (npos < npolys && polyRef != steerPosRef) { prevRef = polyRef; polyRef = polys[npos]; npos++; } for (uint32 i = npos; i < npolys; ++i) polys[i-npos] = polys[i]; npolys -= npos; // Handle the connection. float startPos[VERTEX_SIZE], endPos[VERTEX_SIZE]; if (DT_SUCCESS == m_navMesh->getOffMeshConnectionPolyEndPoints(prevRef, polyRef, startPos, endPos)) { if (nsmoothPath < maxSmoothPathSize) { dtVcopy(&smoothPath[nsmoothPath*VERTEX_SIZE], startPos); nsmoothPath++; } // Move position at the other side of the off-mesh link. dtVcopy(iterPos, endPos); m_navMeshQuery->getPolyHeight(polys[0], iterPos, &iterPos[1]); iterPos[1] += 0.5f; } } // Store results. if (nsmoothPath < maxSmoothPathSize) { dtVcopy(&smoothPath[nsmoothPath*VERTEX_SIZE], iterPos); nsmoothPath++; } } *smoothPathSize = nsmoothPath; // this is most likely a loop return nsmoothPath < MAX_POINT_PATH_LENGTH ? DT_SUCCESS : DT_FAILURE; } bool PathInfo::inRangeYZX(const float* v1, const float* v2, float r, float h) const { const float dx = v2[0] - v1[0]; const float dy = v2[1] - v1[1]; // elevation const float dz = v2[2] - v1[2]; return (dx*dx + dz*dz) < r*r && fabsf(dy) < h; } bool PathInfo::inRange(const PathNode &p1, const PathNode &p2, float r, float h) const { const float dx = p2.x - p1.x; const float dy = p2.y - p1.y; const float dz = p2.z - p1.z; return (dx*dx + dy*dy) < r*r && fabsf(dz) < h; } float PathInfo::dist3DSqr(const PathNode &p1, const PathNode &p2) const { const float dx = p2.x - p1.x; const float dy = p2.y - p1.y; const float dz = p2.z - p1.z; return (dx*dx + dy*dy + dz*dz); }
hlarsen/TBCPvP
src/server/game/Pathfinding/PathFinder.cpp
C++
gpl-2.0
28,922
package com.fred.patten.n_observerpattern; public class ConcreteSubject extends Subject{ private String subjectStatus; public String getSubjectStatus() { return subjectStatus; } public void setSubjectStatus(String subjectStatus) { this.subjectStatus = subjectStatus; } }
fredxiangdong/try
another/src/com/fred/patten/n_observerpattern/ConcreteSubject.java
Java
gpl-2.0
287
/* * TrotTrax * Copyright (c) 2015-2016 Katy Brimm * This source file is licensed under the GNU General Public License. * Please see the file LICENSE in this distribution for license terms. * Contact: info@trottrax.org */ using System; using System.Collections.Generic; using System.Data.SQLite; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TrotTrax { public partial class DBDriver { // Interactions for <year>_class table #region Select Statements public ClassItem GetClassItem(int classNo) { // Construct and execute the query SQLiteCommand query = new SQLiteCommand(); query.CommandText = "SELECT class_no, category_no, class_name, fee FROM [" + Year + "_class] WHERE class_no = @noparam;"; query.CommandType = System.Data.CommandType.Text; query.Parameters.Add(new SQLiteParameter("@noparam", classNo)); query.Connection = ClubConn; SQLiteDataReader reader = DoTheReader(query); // Read the results ClassItem item = new ClassItem(); while (reader.Read()) { item.No = reader.GetInt32(0); item.CatNo = reader.GetInt32(1); item.Name = reader.GetString(2); item.Fee = reader.GetDecimal(3); } reader.Close(); ClubConn.Close(); return item; } //Optional: sort (default is class_no) public List<ClassItem> GetClassItemList(ClassSort sort = ClassSort.Default) { // Case statment for sort column string sortString; switch (sort) { case ClassSort.Name: sortString = "class_name"; break; case ClassSort.Category: sortString = "category_no"; break; default: sortString = "class_no"; break; } // Construct and execute the query string query = "SELECT class_no, category_no, class_name, fee FROM [" + Year + "_class] ORDER BY " + sortString + ";"; SQLiteDataReader reader = DoTheReader(ClubConn, query); List<ClassItem> classItemList = new List<ClassItem>(); ClassItem item; // Read the results reader = DoTheReader(ClubConn, query); while (reader.Read()) { item = new ClassItem(); item.No = reader.GetInt32(0); item.CatNo = reader.GetInt32(1); item.Name = reader.GetString(2); item.Fee = reader.GetDecimal(3); classItemList.Add(item); } reader.Close(); ClubConn.Close(); return classItemList; } #endregion #region Insert Statements public bool AddClassItem(int classNo, int category, string name, decimal fee) { // Construct and execute the query SQLiteCommand query = new SQLiteCommand(); query.CommandText = "INSERT INTO [" + Year + "_class] " + "(class_no, category_no, class_name, fee) " + "VALUES (@noparam, @catparam, @nameparam, @feeparam);"; query.CommandType = System.Data.CommandType.Text; query.Parameters.Add(new SQLiteParameter("@noparam", classNo)); query.Parameters.Add(new SQLiteParameter("@catparam", category)); query.Parameters.Add(new SQLiteParameter("@nameparam", name)); query.Parameters.Add(new SQLiteParameter("@feeparam", fee)); query.Connection = ClubConn; return DoTheNonQuery(query); } #endregion #region Update Statements public bool UpdateClassItem(int classNo, int category, string name, decimal fee) { // Construct and execute the query SQLiteCommand query = new SQLiteCommand(); query.CommandText = "UPDATE [" + Year + "_class] SET category_no = @catparam, class_name = @nameparam, fee = @feeparam " + "WHERE class_no = @noparam;"; query.CommandType = System.Data.CommandType.Text; query.Parameters.Add(new SQLiteParameter("@noparam", classNo)); query.Parameters.Add(new SQLiteParameter("@catparam", category)); query.Parameters.Add(new SQLiteParameter("@nameparam", name)); query.Parameters.Add(new SQLiteParameter("@feeparam", fee)); query.Connection = ClubConn; return DoTheNonQuery(query); } #endregion #region Delete Statements public bool DeleteClassItem(int classNo) { // Construct and execute the query SQLiteCommand query = new SQLiteCommand(); query.CommandText = "DELETE FROM [" + Year + "_class] WHERE class_no = @noparam;"; query.CommandType = System.Data.CommandType.Text; query.Parameters.Add(new SQLiteParameter("@noparam", classNo)); query.Connection = ClubConn; return DoTheNonQuery(query); } #endregion } }
kbrimm/TrotTrax
TrotTrax/Db Drivers/ClassDb.cs
C#
gpl-2.0
5,246
# Circuits and software The basics. Take a close look at your arduino board you will find all kinds of writing on it. What's most important is the things designating the pins on the board. Mostly numbers from 0 to 13. # Tasks ## 0. How to wire a breadboard Breadboards are super simple, which is good because you'll use it a lot. A breadboard lets you make a circuit without all the fuss of soldering things, fumbling with wrapping components together or just holding very still with everything. A circuit is a loop of conductive material, that's it. As I'm sure you know, this is usually metal. The breadboard helps you make a loop because the holes in it are a lot of rows connected up, separated by a gap in the middle and two columns either side to run electricity up and down. See all the metal strips as pictured?![metal strips under a breadboard?](breadboard_back.png). ## 1. Flash the built in LED Get the board plugged in and upload to it the example that comes with the software. `File -> Examples -> Basics -> Blink` When you upload it watch the board and note what it's doing. ## 2 Flash your own LED Get out the following; 1. Any LED 2. 1 560Ohm Resistor Using some wires from the kit put your parts into the breadboard so that the signal (power) will come from the correct pin, through the resistor, through the LED and finally down to a ground (any GND pin). # What did you learn? #### Can you answer these yourself? 1. How small can the speed be and you can still see which LED is on and which is off. 1. The same `flip` function runs for both LEDs. Why don't both LEDs light up and go off at the same time? 1. What LED lights when you first boot the board up? 1. Why? 1. Can you describe what a function is? 1. What is the syntax of a function?
BirkdaleHigh/hardware-club-starter
AltBlink/README.md
Markdown
gpl-2.0
1,777
# issue-generator Generate a volatile and temporary /run/issue file based on the input files from different locations as specified in issue.d(5). ## How does this work? The script can be run on the commandline, as systemd service or as udev rule. If invoked with no arguments, it applies all input files and creates a temporary issue file as /run/issue. /etc/issue should be symlink to this file. Input files could be located in /usr/lib/issue.d, /run/issue.d and /etc/issue.d. Files in /etc/issue.d override files with the same name in /usr/lib/issue.d and /run/issue.d. Files in /run/issue.d override files with the same name in /usr/lib/issue.d. Packages should install their configuration files in /usr/lib/issue.d. Files in /etc/issue.d are reserved for the local administrator, who may use this logic to override the files installed by vendor packages. All configuration files are sorted by their filename in lexicographic order, regardless of which of the directories they reside in. issue-generator has two additional options used by udev rules and systemd service files: network and ssh. The first one will create an issue snippet, which displays the IPv4 and IPv6 address of an ethernet interface. The second option will create an issue snippet, which displays the fingerprints of all public ssh keys of that host. To always build a /run/issue file, issue-generator.service needs to be enabled. issue-add-ssh-keys.service needs to be enabled, if the fingerprint of the public ssh keys of that machine should be shown. A udev rule will always generate or remove a snippet, if a network interface is added or removed. ## Caveats * The udev rule to add/remove the network interface should be configureable.
thkukuk/issue-generator
README.md
Markdown
gpl-2.0
1,721
/* vi: set sw=4 ts=4: */ /* * Mini DNS server implementation for busybox * * Copyright (C) 2005 Roberto A. Foglietta (me@roberto.foglietta.name) * Copyright (C) 2005 Odd Arild Olsen (oao at fibula dot no) * Copyright (C) 2003 Paul Sheer * * Licensed under GPLv2 or later, see file LICENSE in this source tree. * * Odd Arild Olsen started out with the sheerdns [1] of Paul Sheer and rewrote * it into a shape which I believe is both easier to understand and maintain. * I also reused the input buffer for output and removed services he did not * need. [1] http://threading.2038bug.com/sheerdns/ * * Some bugfix and minor changes was applied by Roberto A. Foglietta who made * the first porting of oao' scdns to busybox also. */ //usage:#define dnsd_trivial_usage //usage: "[-dvs] [-c CONFFILE] [-t TTL_SEC] [-p PORT] [-i ADDR]" //usage:#define dnsd_full_usage "\n\n" //usage: "Small static DNS server daemon\n" //usage: "\n -c FILE Config file" //usage: "\n -t SEC TTL" //usage: "\n -p PORT Listen on PORT" //usage: "\n -i ADDR Listen on ADDR" //usage: "\n -d Daemonize" //usage: "\n -v Verbose" //usage: "\n -s Send successful replies only. Use this if you want" //usage: "\n to use /etc/resolv.conf with two nameserver lines:" //usage: "\n nameserver DNSD_SERVER" //usage: "\n nameserver NORNAL_DNS_SERVER" #include "libbb.h" #include <syslog.h> //#define DEBUG 1 #define DEBUG 0 enum { /* can tweak this */ DEFAULT_TTL = 120, /* cannot get bigger packets than 512 per RFC1035. */ MAX_PACK_LEN = 512, IP_STRING_LEN = sizeof(".xxx.xxx.xxx.xxx"), MAX_NAME_LEN = IP_STRING_LEN - 1 + sizeof(".in-addr.arpa"), REQ_A = 1, REQ_PTR = 12, }; /* the message from client and first part of response msg */ struct dns_head { uint16_t id; uint16_t flags; uint16_t nquer; uint16_t nansw; uint16_t nauth; uint16_t nadd; }; /* Structure used to access type and class fields. * They are totally unaligned, but gcc 4.3.4 thinks that pointer of type uint16_t* * is 16-bit aligned and replaces 16-bit memcpy (in move_from_unaligned16 macro) * with aligned halfword access on arm920t! * Oh well. Slapping PACKED everywhere seems to help: */ struct type_and_class { uint16_t type PACKED; uint16_t class PACKED; } PACKED; /* element of known name, ip address and reversed ip address */ struct dns_entry { struct dns_entry *next; uint32_t ip; char rip[IP_STRING_LEN]; /* length decimal reversed IP */ char name[1]; }; #define OPT_verbose (option_mask32 & 1) #define OPT_silent (option_mask32 & 2) /* * Insert length of substrings instead of dots */ static void undot(char *rip) { int i = 0; int s = 0; while (rip[i]) i++; for (--i; i >= 0; i--) { if (rip[i] == '.') { rip[i] = s; s = 0; } else { s++; } } } /* * Read hostname/IP records from file */ static struct dns_entry *parse_conf_file(const char *fileconf) { char *token[2]; parser_t *parser; struct dns_entry *m, *conf_data; struct dns_entry **nextp; conf_data = NULL; nextp = &conf_data; parser = config_open(fileconf); while (config_read(parser, token, 2, 2, "# \t", PARSE_NORMAL)) { struct in_addr ip; uint32_t v32; if (inet_aton(token[1], &ip) == 0) { bb_error_msg("error at line %u, skipping", parser->lineno); continue; } if (OPT_verbose) bb_error_msg("name:%s, ip:%s", token[0], token[1]); /* sizeof(*m) includes 1 byte for m->name[0] */ m = xzalloc(sizeof(*m) + strlen(token[0]) + 1); /*m->next = NULL;*/ *nextp = m; nextp = &m->next; m->name[0] = '.'; strcpy(m->name + 1, token[0]); undot(m->name); m->ip = ip.s_addr; /* in network order */ v32 = ntohl(m->ip); /* inverted order */ sprintf(m->rip, ".%u.%u.%u.%u", (uint8_t)(v32), (uint8_t)(v32 >> 8), (uint8_t)(v32 >> 16), (v32 >> 24) ); undot(m->rip); } config_close(parser); return conf_data; } /* * Look query up in dns records and return answer if found. */ static char *table_lookup(struct dns_entry *d, uint16_t type, char* query_string) { while (d) { unsigned len = d->name[0]; /* d->name[len] is the last (non NUL) char */ #if DEBUG char *p, *q; q = query_string + 1; p = d->name + 1; fprintf(stderr, "%d/%d p:%s q:%s %d\n", (int)strlen(p), len, p, q, (int)strlen(q) ); #endif if (type == htons(REQ_A)) { /* search by host name */ if (len != 1 || d->name[1] != '*') { /* we are lax, hope no name component is ever >64 so that length * (which will be represented as 'A','B'...) matches a lowercase letter. * Actually, I think false matches are hard to construct. * Example. * [31] len is represented as '1', [65] as 'A', [65+32] as 'a'. * [65] <65 same chars>[31]<31 same chars>NUL * [65+32]<65 same chars>1 <31 same chars>NUL * This example seems to be the minimal case when false match occurs. */ if (strcasecmp(d->name, query_string) != 0) goto next; } return (char *)&d->ip; #if DEBUG fprintf(stderr, "Found IP:%x\n", (int)d->ip); #endif return 0; } /* search by IP-address */ if ((len != 1 || d->name[1] != '*') /* we assume (do not check) that query_string * ends in ".in-addr.arpa" */ && strncmp(d->rip, query_string, strlen(d->rip)) == 0 ) { #if DEBUG fprintf(stderr, "Found name:%s\n", d->name); #endif return d->name; } next: d = d->next; } return NULL; } /* * Decode message and generate answer */ /* RFC 1035 ... Whenever an octet represents a numeric quantity, the left most bit in the diagram is the high order or most significant bit. That is, the bit labeled 0 is the most significant bit. ... 4.1.1. Header section format 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ID | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ |QR| OPCODE |AA|TC|RD|RA| 0 0 0| RCODE | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | QDCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ANCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | NSCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ARCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ ID 16 bit random identifier assigned by querying peer. Used to match query/response. QR message is a query (0), or a response (1). OPCODE 0 standard query (QUERY) 1 inverse query (IQUERY) 2 server status request (STATUS) AA Authoritative Answer - this bit is valid in responses. Responding name server is an authority for the domain name in question section. Answer section may have multiple owner names because of aliases. The AA bit corresponds to the name which matches the query name, or the first owner name in the answer section. TC TrunCation - this message was truncated. RD Recursion Desired - this bit may be set in a query and is copied into the response. If RD is set, it directs the name server to pursue the query recursively. Recursive query support is optional. RA Recursion Available - this be is set or cleared in a response, and denotes whether recursive query support is available in the name server. RCODE Response code. 0 No error condition 1 Format error 2 Server failure - server was unable to process the query due to a problem with the name server. 3 Name Error - meaningful only for responses from an authoritative name server. The referenced domain name does not exist. 4 Not Implemented. 5 Refused. QDCOUNT number of entries in the question section. ANCOUNT number of records in the answer section. NSCOUNT number of records in the authority records section. ARCOUNT number of records in the additional records section. 4.1.2. Question section format The section contains QDCOUNT (usually 1) entries, each of this format: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ / QNAME / / / +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | QTYPE | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | QCLASS | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ QNAME a domain name represented as a sequence of labels, where each label consists of a length octet followed by that number of octets. The domain name terminates with the zero length octet for the null label of the root. Note that this field may be an odd number of octets; no padding is used. QTYPE a two octet type of the query. 1 a host address [REQ_A const] 2 an authoritative name server 3 a mail destination (Obsolete - use MX) 4 a mail forwarder (Obsolete - use MX) 5 the canonical name for an alias 6 marks the start of a zone of authority 7 a mailbox domain name (EXPERIMENTAL) 8 a mail group member (EXPERIMENTAL) 9 a mail rename domain name (EXPERIMENTAL) 10 a null RR (EXPERIMENTAL) 11 a well known service description 12 a domain name pointer [REQ_PTR const] 13 host information 14 mailbox or mail list information 15 mail exchange 16 text strings 0x1c IPv6? 252 a request for a transfer of an entire zone 253 a request for mailbox-related records (MB, MG or MR) 254 a request for mail agent RRs (Obsolete - see MX) 255 a request for all records QCLASS a two octet code that specifies the class of the query. 1 the Internet (others are historic only) 255 any class 4.1.3. Resource Record format The answer, authority, and additional sections all share the same format: a variable number of resource records, where the number of records is specified in the corresponding count field in the header. Each resource record has this format: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ / / / NAME / +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | TYPE | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | CLASS | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | TTL | | | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | RDLENGTH | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--| / RDATA / / / +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ NAME a domain name to which this resource record pertains. TYPE two octets containing one of the RR type codes. This field specifies the meaning of the data in the RDATA field. CLASS two octets which specify the class of the data in the RDATA field. TTL a 32 bit unsigned integer that specifies the time interval (in seconds) that the record may be cached. RDLENGTH a 16 bit integer, length in octets of the RDATA field. RDATA a variable length string of octets that describes the resource. The format of this information varies according to the TYPE and CLASS of the resource record. If the TYPE is A and the CLASS is IN, it's a 4 octet IP address. 4.1.4. Message compression In order to reduce the size of messages, domain names coan be compressed. An entire domain name or a list of labels at the end of a domain name is replaced with a pointer to a prior occurance of the same name. The pointer takes the form of a two octet sequence: +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | 1 1| OFFSET | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ The first two bits are ones. This allows a pointer to be distinguished from a label, since the label must begin with two zero bits because labels are restricted to 63 octets or less. The OFFSET field specifies an offset from the start of the message (i.e., the first octet of the ID field in the domain header). A zero offset specifies the first byte of the ID field, etc. Domain name in a message can be represented as either: - a sequence of labels ending in a zero octet - a pointer - a sequence of labels ending with a pointer */ static int process_packet(struct dns_entry *conf_data, uint32_t conf_ttl, uint8_t *buf) { struct dns_head *head; struct type_and_class *unaligned_type_class; const char *err_msg; char *query_string; char *answstr; uint8_t *answb; uint16_t outr_rlen; uint16_t outr_flags; uint16_t type; uint16_t class; int query_len; head = (struct dns_head *)buf; if (head->nquer == 0) { bb_error_msg("packet has 0 queries, ignored"); return 0; /* don't reply */ } if (head->flags & htons(0x8000)) { /* QR bit */ bb_error_msg("response packet, ignored"); return 0; /* don't reply */ } /* QR = 1 "response", RCODE = 4 "Not Implemented" */ outr_flags = htons(0x8000 | 4); err_msg = NULL; /* start of query string */ query_string = (void *)(head + 1); /* caller guarantees strlen is <= MAX_PACK_LEN */ query_len = strlen(query_string) + 1; /* may be unaligned! */ unaligned_type_class = (void *)(query_string + query_len); query_len += sizeof(*unaligned_type_class); /* where to append answer block */ answb = (void *)(unaligned_type_class + 1); /* OPCODE != 0 "standard query"? */ if ((head->flags & htons(0x7800)) != 0) { err_msg = "opcode != 0"; goto empty_packet; } move_from_unaligned16(class, &unaligned_type_class->class); if (class != htons(1)) { /* not class INET? */ err_msg = "class != 1"; goto empty_packet; } move_from_unaligned16(type, &unaligned_type_class->type); if (type != htons(REQ_A) && type != htons(REQ_PTR)) { /* we can't handle this query type */ //TODO: happens all the time with REQ_AAAA (0x1c) requests - implement those? err_msg = "type is !REQ_A and !REQ_PTR"; goto empty_packet; } /* look up the name */ answstr = table_lookup(conf_data, type, query_string); #if DEBUG /* Shows lengths instead of dots, unusable for !DEBUG */ bb_error_msg("'%s'->'%s'", query_string, answstr); #endif outr_rlen = 4; if (answstr && type == htons(REQ_PTR)) { /* returning a host name */ outr_rlen = strlen(answstr) + 1; } if (!answstr || (unsigned)(answb - buf) + query_len + 4 + 2 + outr_rlen > MAX_PACK_LEN ) { /* QR = 1 "response" * AA = 1 "Authoritative Answer" * RCODE = 3 "Name Error" */ err_msg = "name is not found"; outr_flags = htons(0x8000 | 0x0400 | 3); goto empty_packet; } /* Append answer Resource Record */ memcpy(answb, query_string, query_len); /* name, type, class */ answb += query_len; move_to_unaligned32((uint32_t *)answb, htonl(conf_ttl)); answb += 4; move_to_unaligned16((uint16_t *)answb, htons(outr_rlen)); answb += 2; memcpy(answb, answstr, outr_rlen); answb += outr_rlen; /* QR = 1 "response", * AA = 1 "Authoritative Answer", * TODO: need to set RA bit 0x80? One user says nslookup complains * "Got recursion not available from SERVER, trying next server" * "** server can't find HOSTNAME" * RCODE = 0 "success" */ if (OPT_verbose) bb_error_msg("returning positive reply"); outr_flags = htons(0x8000 | 0x0400 | 0); /* we have one answer */ head->nansw = htons(1); empty_packet: if ((outr_flags & htons(0xf)) != 0) { /* not a positive response */ if (OPT_verbose) { bb_error_msg("%s, %s", err_msg, OPT_silent ? "dropping query" : "sending error reply" ); } if (OPT_silent) return 0; } head->flags |= outr_flags; head->nauth = head->nadd = 0; head->nquer = htons(1); // why??? return answb - buf; } int dnsd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE; int dnsd_main(int argc UNUSED_PARAM, char **argv) { const char *listen_interface = "0.0.0.0"; const char *fileconf = "/etc/dnsd.conf"; struct dns_entry *conf_data; uint32_t conf_ttl = DEFAULT_TTL; char *sttl, *sport; len_and_sockaddr *lsa, *from, *to; unsigned lsa_size; int udps, opts; uint16_t port = 53; /* Ensure buf is 32bit aligned (we need 16bit, but 32bit can't hurt) */ uint8_t buf[MAX_PACK_LEN + 1] ALIGN4; opts = getopt32(argv, "vsi:c:t:p:d", &listen_interface, &fileconf, &sttl, &sport); //if (opts & (1 << 0)) // -v //if (opts & (1 << 1)) // -s //if (opts & (1 << 2)) // -i //if (opts & (1 << 3)) // -c if (opts & (1 << 4)) // -t conf_ttl = xatou_range(sttl, 1, 0xffffffff); if (opts & (1 << 5)) // -p port = xatou_range(sport, 1, 0xffff); if (opts & (1 << 6)) { // -d bb_daemonize_or_rexec(DAEMON_CLOSE_EXTRA_FDS, argv); openlog(applet_name, LOG_PID, LOG_DAEMON); logmode = LOGMODE_SYSLOG; } conf_data = parse_conf_file(fileconf); lsa = xdotted2sockaddr(listen_interface, port); udps = xsocket(lsa->u.sa.sa_family, SOCK_DGRAM, 0); xbind(udps, &lsa->u.sa, lsa->len); socket_want_pktinfo(udps); /* needed for recv_from_to to work */ lsa_size = LSA_LEN_SIZE + lsa->len; from = xzalloc(lsa_size); to = xzalloc(lsa_size); { char *p = xmalloc_sockaddr2dotted(&lsa->u.sa); bb_error_msg("accepting UDP packets on %s", p); free(p); } while (1) { int r; /* Try to get *DEST* address (to which of our addresses * this query was directed), and reply from the same address. * Or else we can exhibit usual UDP ugliness: * [ip1.multihomed.ip2] <= query to ip1 <= peer * [ip1.multihomed.ip2] => reply from ip2 => peer (confused) */ memcpy(to, lsa, lsa_size); r = recv_from_to(udps, buf, MAX_PACK_LEN + 1, 0, &from->u.sa, &to->u.sa, lsa->len); if (r < 12 || r > MAX_PACK_LEN) { bb_error_msg("packet size %d, ignored", r); continue; } if (OPT_verbose) bb_error_msg("got UDP packet"); buf[r] = '\0'; /* paranoia */ r = process_packet(conf_data, conf_ttl, buf); if (r <= 0) continue; send_to_from(udps, buf, r, 0, &from->u.sa, &to->u.sa, lsa->len); } return 0; }
marquicus/busybox-xoom
networking/dnsd.c
C
gpl-2.0
18,616
<!doctype html> <html> <head> <title>YUI: GetXY</title> <script type="text/javascript" src="../../../../build/yui/yui.js"></script> <script type="text/javascript" src="./assets/dom-xy-test.js"></script> <script type="text/javascript"> YUI({ coverage: ['dom-screen'], filter: (window.location.search.match(/[?&]filter=([^&]+)/) || [])[1] || 'raw' }).use('test-console', 'dom-xy-test', function (Y) { Y.DOM._testXY(); new Y.Test.Console().render(); Y.Test.Runner.setName('Dom: XY'); Y.Test.Runner.run(); }); </script> <style type="text/css" media="screen"> .yui3-console { position: absolute; right: 0; top: 0; } html { border: 10px solid #000; Xmargin: 20px; /* manual test: false negative */ } body { /*background-image: url( grid.png );*/ background-position: -12.5px -12.5px; Xborder: 30px solid blue; /* manual test: false negative */ height: 2000px; margin: 50px; padding: 10px; } .node { height: 50px; width: 50px; border: 3px solid black; background-color: #ccc; opacity: .5; filter: alpha(opacity=50); } span.node { height:auto; width:auto; } .nodeOver { position: relative; background-color: yellow; opacity: .5; filter: alpha(opacity=50); } .nodeOver-table { background-color: red; opacity: .1; filter: alpha(opacity=10); } .nodeOver-td, .nodeOver-th { background-color: blue; } .nodeOver-tr { background-color: green; } #abs1, #abs2, #abs3, #abs4 { position: absolute; top: 200px; left: 200px; } #rel1, #rel2, #rel3, #rel4 { position: relative; top: 100px; left: 100px; } span.rel { position: relative; top:150px; left:150px; } span.abs { position: absolute; top:250px; left:250px; } #play1, #play2, #play3, #play4 { position: relative; height: 400px; width: 400px; border: 3px solid black; float: left; margin: 10px; } #play2, #play3, #play4 { overflow: auto; } #play2 .wrap, #play3 .wrap, #play4 .wrap { height: 700px; } #play2 { top: 200px; left: 200px; } #play3, #play4 { position: static; } #runner { clear: both; } #fixed { position: fixed; top: 0px; left: 800px; } #results { border: 1px solid black; background-color: #ccc; width: 200px; } </style> </head> <body class="yui3-skin-sam"> <h1 id="h1-1">Positioning Tests</h1> <div id="static1" class="node">S1</div> <div id="abs1" class="node">A1</div> <div id="rel1" class="node">R1</div> <div id="play1"> <div id="static2" class="node">S2</div> <div id="abs2" class="node">A2</div> <div id="rel2" class="node">R2</div> </div> <div id="play2"> <div class="wrap"> <div id="static3" class="node">S3</div> <div id="abs3" class="node">A3</div> <div id="rel3" class="node">R3</div> Lorem ipsum dolor sit amet, <span id="p2-is" class="node st">P2 Static Inline</span> consectetuer adipiscing elit. Morbi sed mauris in magna tincidunt sodales. Etiam dolor. Aenean non justo. Sed nec diam sed lacus pretium luctus. Vivamus felis tortor, cursus vitae, malesuada in, pharetra vel, arcu. Aliquam erat volutpat. Suspendisse potenti. Maecenas in ipsum ac nisl congue congue. Cras a nibh. Praesent non est. Morbi non dolor. <span id="p2-ir" class="node rel">P2 Rel Inline</span> Donec ut est <span id="p2-ia" class="node abs">P2 Abs Inline</span> vitae quam hendrerit tincidunt. Cras non tellus at lectus luctus ultricies. Nullam bibendum leo quis purus. Curabitur cursus tempus elit. Donec fringilla pede in leo. Morbi dapibus vestibulum enim. Phasellus non mi vel nunc luctus lacinia. Phasellus quis urna. Pellentesque dolor risus, fermentum et, molestie tempus, cursus eget, nisl. </div> </div> <div id="play3"> <div class="wrap"> <div id="static4" class="node">S4</div> </div> </div> <div id="play4"> <div class="wrap"> <div id="static5" class="node">S5</div> <div id="abs4" class="node">A4</div> <div id="rel4" class="node">R4</div> Lorem ipsum dolor sit amet, <span id="p4-is" class="node st">P4 Static Inline</span> consectetuer adipiscing elit. Morbi sed mauris in magna tincidunt sodales. Etiam dolor. Aenean non justo. Sed nec diam sed lacus pretium luctus. Vivamus felis tortor, cursus vitae, malesuada in, pharetra vel, arcu. Aliquam erat volutpat. Suspendisse potenti. Maecenas in ipsum ac nisl congue congue. Cras a nibh. Praesent non est. Morbi non dolor. <span id="p4-ir" class="node rel">P4 Rel Inline</span> Donec ut est <span id="p4-ia" class="node abs">P4 Abs Inline</span> vitae quam hendrerit tincidunt. Cras non tellus at lectus luctus ultricies. Nullam bibendum leo quis purus. Curabitur cursus tempus elit. Donec fringilla pede in leo. Morbi dapibus vestibulum enim. Phasellus non mi vel nunc luctus lacinia. Phasellus quis urna. Pellentesque dolor risus, fermentum et, molestie tempus, cursus eget, nisl. </div> </div> <div id="fixed" class="node">Fixed</div> <table border="1" width="300" id="table1"> <caption>I am a table</caption> <thead> <tr id="tr1"> <th id="th1">1</th><th id="th2">2</th><th id="th3">3</th><th id="th4">4</th> </tr> </thead> <tbody> <tr id="tr2"> <td id="td2-1">1</td> <td id="td2-2">2</td> <td id="td2-3">3</td> <td id="td2-4">4</td> </tr> <tr id="tr3"> <td id="td3-1">1</td> <td id="td3-2">2</td> <td id="td3-3">3</td> <td id="td3-4">4</td> </tr> <tr id="tr4"> <td id="td4-1">1</td> <td id="td4-2">2</td> <td id="td4-3">3</td> <td id="td4-4">4</td> </tr> </tbody> </table> </body> </html>
artefactual-labs/trac
sites/all/libraries/yui/tests/dom/tests/unit/dom-xy.html
HTML
gpl-2.0
6,465
""" .. module:: editor_subscribe_label_deleted The **Editor Subscribe Label Deleted** Model. PostgreSQL Definition --------------------- The :code:`editor_subscribe_label_deleted` table is defined in the MusicBrainz Server as: .. code-block:: sql CREATE TABLE editor_subscribe_label_deleted ( editor INTEGER NOT NULL, -- PK, references editor.id gid UUID NOT NULL, -- PK, references deleted_entity.gid deleted_by INTEGER NOT NULL -- references edit.id ); """ from django.db import models from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class editor_subscribe_label_deleted(models.Model): """ Not all parameters are listed here, only those that present some interest in their Django implementation. :param editor: references :class:`.editor` :param gid: references :class:`.deleted_entity` :param deleted_by: references :class:`.edit` """ editor = models.OneToOneField('editor', primary_key=True) gid = models.OneToOneField('deleted_entity') deleted_by = models.ForeignKey('edit') def __str__(self): return 'Editor Subscribe Label Deleted' class Meta: db_table = 'editor_subscribe_label_deleted'
marios-zindilis/musicbrainz-django-models
musicbrainz_django_models/models/editor_subscribe_label_deleted.py
Python
gpl-2.0
1,251
showWord(["n. "," Transpòtasyon ki vole tankou avyon. Li gen yon gwo elis sou tèt li. Yo sèvi avè l souvan nan ijans paske li ka poze nenpòt ki kote san aywepò. Mwen pa janm renmen moute elikoptè paske li vole twò ba, li ban mwen tèt vire." ])
georgejhunt/HaitiDictionary.activity
data/words/elikopt~e.js
JavaScript
gpl-2.0
252
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace KerbalRogueAI { class ConditionBody : AICondition { public ConditionBody(AICore aicore) : base(aicore) { } public string BodyName=null; public override bool _condition() { CelestialBody body = aicore.GetBody(BodyName); return body != null; } } }
johnfink8/KerbalRogueAI
KerbalRogueAI/KerbalRogueAI/Conditions/ConditionBody.cs
C#
gpl-2.0
471
cmd_drivers/net/ethernet/dec/built-in.o := rm -f drivers/net/ethernet/dec/built-in.o; /home/livlogik/android/ndk/android-ndk-r10e/toolchains/aarch64-linux-android-4.9/prebuilt/linux-x86_64/bin/aarch64-linux-android-ar rcsD drivers/net/ethernet/dec/built-in.o
livlogik/Evil_Yummy_Gumdrop--Tmo-V10-Kernel
drivers/net/ethernet/dec/.built-in.o.cmd
Batchfile
gpl-2.0
260
<?php /** * * @package Axiom * @author averta * @copyright Copyright (c) averta co * @version Release: 1.0 * @link http://www.averta.net */ /*---------------------------------------------- * Recent Posts widget * --------------------------------------------*/ class AxiTestimonialWidget extends Axiom_Widget { public $fields = array( array( 'name' => 'Title', 'id' => 'title', 'type' => 'textbox', 'value' => '' ),/* array( 'name' => 'Display Items From', 'id' => 'id_type', 'type' => 'select', 'value' => 'specific', 'options' => array( "specific" => "Spesific Testimonial" , "category" => "Category") ),*/ array( 'name' => 'Select Item', 'id' => 'single_id', 'type' => 'select', 'value' => 'none', 'options' => array( "none" => "Select ...", "563" => "c1" , "1084" => "c2", "1085" => "c3") ),/* array( 'name' => 'Select Category', 'id' => 'cat_id', 'type' => 'select', 'value' => 'none', 'options' => array( "none" => "Select ...", "104" => "web" ) )*/ ); /** constructor */ function __construct() { $this->assign_single_ids(); parent::__construct(); parent::WP_Widget( "testimonial" , $name = '[axiom] Testimonial' /* Name */ , array( 'description' => 'Display Testimonial' ) ); } function assign_single_ids(){ //-- get all single ids ---------------------------- $args = array( 'post_type' => 'testimonial', 'orderby' => "date", 'post_status' => 'publish', 'posts_per_page' => -1 ); $ops = array("none" => "Select ..."); $th_query = null; $th_query = new WP_Query($args); if( $th_query->have_posts() ): while ($th_query->have_posts()) : $th_query->the_post(); $ops[$th_query->post->ID] = get_the_title(); endwhile; endif; wp_reset_query(); unset($args); //-- clone fields and assign single ids -------------- $clone_fields = array(); foreach ($this->fields as $value) { if($value["id"] == "single_id") $value["options"] = $ops; $clone_fields[] = $value; } $this->fields = $clone_fields; } // outputs the content of the widget function widget( $args, $instance ) { extract( $args ); $title = apply_filters( 'widget_title', $instance['title'] ); $id_type = isset($instance["id_type"])?$instance["id_type"]:""; $cat_id = isset($instance["cat_id"])?$instance["cat_id"]:""; if(!isset($instance["single_id"])) return "Please specify the testimonial item "; $single_id = $instance["single_id"]; // Fetch specific id or category? if type is not set, but one of ids is set, then specify id_type if(empty($id_type)) { if(!empty($single_id) && empty($cat_id)){ $id_type = 'specific'; }else if(empty($single_id) && !empty($cat_id)){ $id_type = 'category'; }else{ return; } } // if specific testimonial is requested --------------------------- if($id_type == 'category'){ $items = ''; // for storing all testimonial_item shortcodes $tax_args = array('taxonomy' => 'testimonial-category', 'terms' => $cat_id ); if(empty($cat_id) || $cat_id == "all" ) $tax_args = ""; // create wp_query to get latest items $args = array( 'post_type' => 'testimonial', 'post_status' => 'publish', 'posts_per_page'=> -1, 'orderby' => 'date', 'tax_query' => array($tax_args) ); // if a testimonial category is requested } else{ $args = array( 'page_id' => $single_id, 'post_type' => 'testimonial' ); } echo $before_widget; if ( !empty( $title ) ) { echo $before_title . $title . $after_title; } echo '<div class="widget-inner">'; // ----------------------------------------------------------------- $th_query = null; $th_query = new WP_Query($args); $items = ""; if( $th_query->have_posts() ): while ($th_query->have_posts()) : $th_query->the_post(); $cjob = get_post_meta($th_query->post->ID, 'customer_job', true); $curl = get_post_meta($th_query->post->ID, 'customer_url' , true); $avatar = axiom_get_the_post_thumbnail_src($th_query->post->ID, 100, 100, true, 75); // if cat_id is set , use testimonial_slider shortcode if($id_type == 'category'){ $attr = ' author="'.get_the_title().'" avatar="'.$avatar.'" role="'.$cjob.'" link="'.$curl.'" type="blockquote" '; $items .= '[testimonial_item '.$attr.' ]'.get_the_excerpt().'[/testimonial_item]'; // if single id is set , use testimonial shortcode } else{ $items = ""; $attr = ' author="'.get_the_title().'" avatar="'.$avatar.'" role="'.$cjob.'" link="'.$curl.'" type="blockquote" '; $items .= '[testimonial_item '.$attr.' ]'.get_the_excerpt().'[/testimonial_item]'; echo do_shortcode($items); } endwhile; endif; wp_reset_query(); unset($cjob, $curl, $avatar, $attr); if($id_type == 'category'){ $slider_attr = ' size="'.$size.'" title="'.$title.'" type="blockquote" '; echo do_shortcode('[testimonial_slider '.$slider_attr.' ]'.$items.'[/testimonial_slider]'); } echo '</div>', $after_widget; } } // end widget class // register Widget add_action( 'widgets_init', create_function( '', 'register_widget("AxiTestimonialWidget");' ) ); ?>
Batname/lifehouse.com.ua
wp-content/themes/lotus/admin/include/sidebars/widgets/testimonials.php
PHP
gpl-2.0
7,339
# encoding: UTF-8 # This file is auto-generated from the current state of the database. Instead # of editing this file, please use the migrations feature of Active Record to # incrementally modify your database, and then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your # database schema. If you need to create the application database on another # system, you should be using db:schema:load, not running all the migrations # from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended that you check this file into your version control system. ActiveRecord::Schema.define(version: 20151011071338) do # These are extensions that must be enabled in order to support this database enable_extension "plpgsql" create_table "programs", force: :cascade do |t| t.string "name" t.text "purpose" t.string "contact" t.string "phone" t.string "cost" t.string "location" t.datetime "created_at", null: false t.datetime "updated_at", null: false end create_table "schools", force: :cascade do |t| t.string "name" t.string "address" t.string "phone" t.string "principal" t.text "description" t.datetime "created_at", null: false t.datetime "updated_at", null: false end end
tenji240/Reach-Higher-Challenge
db/schema.rb
Ruby
gpl-2.0
1,460
<?php /** * This is a Backbone.js template */ ?> <# var thumbnail = data.sizes.thumbnail || data.sizes.medium || data.sizes.large || data.sizes.full || { url: data.url } #> <div class="thumbnail" data-id="{{ data.id }}"> <a href="#" class="delete-button"></a> <img src="{{ thumbnail.url }}" alt="{{ data.alt }}" /> </div>
alessiomaffeis/SanePress
wp-content/plugins/rocket-galleries/backbone/gallery-thumbnail.php
PHP
gpl-2.0
330
/*****************************************************************************/ /* * devio.c -- User space communication with USB devices. * * Copyright (C) 1999-2000 Thomas Sailer (sailer@ife.ee.ethz.ch) * * 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., 675 Mass Ave, Cambridge, MA 02139, USA. * * This file implements the usbfs/x/y files, where * x is the bus number and y the device number. * * It allows user space programs/"drivers" to communicate directly * with USB devices without intervening kernel driver. * * Revision history * 22.12.1999 0.1 Initial release (split from proc_usb.c) * 04.01.2000 0.2 Turned into its own filesystem * 30.09.2005 0.3 Fix user-triggerable oops in async URB delivery * (CAN-2005-3055) */ /*****************************************************************************/ #include <linux/fs.h> #include <linux/mm.h> #include <linux/slab.h> #include <linux/smp_lock.h> #include <linux/signal.h> #include <linux/poll.h> #include <linux/module.h> #include <linux/usb.h> #include <linux/usbdevice_fs.h> #include <linux/cdev.h> #include <linux/notifier.h> #include <linux/security.h> #include <asm/uaccess.h> #include <asm/byteorder.h> #include <linux/moduleparam.h> #include <linux/usb/hcd.h> /* for usbcore internals */ #include "usb.h" #define USB_MAXBUS 64 #define USB_DEVICE_MAX USB_MAXBUS * 128 /* Mutual exclusion for removal, open, and release */ DEFINE_MUTEX(usbfs_mutex); struct dev_state { struct list_head list; /* state list */ struct usb_device *dev; struct file *file; spinlock_t lock; /* protects the async urb lists */ struct list_head async_pending; struct list_head async_completed; wait_queue_head_t wait; /* wake up if a request completed */ unsigned int discsignr; struct pid *disc_pid; uid_t disc_uid, disc_euid; void __user *disccontext; unsigned long ifclaimed; u32 secid; u32 disabled_bulk_eps; }; struct async { struct list_head asynclist; struct dev_state *ps; struct pid *pid; uid_t uid, euid; unsigned int signr; unsigned int ifnum; void __user *userbuffer; void __user *userurb; struct urb *urb; int status; u32 secid; u8 bulk_addr; u8 bulk_status; }; static int usbfs_snoop; module_param(usbfs_snoop, bool, S_IRUGO | S_IWUSR); MODULE_PARM_DESC(usbfs_snoop, "true to log all usbfs traffic"); #define snoop(dev, format, arg...) \ do { \ if (usbfs_snoop) \ dev_info(dev , format , ## arg); \ } while (0) enum snoop_when { SUBMIT, COMPLETE }; #define USB_DEVICE_DEV MKDEV(USB_DEVICE_MAJOR, 0) #define MAX_USBFS_BUFFER_SIZE 16384 static int connected(struct dev_state *ps) { return (!list_empty(&ps->list) && ps->dev->state != USB_STATE_NOTATTACHED); } static loff_t usbdev_lseek(struct file *file, loff_t offset, int orig) { loff_t ret; mutex_lock(&file->f_dentry->d_inode->i_mutex); switch (orig) { case 0: file->f_pos = offset; ret = file->f_pos; break; case 1: file->f_pos += offset; ret = file->f_pos; break; case 2: default: ret = -EINVAL; } mutex_unlock(&file->f_dentry->d_inode->i_mutex); return ret; } static ssize_t usbdev_read(struct file *file, char __user *buf, size_t nbytes, loff_t *ppos) { struct dev_state *ps = file->private_data; struct usb_device *dev = ps->dev; ssize_t ret = 0; unsigned len; loff_t pos; int i; pos = *ppos; usb_lock_device(dev); if (!connected(ps)) { ret = -ENODEV; goto err; } else if (pos < 0) { ret = -EINVAL; goto err; } if (pos < sizeof(struct usb_device_descriptor)) { /* 18 bytes - fits on the stack */ struct usb_device_descriptor temp_desc; memcpy(&temp_desc, &dev->descriptor, sizeof(dev->descriptor)); le16_to_cpus(&temp_desc.bcdUSB); le16_to_cpus(&temp_desc.idVendor); le16_to_cpus(&temp_desc.idProduct); le16_to_cpus(&temp_desc.bcdDevice); len = sizeof(struct usb_device_descriptor) - pos; if (len > nbytes) len = nbytes; if (copy_to_user(buf, ((char *)&temp_desc) + pos, len)) { ret = -EFAULT; goto err; } *ppos += len; buf += len; nbytes -= len; ret += len; } pos = sizeof(struct usb_device_descriptor); for (i = 0; nbytes && i < dev->descriptor.bNumConfigurations; i++) { struct usb_config_descriptor *config = (struct usb_config_descriptor *)dev->rawdescriptors[i]; unsigned int length = le16_to_cpu(config->wTotalLength); if (*ppos < pos + length) { /* The descriptor may claim to be longer than it * really is. Here is the actual allocated length. */ unsigned alloclen = le16_to_cpu(dev->config[i].desc.wTotalLength); len = length - (*ppos - pos); if (len > nbytes) len = nbytes; /* Simply don't write (skip over) unallocated parts */ if (alloclen > (*ppos - pos)) { alloclen -= (*ppos - pos); if (copy_to_user(buf, dev->rawdescriptors[i] + (*ppos - pos), min(len, alloclen))) { ret = -EFAULT; goto err; } } *ppos += len; buf += len; nbytes -= len; ret += len; } pos += length; } err: usb_unlock_device(dev); return ret; } /* * async list handling */ static struct async *alloc_async(unsigned int numisoframes) { struct async *as; as = kzalloc(sizeof(struct async), GFP_KERNEL); if (!as) return NULL; as->urb = usb_alloc_urb(numisoframes, GFP_KERNEL); if (!as->urb) { kfree(as); return NULL; } return as; } static void free_async(struct async *as) { put_pid(as->pid); kfree(as->urb->transfer_buffer); kfree(as->urb->setup_packet); usb_free_urb(as->urb); kfree(as); } static void async_newpending(struct async *as) { struct dev_state *ps = as->ps; unsigned long flags; spin_lock_irqsave(&ps->lock, flags); list_add_tail(&as->asynclist, &ps->async_pending); spin_unlock_irqrestore(&ps->lock, flags); } static void async_removepending(struct async *as) { struct dev_state *ps = as->ps; unsigned long flags; spin_lock_irqsave(&ps->lock, flags); list_del_init(&as->asynclist); spin_unlock_irqrestore(&ps->lock, flags); } static struct async *async_getcompleted(struct dev_state *ps) { unsigned long flags; struct async *as = NULL; spin_lock_irqsave(&ps->lock, flags); if (!list_empty(&ps->async_completed)) { as = list_entry(ps->async_completed.next, struct async, asynclist); list_del_init(&as->asynclist); } spin_unlock_irqrestore(&ps->lock, flags); return as; } static struct async *async_getpending(struct dev_state *ps, void __user *userurb) { unsigned long flags; struct async *as; spin_lock_irqsave(&ps->lock, flags); list_for_each_entry(as, &ps->async_pending, asynclist) if (as->userurb == userurb) { list_del_init(&as->asynclist); spin_unlock_irqrestore(&ps->lock, flags); return as; } spin_unlock_irqrestore(&ps->lock, flags); return NULL; } static void snoop_urb(struct usb_device *udev, void __user *userurb, int pipe, unsigned length, int timeout_or_status, enum snoop_when when, unsigned char *data, unsigned data_len) { static const char *types[] = {"isoc", "int", "ctrl", "bulk"}; static const char *dirs[] = {"out", "in"}; int ep; const char *t, *d; if (!usbfs_snoop) return; ep = usb_pipeendpoint(pipe); t = types[usb_pipetype(pipe)]; d = dirs[!!usb_pipein(pipe)]; if (userurb) { /* Async */ if (when == SUBMIT) dev_info(&udev->dev, "userurb %p, ep%d %s-%s, " "length %u\n", userurb, ep, t, d, length); else dev_info(&udev->dev, "userurb %p, ep%d %s-%s, " "actual_length %u status %d\n", userurb, ep, t, d, length, timeout_or_status); } else { if (when == SUBMIT) dev_info(&udev->dev, "ep%d %s-%s, length %u, " "timeout %d\n", ep, t, d, length, timeout_or_status); else dev_info(&udev->dev, "ep%d %s-%s, actual_length %u, " "status %d\n", ep, t, d, length, timeout_or_status); } if (data && data_len > 0) { print_hex_dump(KERN_DEBUG, "data: ", DUMP_PREFIX_NONE, 32, 1, data, data_len, 1); } } #define AS_CONTINUATION 1 #define AS_UNLINK 2 static void cancel_bulk_urbs(struct dev_state *ps, unsigned bulk_addr) __releases(ps->lock) __acquires(ps->lock) { struct async *as; /* Mark all the pending URBs that match bulk_addr, up to but not * including the first one without AS_CONTINUATION. If such an * URB is encountered then a new transfer has already started so * the endpoint doesn't need to be disabled; otherwise it does. */ list_for_each_entry(as, &ps->async_pending, asynclist) { if (as->bulk_addr == bulk_addr) { if (as->bulk_status != AS_CONTINUATION) goto rescan; as->bulk_status = AS_UNLINK; as->bulk_addr = 0; } } ps->disabled_bulk_eps |= (1 << bulk_addr); /* Now carefully unlink all the marked pending URBs */ rescan: list_for_each_entry(as, &ps->async_pending, asynclist) { if (as->bulk_status == AS_UNLINK) { as->bulk_status = 0; /* Only once */ spin_unlock(&ps->lock); /* Allow completions */ usb_unlink_urb(as->urb); spin_lock(&ps->lock); goto rescan; } } } static void async_completed(struct urb *urb) { struct async *as = urb->context; struct dev_state *ps = as->ps; struct siginfo sinfo; struct pid *pid = NULL; uid_t uid = 0; uid_t euid = 0; u32 secid = 0; int signr; spin_lock(&ps->lock); list_move_tail(&as->asynclist, &ps->async_completed); as->status = urb->status; signr = as->signr; if (signr) { sinfo.si_signo = as->signr; sinfo.si_errno = as->status; sinfo.si_code = SI_ASYNCIO; sinfo.si_addr = as->userurb; pid = as->pid; uid = as->uid; euid = as->euid; secid = as->secid; } snoop(&urb->dev->dev, "urb complete\n"); snoop_urb(urb->dev, as->userurb, urb->pipe, urb->actual_length, as->status, COMPLETE, ((urb->transfer_flags & URB_DIR_MASK) == USB_DIR_OUT) ? NULL : urb->transfer_buffer, urb->actual_length); if (as->status < 0 && as->bulk_addr && as->status != -ECONNRESET && as->status != -ENOENT) cancel_bulk_urbs(ps, as->bulk_addr); spin_unlock(&ps->lock); if (signr) kill_pid_info_as_uid(sinfo.si_signo, &sinfo, pid, uid, euid, secid); wake_up(&ps->wait); } static void destroy_async(struct dev_state *ps, struct list_head *list) { struct async *as; unsigned long flags; spin_lock_irqsave(&ps->lock, flags); while (!list_empty(list)) { as = list_entry(list->next, struct async, asynclist); list_del_init(&as->asynclist); /* drop the spinlock so the completion handler can run */ spin_unlock_irqrestore(&ps->lock, flags); usb_kill_urb(as->urb); spin_lock_irqsave(&ps->lock, flags); } spin_unlock_irqrestore(&ps->lock, flags); } static void destroy_async_on_interface(struct dev_state *ps, unsigned int ifnum) { struct list_head *p, *q, hitlist; unsigned long flags; INIT_LIST_HEAD(&hitlist); spin_lock_irqsave(&ps->lock, flags); list_for_each_safe(p, q, &ps->async_pending) if (ifnum == list_entry(p, struct async, asynclist)->ifnum) list_move_tail(p, &hitlist); spin_unlock_irqrestore(&ps->lock, flags); destroy_async(ps, &hitlist); } static void destroy_all_async(struct dev_state *ps) { destroy_async(ps, &ps->async_pending); } /* * interface claims are made only at the request of user level code, * which can also release them (explicitly or by closing files). * they're also undone when devices disconnect. */ static int driver_probe(struct usb_interface *intf, const struct usb_device_id *id) { return -ENODEV; } static void driver_disconnect(struct usb_interface *intf) { struct dev_state *ps = usb_get_intfdata(intf); unsigned int ifnum = intf->altsetting->desc.bInterfaceNumber; if (!ps) return; /* NOTE: this relies on usbcore having canceled and completed * all pending I/O requests; 2.6 does that. */ if (likely(ifnum < 8*sizeof(ps->ifclaimed))) clear_bit(ifnum, &ps->ifclaimed); else dev_warn(&intf->dev, "interface number %u out of range\n", ifnum); usb_set_intfdata(intf, NULL); /* force async requests to complete */ destroy_async_on_interface(ps, ifnum); } /* The following routines are merely placeholders. There is no way * to inform a user task about suspend or resumes. */ static int driver_suspend(struct usb_interface *intf, pm_message_t msg) { return 0; } static int driver_resume(struct usb_interface *intf) { return 0; } struct usb_driver usbfs_driver = { .name = "usbfs", .probe = driver_probe, .disconnect = driver_disconnect, .suspend = driver_suspend, .resume = driver_resume, }; static int claimintf(struct dev_state *ps, unsigned int ifnum) { struct usb_device *dev = ps->dev; struct usb_interface *intf; int err; if (ifnum >= 8*sizeof(ps->ifclaimed)) return -EINVAL; /* already claimed */ if (test_bit(ifnum, &ps->ifclaimed)) return 0; intf = usb_ifnum_to_if(dev, ifnum); if (!intf) err = -ENOENT; else err = usb_driver_claim_interface(&usbfs_driver, intf, ps); if (err == 0) set_bit(ifnum, &ps->ifclaimed); return err; } static int releaseintf(struct dev_state *ps, unsigned int ifnum) { struct usb_device *dev; struct usb_interface *intf; int err; err = -EINVAL; if (ifnum >= 8*sizeof(ps->ifclaimed)) return err; dev = ps->dev; intf = usb_ifnum_to_if(dev, ifnum); if (!intf) err = -ENOENT; else if (test_and_clear_bit(ifnum, &ps->ifclaimed)) { usb_driver_release_interface(&usbfs_driver, intf); err = 0; } return err; } static int checkintf(struct dev_state *ps, unsigned int ifnum) { if (ps->dev->state != USB_STATE_CONFIGURED) return -EHOSTUNREACH; if (ifnum >= 8*sizeof(ps->ifclaimed)) return -EINVAL; if (test_bit(ifnum, &ps->ifclaimed)) return 0; /* if not yet claimed, claim it for the driver */ dev_warn(&ps->dev->dev, "usbfs: process %d (%s) did not claim " "interface %u before use\n", task_pid_nr(current), current->comm, ifnum); return claimintf(ps, ifnum); } static int findintfep(struct usb_device *dev, unsigned int ep) { unsigned int i, j, e; struct usb_interface *intf; struct usb_host_interface *alts; struct usb_endpoint_descriptor *endpt; if (ep & ~(USB_DIR_IN|0xf)) return -EINVAL; if (!dev->actconfig) return -ESRCH; for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) { intf = dev->actconfig->interface[i]; for (j = 0; j < intf->num_altsetting; j++) { alts = &intf->altsetting[j]; for (e = 0; e < alts->desc.bNumEndpoints; e++) { endpt = &alts->endpoint[e].desc; if (endpt->bEndpointAddress == ep) return alts->desc.bInterfaceNumber; } } } return -ENOENT; } static int check_ctrlrecip(struct dev_state *ps, unsigned int requesttype, unsigned int index) { int ret = 0; if (ps->dev->state != USB_STATE_UNAUTHENTICATED && ps->dev->state != USB_STATE_ADDRESS && ps->dev->state != USB_STATE_CONFIGURED) return -EHOSTUNREACH; if (USB_TYPE_VENDOR == (USB_TYPE_MASK & requesttype)) return 0; index &= 0xff; switch (requesttype & USB_RECIP_MASK) { case USB_RECIP_ENDPOINT: ret = findintfep(ps->dev, index); if (ret >= 0) ret = checkintf(ps, ret); break; case USB_RECIP_INTERFACE: ret = checkintf(ps, index); break; } return ret; } static int match_devt(struct device *dev, void *data) { return dev->devt == (dev_t) (unsigned long) data; } static struct usb_device *usbdev_lookup_by_devt(dev_t devt) { struct device *dev; dev = bus_find_device(&usb_bus_type, NULL, (void *) (unsigned long) devt, match_devt); if (!dev) return NULL; return container_of(dev, struct usb_device, dev); } /* * file operations */ static int usbdev_open(struct inode *inode, struct file *file) { struct usb_device *dev = NULL; struct dev_state *ps; const struct cred *cred = current_cred(); int ret; ret = -ENOMEM; ps = kmalloc(sizeof(struct dev_state), GFP_KERNEL); if (!ps) goto out_free_ps; ret = -ENODEV; /* Protect against simultaneous removal or release */ mutex_lock(&usbfs_mutex); /* usbdev device-node */ if (imajor(inode) == USB_DEVICE_MAJOR) dev = usbdev_lookup_by_devt(inode->i_rdev); #ifdef CONFIG_USB_DEVICEFS /* procfs file */ if (!dev) { dev = inode->i_private; if (dev && dev->usbfs_dentry && dev->usbfs_dentry->d_inode == inode) usb_get_dev(dev); else dev = NULL; } #endif mutex_unlock(&usbfs_mutex); if (!dev) goto out_free_ps; usb_lock_device(dev); if (dev->state == USB_STATE_NOTATTACHED) goto out_unlock_device; ret = usb_autoresume_device(dev); if (ret) goto out_unlock_device; ps->dev = dev; ps->file = file; spin_lock_init(&ps->lock); INIT_LIST_HEAD(&ps->list); INIT_LIST_HEAD(&ps->async_pending); INIT_LIST_HEAD(&ps->async_completed); init_waitqueue_head(&ps->wait); ps->discsignr = 0; ps->disc_pid = get_pid(task_pid(current)); ps->disc_uid = cred->uid; ps->disc_euid = cred->euid; ps->disccontext = NULL; ps->ifclaimed = 0; security_task_getsecid(current, &ps->secid); smp_wmb(); list_add_tail(&ps->list, &dev->filelist); file->private_data = ps; usb_unlock_device(dev); snoop(&dev->dev, "opened by process %d: %s\n", task_pid_nr(current), current->comm); return ret; out_unlock_device: usb_unlock_device(dev); usb_put_dev(dev); out_free_ps: kfree(ps); return ret; } static int usbdev_release(struct inode *inode, struct file *file) { struct dev_state *ps = file->private_data; struct usb_device *dev = ps->dev; unsigned int ifnum; struct async *as; usb_lock_device(dev); usb_hub_release_all_ports(dev, ps); list_del_init(&ps->list); for (ifnum = 0; ps->ifclaimed && ifnum < 8*sizeof(ps->ifclaimed); ifnum++) { if (test_bit(ifnum, &ps->ifclaimed)) releaseintf(ps, ifnum); } destroy_all_async(ps); usb_autosuspend_device(dev); usb_unlock_device(dev); usb_put_dev(dev); put_pid(ps->disc_pid); as = async_getcompleted(ps); while (as) { free_async(as); as = async_getcompleted(ps); } kfree(ps); return 0; } static int proc_control(struct dev_state *ps, void __user *arg) { struct usb_device *dev = ps->dev; struct usbdevfs_ctrltransfer ctrl; unsigned int tmo; unsigned char *tbuf; unsigned wLength; int i, pipe, ret; if (copy_from_user(&ctrl, arg, sizeof(ctrl))) return -EFAULT; ret = check_ctrlrecip(ps, ctrl.bRequestType, ctrl.wIndex); if (ret) return ret; wLength = ctrl.wLength; /* To suppress 64k PAGE_SIZE warning */ if (wLength > PAGE_SIZE) return -EINVAL; tbuf = (unsigned char *)__get_free_page(GFP_KERNEL); if (!tbuf) return -ENOMEM; tmo = ctrl.timeout; snoop(&dev->dev, "control urb: bRequestType=%02x " "bRequest=%02x wValue=%04x " "wIndex=%04x wLength=%04x\n", ctrl.bRequestType, ctrl.bRequest, __le16_to_cpup(&ctrl.wValue), __le16_to_cpup(&ctrl.wIndex), __le16_to_cpup(&ctrl.wLength)); if (ctrl.bRequestType & 0x80) { if (ctrl.wLength && !access_ok(VERIFY_WRITE, ctrl.data, ctrl.wLength)) { free_page((unsigned long)tbuf); return -EINVAL; } pipe = usb_rcvctrlpipe(dev, 0); snoop_urb(dev, NULL, pipe, ctrl.wLength, tmo, SUBMIT, NULL, 0); usb_unlock_device(dev); i = usb_control_msg(dev, pipe, ctrl.bRequest, ctrl.bRequestType, ctrl.wValue, ctrl.wIndex, tbuf, ctrl.wLength, tmo); usb_lock_device(dev); snoop_urb(dev, NULL, pipe, max(i, 0), min(i, 0), COMPLETE, tbuf, i); if ((i > 0) && ctrl.wLength) { if (copy_to_user(ctrl.data, tbuf, i)) { free_page((unsigned long)tbuf); return -EFAULT; } } } else { if (ctrl.wLength) { if (copy_from_user(tbuf, ctrl.data, ctrl.wLength)) { free_page((unsigned long)tbuf); return -EFAULT; } } pipe = usb_sndctrlpipe(dev, 0); snoop_urb(dev, NULL, pipe, ctrl.wLength, tmo, SUBMIT, tbuf, ctrl.wLength); usb_unlock_device(dev); i = usb_control_msg(dev, usb_sndctrlpipe(dev, 0), ctrl.bRequest, ctrl.bRequestType, ctrl.wValue, ctrl.wIndex, tbuf, ctrl.wLength, tmo); usb_lock_device(dev); snoop_urb(dev, NULL, pipe, max(i, 0), min(i, 0), COMPLETE, NULL, 0); } free_page((unsigned long)tbuf); if (i < 0 && i != -EPIPE) { dev_printk(KERN_DEBUG, &dev->dev, "usbfs: USBDEVFS_CONTROL " "failed cmd %s rqt %u rq %u len %u ret %d\n", current->comm, ctrl.bRequestType, ctrl.bRequest, ctrl.wLength, i); } return i; } static int proc_bulk(struct dev_state *ps, void __user *arg) { struct usb_device *dev = ps->dev; struct usbdevfs_bulktransfer bulk; unsigned int tmo, len1, pipe; int len2; unsigned char *tbuf; int i, ret; if (copy_from_user(&bulk, arg, sizeof(bulk))) return -EFAULT; ret = findintfep(ps->dev, bulk.ep); if (ret < 0) return ret; ret = checkintf(ps, ret); if (ret) return ret; if (bulk.ep & USB_DIR_IN) pipe = usb_rcvbulkpipe(dev, bulk.ep & 0x7f); else pipe = usb_sndbulkpipe(dev, bulk.ep & 0x7f); if (!usb_maxpacket(dev, pipe, !(bulk.ep & USB_DIR_IN))) return -EINVAL; len1 = bulk.len; if (len1 > MAX_USBFS_BUFFER_SIZE) return -EINVAL; if (!(tbuf = kmalloc(len1, GFP_KERNEL))) return -ENOMEM; tmo = bulk.timeout; if (bulk.ep & 0x80) { if (len1 && !access_ok(VERIFY_WRITE, bulk.data, len1)) { kfree(tbuf); return -EINVAL; } snoop_urb(dev, NULL, pipe, len1, tmo, SUBMIT, NULL, 0); usb_unlock_device(dev); i = usb_bulk_msg(dev, pipe, tbuf, len1, &len2, tmo); usb_lock_device(dev); snoop_urb(dev, NULL, pipe, len2, i, COMPLETE, tbuf, len2); if (!i && len2) { if (copy_to_user(bulk.data, tbuf, len2)) { kfree(tbuf); return -EFAULT; } } } else { if (len1) { if (copy_from_user(tbuf, bulk.data, len1)) { kfree(tbuf); return -EFAULT; } } snoop_urb(dev, NULL, pipe, len1, tmo, SUBMIT, tbuf, len1); usb_unlock_device(dev); i = usb_bulk_msg(dev, pipe, tbuf, len1, &len2, tmo); usb_lock_device(dev); snoop_urb(dev, NULL, pipe, len2, i, COMPLETE, NULL, 0); } kfree(tbuf); if (i < 0) return i; return len2; } static int proc_resetep(struct dev_state *ps, void __user *arg) { unsigned int ep; int ret; if (get_user(ep, (unsigned int __user *)arg)) return -EFAULT; ret = findintfep(ps->dev, ep); if (ret < 0) return ret; ret = checkintf(ps, ret); if (ret) return ret; usb_reset_endpoint(ps->dev, ep); return 0; } static int proc_clearhalt(struct dev_state *ps, void __user *arg) { unsigned int ep; int pipe; int ret; if (get_user(ep, (unsigned int __user *)arg)) return -EFAULT; ret = findintfep(ps->dev, ep); if (ret < 0) return ret; ret = checkintf(ps, ret); if (ret) return ret; if (ep & USB_DIR_IN) pipe = usb_rcvbulkpipe(ps->dev, ep & 0x7f); else pipe = usb_sndbulkpipe(ps->dev, ep & 0x7f); return usb_clear_halt(ps->dev, pipe); } static int proc_getdriver(struct dev_state *ps, void __user *arg) { struct usbdevfs_getdriver gd; struct usb_interface *intf; int ret; if (copy_from_user(&gd, arg, sizeof(gd))) return -EFAULT; intf = usb_ifnum_to_if(ps->dev, gd.interface); if (!intf || !intf->dev.driver) ret = -ENODATA; else { strncpy(gd.driver, intf->dev.driver->name, sizeof(gd.driver)); ret = (copy_to_user(arg, &gd, sizeof(gd)) ? -EFAULT : 0); } return ret; } static int proc_connectinfo(struct dev_state *ps, void __user *arg) { struct usbdevfs_connectinfo ci = { .devnum = ps->dev->devnum, .slow = ps->dev->speed == USB_SPEED_LOW }; if (copy_to_user(arg, &ci, sizeof(ci))) return -EFAULT; return 0; } static int proc_resetdevice(struct dev_state *ps) { return usb_reset_device(ps->dev); } static int proc_setintf(struct dev_state *ps, void __user *arg) { struct usbdevfs_setinterface setintf; int ret; if (copy_from_user(&setintf, arg, sizeof(setintf))) return -EFAULT; if ((ret = checkintf(ps, setintf.interface))) return ret; return usb_set_interface(ps->dev, setintf.interface, setintf.altsetting); } static int proc_setconfig(struct dev_state *ps, void __user *arg) { int u; int status = 0; struct usb_host_config *actconfig; if (get_user(u, (int __user *)arg)) return -EFAULT; actconfig = ps->dev->actconfig; /* Don't touch the device if any interfaces are claimed. * It could interfere with other drivers' operations, and if * an interface is claimed by usbfs it could easily deadlock. */ if (actconfig) { int i; for (i = 0; i < actconfig->desc.bNumInterfaces; ++i) { if (usb_interface_claimed(actconfig->interface[i])) { dev_warn(&ps->dev->dev, "usbfs: interface %d claimed by %s " "while '%s' sets config #%d\n", actconfig->interface[i] ->cur_altsetting ->desc.bInterfaceNumber, actconfig->interface[i] ->dev.driver->name, current->comm, u); status = -EBUSY; break; } } } /* SET_CONFIGURATION is often abused as a "cheap" driver reset, * so avoid usb_set_configuration()'s kick to sysfs */ if (status == 0) { if (actconfig && actconfig->desc.bConfigurationValue == u) status = usb_reset_configuration(ps->dev); else status = usb_set_configuration(ps->dev, u); } return status; } static int proc_do_submiturb(struct dev_state *ps, struct usbdevfs_urb *uurb, struct usbdevfs_iso_packet_desc __user *iso_frame_desc, void __user *arg) { struct usbdevfs_iso_packet_desc *isopkt = NULL; struct usb_host_endpoint *ep; struct async *as; struct usb_ctrlrequest *dr = NULL; const struct cred *cred = current_cred(); unsigned int u, totlen, isofrmlen; int ret, ifnum = -1; int is_in; if (uurb->flags & ~(USBDEVFS_URB_ISO_ASAP | USBDEVFS_URB_SHORT_NOT_OK | USBDEVFS_URB_BULK_CONTINUATION | USBDEVFS_URB_NO_FSBR | USBDEVFS_URB_ZERO_PACKET | USBDEVFS_URB_NO_INTERRUPT)) return -EINVAL; if (uurb->buffer_length > 0 && !uurb->buffer) return -EINVAL; if (!(uurb->type == USBDEVFS_URB_TYPE_CONTROL && (uurb->endpoint & ~USB_ENDPOINT_DIR_MASK) == 0)) { ifnum = findintfep(ps->dev, uurb->endpoint); if (ifnum < 0) return ifnum; ret = checkintf(ps, ifnum); if (ret) return ret; } if ((uurb->endpoint & USB_ENDPOINT_DIR_MASK) != 0) { is_in = 1; ep = ps->dev->ep_in[uurb->endpoint & USB_ENDPOINT_NUMBER_MASK]; } else { is_in = 0; ep = ps->dev->ep_out[uurb->endpoint & USB_ENDPOINT_NUMBER_MASK]; } if (!ep) return -ENOENT; switch(uurb->type) { case USBDEVFS_URB_TYPE_CONTROL: if (!usb_endpoint_xfer_control(&ep->desc)) return -EINVAL; /* min 8 byte setup packet, * max 8 byte setup plus an arbitrary data stage */ if (uurb->buffer_length < 8 || uurb->buffer_length > (8 + MAX_USBFS_BUFFER_SIZE)) return -EINVAL; dr = kmalloc(sizeof(struct usb_ctrlrequest), GFP_KERNEL); if (!dr) return -ENOMEM; if (copy_from_user(dr, uurb->buffer, 8)) { kfree(dr); return -EFAULT; } if (uurb->buffer_length < (le16_to_cpup(&dr->wLength) + 8)) { kfree(dr); return -EINVAL; } ret = check_ctrlrecip(ps, dr->bRequestType, le16_to_cpup(&dr->wIndex)); if (ret) { kfree(dr); return ret; } uurb->number_of_packets = 0; uurb->buffer_length = le16_to_cpup(&dr->wLength); uurb->buffer += 8; if ((dr->bRequestType & USB_DIR_IN) && uurb->buffer_length) { is_in = 1; uurb->endpoint |= USB_DIR_IN; } else { is_in = 0; uurb->endpoint &= ~USB_DIR_IN; } snoop(&ps->dev->dev, "control urb: bRequestType=%02x " "bRequest=%02x wValue=%04x " "wIndex=%04x wLength=%04x\n", dr->bRequestType, dr->bRequest, __le16_to_cpup(&dr->wValue), __le16_to_cpup(&dr->wIndex), __le16_to_cpup(&dr->wLength)); break; case USBDEVFS_URB_TYPE_BULK: switch (usb_endpoint_type(&ep->desc)) { case USB_ENDPOINT_XFER_CONTROL: case USB_ENDPOINT_XFER_ISOC: return -EINVAL; case USB_ENDPOINT_XFER_INT: /* allow single-shot interrupt transfers */ uurb->type = USBDEVFS_URB_TYPE_INTERRUPT; goto interrupt_urb; } uurb->number_of_packets = 0; if (uurb->buffer_length > MAX_USBFS_BUFFER_SIZE) return -EINVAL; break; case USBDEVFS_URB_TYPE_INTERRUPT: if (!usb_endpoint_xfer_int(&ep->desc)) return -EINVAL; interrupt_urb: uurb->number_of_packets = 0; if (uurb->buffer_length > MAX_USBFS_BUFFER_SIZE) return -EINVAL; break; case USBDEVFS_URB_TYPE_ISO: /* arbitrary limit */ if (uurb->number_of_packets < 1 || uurb->number_of_packets > 128) return -EINVAL; if (!usb_endpoint_xfer_isoc(&ep->desc)) return -EINVAL; isofrmlen = sizeof(struct usbdevfs_iso_packet_desc) * uurb->number_of_packets; if (!(isopkt = kmalloc(isofrmlen, GFP_KERNEL))) return -ENOMEM; if (copy_from_user(isopkt, iso_frame_desc, isofrmlen)) { kfree(isopkt); return -EFAULT; } for (totlen = u = 0; u < uurb->number_of_packets; u++) { /* arbitrary limit, * sufficient for USB 2.0 high-bandwidth iso */ if (isopkt[u].length > 8192) { kfree(isopkt); return -EINVAL; } totlen += isopkt[u].length; } /* 3072 * 64 microframes */ if (totlen > 196608) { kfree(isopkt); return -EINVAL; } uurb->buffer_length = totlen; break; default: return -EINVAL; } if (uurb->buffer_length > 0 && !access_ok(is_in ? VERIFY_WRITE : VERIFY_READ, uurb->buffer, uurb->buffer_length)) { kfree(isopkt); kfree(dr); return -EFAULT; } as = alloc_async(uurb->number_of_packets); if (!as) { kfree(isopkt); kfree(dr); return -ENOMEM; } if (uurb->buffer_length > 0) { as->urb->transfer_buffer = kmalloc(uurb->buffer_length, GFP_KERNEL); if (!as->urb->transfer_buffer) { kfree(isopkt); kfree(dr); free_async(as); return -ENOMEM; } /* Isochronous input data may end up being discontiguous * if some of the packets are short. Clear the buffer so * that the gaps don't leak kernel data to userspace. */ if (is_in && uurb->type == USBDEVFS_URB_TYPE_ISO) memset(as->urb->transfer_buffer, 0, uurb->buffer_length); } as->urb->dev = ps->dev; as->urb->pipe = (uurb->type << 30) | __create_pipe(ps->dev, uurb->endpoint & 0xf) | (uurb->endpoint & USB_DIR_IN); /* This tedious sequence is necessary because the URB_* flags * are internal to the kernel and subject to change, whereas * the USBDEVFS_URB_* flags are a user API and must not be changed. */ u = (is_in ? URB_DIR_IN : URB_DIR_OUT); if (uurb->flags & USBDEVFS_URB_ISO_ASAP) u |= URB_ISO_ASAP; if (uurb->flags & USBDEVFS_URB_SHORT_NOT_OK) u |= URB_SHORT_NOT_OK; if (uurb->flags & USBDEVFS_URB_NO_FSBR) u |= URB_NO_FSBR; if (uurb->flags & USBDEVFS_URB_ZERO_PACKET) u |= URB_ZERO_PACKET; if (uurb->flags & USBDEVFS_URB_NO_INTERRUPT) u |= URB_NO_INTERRUPT; as->urb->transfer_flags = u; as->urb->transfer_buffer_length = uurb->buffer_length; as->urb->setup_packet = (unsigned char *)dr; as->urb->start_frame = uurb->start_frame; as->urb->number_of_packets = uurb->number_of_packets; if (uurb->type == USBDEVFS_URB_TYPE_ISO || ps->dev->speed == USB_SPEED_HIGH) as->urb->interval = 1 << min(15, ep->desc.bInterval - 1); else as->urb->interval = ep->desc.bInterval; as->urb->context = as; as->urb->complete = async_completed; for (totlen = u = 0; u < uurb->number_of_packets; u++) { as->urb->iso_frame_desc[u].offset = totlen; as->urb->iso_frame_desc[u].length = isopkt[u].length; totlen += isopkt[u].length; } kfree(isopkt); as->ps = ps; as->userurb = arg; if (is_in && uurb->buffer_length > 0) as->userbuffer = uurb->buffer; else as->userbuffer = NULL; as->signr = uurb->signr; as->ifnum = ifnum; as->pid = get_pid(task_pid(current)); as->uid = cred->uid; as->euid = cred->euid; security_task_getsecid(current, &as->secid); if (!is_in && uurb->buffer_length > 0) { if (copy_from_user(as->urb->transfer_buffer, uurb->buffer, uurb->buffer_length)) { free_async(as); return -EFAULT; } } snoop_urb(ps->dev, as->userurb, as->urb->pipe, as->urb->transfer_buffer_length, 0, SUBMIT, is_in ? NULL : as->urb->transfer_buffer, uurb->buffer_length); async_newpending(as); if (usb_endpoint_xfer_bulk(&ep->desc)) { spin_lock_irq(&ps->lock); /* Not exactly the endpoint address; the direction bit is * shifted to the 0x10 position so that the value will be * between 0 and 31. */ as->bulk_addr = usb_endpoint_num(&ep->desc) | ((ep->desc.bEndpointAddress & USB_ENDPOINT_DIR_MASK) >> 3); /* If this bulk URB is the start of a new transfer, re-enable * the endpoint. Otherwise mark it as a continuation URB. */ if (uurb->flags & USBDEVFS_URB_BULK_CONTINUATION) as->bulk_status = AS_CONTINUATION; else ps->disabled_bulk_eps &= ~(1 << as->bulk_addr); /* Don't accept continuation URBs if the endpoint is * disabled because of an earlier error. */ if (ps->disabled_bulk_eps & (1 << as->bulk_addr)) ret = -EREMOTEIO; else ret = usb_submit_urb(as->urb, GFP_ATOMIC); spin_unlock_irq(&ps->lock); } else { ret = usb_submit_urb(as->urb, GFP_KERNEL); } if (ret) { dev_printk(KERN_DEBUG, &ps->dev->dev, "usbfs: usb_submit_urb returned %d\n", ret); snoop_urb(ps->dev, as->userurb, as->urb->pipe, 0, ret, COMPLETE, NULL, 0); async_removepending(as); free_async(as); return ret; } return 0; } static int proc_submiturb(struct dev_state *ps, void __user *arg) { struct usbdevfs_urb uurb; if (copy_from_user(&uurb, arg, sizeof(uurb))) return -EFAULT; return proc_do_submiturb(ps, &uurb, (((struct usbdevfs_urb __user *)arg)->iso_frame_desc), arg); } static int proc_unlinkurb(struct dev_state *ps, void __user *arg) { struct async *as; as = async_getpending(ps, arg); if (!as) return -EINVAL; usb_kill_urb(as->urb); return 0; } static int processcompl(struct async *as, void __user * __user *arg) { struct urb *urb = as->urb; struct usbdevfs_urb __user *userurb = as->userurb; void __user *addr = as->userurb; unsigned int i; if (as->userbuffer && urb->actual_length) { if (urb->number_of_packets > 0) /* Isochronous */ i = urb->transfer_buffer_length; else /* Non-Isoc */ i = urb->actual_length; if (copy_to_user(as->userbuffer, urb->transfer_buffer, i)) goto err_out; } if (put_user(as->status, &userurb->status)) goto err_out; if (put_user(urb->actual_length, &userurb->actual_length)) goto err_out; if (put_user(urb->error_count, &userurb->error_count)) goto err_out; if (usb_endpoint_xfer_isoc(&urb->ep->desc)) { for (i = 0; i < urb->number_of_packets; i++) { if (put_user(urb->iso_frame_desc[i].actual_length, &userurb->iso_frame_desc[i].actual_length)) goto err_out; if (put_user(urb->iso_frame_desc[i].status, &userurb->iso_frame_desc[i].status)) goto err_out; } } if (put_user(addr, (void __user * __user *)arg)) return -EFAULT; return 0; err_out: return -EFAULT; } static struct async *reap_as(struct dev_state *ps) { DECLARE_WAITQUEUE(wait, current); struct async *as = NULL; struct usb_device *dev = ps->dev; add_wait_queue(&ps->wait, &wait); for (;;) { __set_current_state(TASK_INTERRUPTIBLE); as = async_getcompleted(ps); if (as) break; if (signal_pending(current)) break; usb_unlock_device(dev); schedule(); usb_lock_device(dev); } remove_wait_queue(&ps->wait, &wait); set_current_state(TASK_RUNNING); return as; } static int proc_reapurb(struct dev_state *ps, void __user *arg) { struct async *as = reap_as(ps); if (as) { int retval = processcompl(as, (void __user * __user *)arg); free_async(as); return retval; } if (signal_pending(current)) return -EINTR; return -EIO; } static int proc_reapurbnonblock(struct dev_state *ps, void __user *arg) { int retval; struct async *as; as = async_getcompleted(ps); retval = -EAGAIN; if (as) { retval = processcompl(as, (void __user * __user *)arg); free_async(as); } return retval; } #ifdef CONFIG_COMPAT static int proc_control_compat(struct dev_state *ps, struct usbdevfs_ctrltransfer32 __user *p32) { struct usbdevfs_ctrltransfer __user *p; __u32 udata; p = compat_alloc_user_space(sizeof(*p)); if (copy_in_user(p, p32, (sizeof(*p32) - sizeof(compat_caddr_t))) || get_user(udata, &p32->data) || put_user(compat_ptr(udata), &p->data)) return -EFAULT; return proc_control(ps, p); } static int proc_bulk_compat(struct dev_state *ps, struct usbdevfs_bulktransfer32 __user *p32) { struct usbdevfs_bulktransfer __user *p; compat_uint_t n; compat_caddr_t addr; p = compat_alloc_user_space(sizeof(*p)); if (get_user(n, &p32->ep) || put_user(n, &p->ep) || get_user(n, &p32->len) || put_user(n, &p->len) || get_user(n, &p32->timeout) || put_user(n, &p->timeout) || get_user(addr, &p32->data) || put_user(compat_ptr(addr), &p->data)) return -EFAULT; return proc_bulk(ps, p); } static int proc_disconnectsignal_compat(struct dev_state *ps, void __user *arg) { struct usbdevfs_disconnectsignal32 ds; if (copy_from_user(&ds, arg, sizeof(ds))) return -EFAULT; ps->discsignr = ds.signr; ps->disccontext = compat_ptr(ds.context); return 0; } static int get_urb32(struct usbdevfs_urb *kurb, struct usbdevfs_urb32 __user *uurb) { __u32 uptr; if (!access_ok(VERIFY_READ, uurb, sizeof(*uurb)) || __get_user(kurb->type, &uurb->type) || __get_user(kurb->endpoint, &uurb->endpoint) || __get_user(kurb->status, &uurb->status) || __get_user(kurb->flags, &uurb->flags) || __get_user(kurb->buffer_length, &uurb->buffer_length) || __get_user(kurb->actual_length, &uurb->actual_length) || __get_user(kurb->start_frame, &uurb->start_frame) || __get_user(kurb->number_of_packets, &uurb->number_of_packets) || __get_user(kurb->error_count, &uurb->error_count) || __get_user(kurb->signr, &uurb->signr)) return -EFAULT; if (__get_user(uptr, &uurb->buffer)) return -EFAULT; kurb->buffer = compat_ptr(uptr); if (__get_user(uptr, &uurb->usercontext)) return -EFAULT; kurb->usercontext = compat_ptr(uptr); return 0; } static int proc_submiturb_compat(struct dev_state *ps, void __user *arg) { struct usbdevfs_urb uurb; if (get_urb32(&uurb, (struct usbdevfs_urb32 __user *)arg)) return -EFAULT; return proc_do_submiturb(ps, &uurb, ((struct usbdevfs_urb32 __user *)arg)->iso_frame_desc, arg); } static int processcompl_compat(struct async *as, void __user * __user *arg) { struct urb *urb = as->urb; struct usbdevfs_urb32 __user *userurb = as->userurb; void __user *addr = as->userurb; unsigned int i; if (as->userbuffer && urb->actual_length) if (copy_to_user(as->userbuffer, urb->transfer_buffer, urb->actual_length)) return -EFAULT; if (put_user(as->status, &userurb->status)) return -EFAULT; if (put_user(urb->actual_length, &userurb->actual_length)) return -EFAULT; if (put_user(urb->error_count, &userurb->error_count)) return -EFAULT; if (usb_endpoint_xfer_isoc(&urb->ep->desc)) { for (i = 0; i < urb->number_of_packets; i++) { if (put_user(urb->iso_frame_desc[i].actual_length, &userurb->iso_frame_desc[i].actual_length)) return -EFAULT; if (put_user(urb->iso_frame_desc[i].status, &userurb->iso_frame_desc[i].status)) return -EFAULT; } } if (put_user(ptr_to_compat(addr), (u32 __user *)arg)) return -EFAULT; return 0; } static int proc_reapurb_compat(struct dev_state *ps, void __user *arg) { struct async *as = reap_as(ps); if (as) { int retval = processcompl_compat(as, (void __user * __user *)arg); free_async(as); return retval; } if (signal_pending(current)) return -EINTR; return -EIO; } static int proc_reapurbnonblock_compat(struct dev_state *ps, void __user *arg) { int retval; struct async *as; retval = -EAGAIN; as = async_getcompleted(ps); if (as) { retval = processcompl_compat(as, (void __user * __user *)arg); free_async(as); } return retval; } #endif static int proc_disconnectsignal(struct dev_state *ps, void __user *arg) { struct usbdevfs_disconnectsignal ds; if (copy_from_user(&ds, arg, sizeof(ds))) return -EFAULT; ps->discsignr = ds.signr; ps->disccontext = ds.context; return 0; } static int proc_claiminterface(struct dev_state *ps, void __user *arg) { unsigned int ifnum; if (get_user(ifnum, (unsigned int __user *)arg)) return -EFAULT; return claimintf(ps, ifnum); } static int proc_releaseinterface(struct dev_state *ps, void __user *arg) { unsigned int ifnum; int ret; if (get_user(ifnum, (unsigned int __user *)arg)) return -EFAULT; if ((ret = releaseintf(ps, ifnum)) < 0) return ret; destroy_async_on_interface (ps, ifnum); return 0; } static int proc_ioctl(struct dev_state *ps, struct usbdevfs_ioctl *ctl) { int size; void *buf = NULL; int retval = 0; struct usb_interface *intf = NULL; struct usb_driver *driver = NULL; /* alloc buffer */ if ((size = _IOC_SIZE(ctl->ioctl_code)) > 0) { if ((buf = kmalloc(size, GFP_KERNEL)) == NULL) return -ENOMEM; if ((_IOC_DIR(ctl->ioctl_code) & _IOC_WRITE)) { if (copy_from_user(buf, ctl->data, size)) { kfree(buf); return -EFAULT; } } else { memset(buf, 0, size); } } if (!connected(ps)) { kfree(buf); return -ENODEV; } if (ps->dev->state != USB_STATE_CONFIGURED) retval = -EHOSTUNREACH; else if (!(intf = usb_ifnum_to_if(ps->dev, ctl->ifno))) retval = -EINVAL; else switch (ctl->ioctl_code) { /* disconnect kernel driver from interface */ case USBDEVFS_DISCONNECT: if (intf->dev.driver) { driver = to_usb_driver(intf->dev.driver); dev_dbg(&intf->dev, "disconnect by usbfs\n"); usb_driver_release_interface(driver, intf); } else retval = -ENODATA; break; /* let kernel drivers try to (re)bind to the interface */ case USBDEVFS_CONNECT: if (!intf->dev.driver) retval = device_attach(&intf->dev); else retval = -EBUSY; break; /* talk directly to the interface's driver */ default: if (intf->dev.driver) driver = to_usb_driver(intf->dev.driver); if (driver == NULL || driver->unlocked_ioctl == NULL) { retval = -ENOTTY; } else { retval = driver->unlocked_ioctl(intf, ctl->ioctl_code, buf); if (retval == -ENOIOCTLCMD) retval = -ENOTTY; } } /* cleanup and return */ if (retval >= 0 && (_IOC_DIR(ctl->ioctl_code) & _IOC_READ) != 0 && size > 0 && copy_to_user(ctl->data, buf, size) != 0) retval = -EFAULT; kfree(buf); return retval; } static int proc_ioctl_default(struct dev_state *ps, void __user *arg) { struct usbdevfs_ioctl ctrl; if (copy_from_user(&ctrl, arg, sizeof(ctrl))) return -EFAULT; return proc_ioctl(ps, &ctrl); } #ifdef CONFIG_COMPAT static int proc_ioctl_compat(struct dev_state *ps, compat_uptr_t arg) { struct usbdevfs_ioctl32 __user *uioc; struct usbdevfs_ioctl ctrl; u32 udata; uioc = compat_ptr((long)arg); if (!access_ok(VERIFY_READ, uioc, sizeof(*uioc)) || __get_user(ctrl.ifno, &uioc->ifno) || __get_user(ctrl.ioctl_code, &uioc->ioctl_code) || __get_user(udata, &uioc->data)) return -EFAULT; ctrl.data = compat_ptr(udata); return proc_ioctl(ps, &ctrl); } #endif static int proc_claim_port(struct dev_state *ps, void __user *arg) { unsigned portnum; int rc; if (get_user(portnum, (unsigned __user *) arg)) return -EFAULT; rc = usb_hub_claim_port(ps->dev, portnum, ps); if (rc == 0) snoop(&ps->dev->dev, "port %d claimed by process %d: %s\n", portnum, task_pid_nr(current), current->comm); return rc; } static int proc_release_port(struct dev_state *ps, void __user *arg) { unsigned portnum; if (get_user(portnum, (unsigned __user *) arg)) return -EFAULT; return usb_hub_release_port(ps->dev, portnum, ps); } /* * NOTE: All requests here that have interface numbers as parameters * are assuming that somehow the configuration has been prevented from * changing. But there's no mechanism to ensure that... */ static long usbdev_do_ioctl(struct file *file, unsigned int cmd, void __user *p) { struct dev_state *ps = file->private_data; struct inode *inode = file->f_path.dentry->d_inode; struct usb_device *dev = ps->dev; int ret = -ENOTTY; if (!(file->f_mode & FMODE_WRITE)) return -EPERM; usb_lock_device(dev); if (!connected(ps)) { usb_unlock_device(dev); return -ENODEV; } switch (cmd) { case USBDEVFS_CONTROL: snoop(&dev->dev, "%s: CONTROL\n", __func__); ret = proc_control(ps, p); if (ret >= 0) inode->i_mtime = CURRENT_TIME; break; case USBDEVFS_BULK: snoop(&dev->dev, "%s: BULK\n", __func__); ret = proc_bulk(ps, p); if (ret >= 0) inode->i_mtime = CURRENT_TIME; break; case USBDEVFS_RESETEP: snoop(&dev->dev, "%s: RESETEP\n", __func__); ret = proc_resetep(ps, p); if (ret >= 0) inode->i_mtime = CURRENT_TIME; break; case USBDEVFS_RESET: snoop(&dev->dev, "%s: RESET\n", __func__); ret = proc_resetdevice(ps); break; case USBDEVFS_CLEAR_HALT: snoop(&dev->dev, "%s: CLEAR_HALT\n", __func__); ret = proc_clearhalt(ps, p); if (ret >= 0) inode->i_mtime = CURRENT_TIME; break; case USBDEVFS_GETDRIVER: snoop(&dev->dev, "%s: GETDRIVER\n", __func__); ret = proc_getdriver(ps, p); break; case USBDEVFS_CONNECTINFO: snoop(&dev->dev, "%s: CONNECTINFO\n", __func__); ret = proc_connectinfo(ps, p); break; case USBDEVFS_SETINTERFACE: snoop(&dev->dev, "%s: SETINTERFACE\n", __func__); ret = proc_setintf(ps, p); break; case USBDEVFS_SETCONFIGURATION: snoop(&dev->dev, "%s: SETCONFIGURATION\n", __func__); ret = proc_setconfig(ps, p); break; case USBDEVFS_SUBMITURB: snoop(&dev->dev, "%s: SUBMITURB\n", __func__); ret = proc_submiturb(ps, p); if (ret >= 0) inode->i_mtime = CURRENT_TIME; break; #ifdef CONFIG_COMPAT case USBDEVFS_CONTROL32: snoop(&dev->dev, "%s: CONTROL32\n", __func__); ret = proc_control_compat(ps, p); if (ret >= 0) inode->i_mtime = CURRENT_TIME; break; case USBDEVFS_BULK32: snoop(&dev->dev, "%s: BULK32\n", __func__); ret = proc_bulk_compat(ps, p); if (ret >= 0) inode->i_mtime = CURRENT_TIME; break; case USBDEVFS_DISCSIGNAL32: snoop(&dev->dev, "%s: DISCSIGNAL32\n", __func__); ret = proc_disconnectsignal_compat(ps, p); break; case USBDEVFS_SUBMITURB32: snoop(&dev->dev, "%s: SUBMITURB32\n", __func__); ret = proc_submiturb_compat(ps, p); if (ret >= 0) inode->i_mtime = CURRENT_TIME; break; case USBDEVFS_REAPURB32: snoop(&dev->dev, "%s: REAPURB32\n", __func__); ret = proc_reapurb_compat(ps, p); break; case USBDEVFS_REAPURBNDELAY32: snoop(&dev->dev, "%s: REAPURBNDELAY32\n", __func__); ret = proc_reapurbnonblock_compat(ps, p); break; case USBDEVFS_IOCTL32: snoop(&dev->dev, "%s: IOCTL32\n", __func__); ret = proc_ioctl_compat(ps, ptr_to_compat(p)); break; #endif case USBDEVFS_DISCARDURB: snoop(&dev->dev, "%s: DISCARDURB\n", __func__); ret = proc_unlinkurb(ps, p); break; case USBDEVFS_REAPURB: snoop(&dev->dev, "%s: REAPURB\n", __func__); ret = proc_reapurb(ps, p); break; case USBDEVFS_REAPURBNDELAY: snoop(&dev->dev, "%s: REAPURBNDELAY\n", __func__); ret = proc_reapurbnonblock(ps, p); break; case USBDEVFS_DISCSIGNAL: snoop(&dev->dev, "%s: DISCSIGNAL\n", __func__); ret = proc_disconnectsignal(ps, p); break; case USBDEVFS_CLAIMINTERFACE: snoop(&dev->dev, "%s: CLAIMINTERFACE\n", __func__); ret = proc_claiminterface(ps, p); break; case USBDEVFS_RELEASEINTERFACE: snoop(&dev->dev, "%s: RELEASEINTERFACE\n", __func__); ret = proc_releaseinterface(ps, p); break; case USBDEVFS_IOCTL: snoop(&dev->dev, "%s: IOCTL\n", __func__); ret = proc_ioctl_default(ps, p); break; case USBDEVFS_CLAIM_PORT: snoop(&dev->dev, "%s: CLAIM_PORT\n", __func__); ret = proc_claim_port(ps, p); break; case USBDEVFS_RELEASE_PORT: snoop(&dev->dev, "%s: RELEASE_PORT\n", __func__); ret = proc_release_port(ps, p); break; } usb_unlock_device(dev); if (ret >= 0) inode->i_atime = CURRENT_TIME; return ret; } static long usbdev_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { int ret; ret = usbdev_do_ioctl(file, cmd, (void __user *)arg); return ret; } #ifdef CONFIG_COMPAT static long usbdev_compat_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { int ret; ret = usbdev_do_ioctl(file, cmd, compat_ptr(arg)); return ret; } #endif /* No kernel lock - fine */ static unsigned int usbdev_poll(struct file *file, struct poll_table_struct *wait) { struct dev_state *ps = file->private_data; unsigned int mask = 0; poll_wait(file, &ps->wait, wait); if (file->f_mode & FMODE_WRITE && !list_empty(&ps->async_completed)) mask |= POLLOUT | POLLWRNORM; if (!connected(ps)) mask |= POLLERR | POLLHUP; return mask; } const struct file_operations usbdev_file_operations = { .owner = THIS_MODULE, .llseek = usbdev_lseek, .read = usbdev_read, .poll = usbdev_poll, .unlocked_ioctl = usbdev_ioctl, #ifdef CONFIG_COMPAT .compat_ioctl = usbdev_compat_ioctl, #endif .open = usbdev_open, .release = usbdev_release, }; static void usbdev_remove(struct usb_device *udev) { struct dev_state *ps; struct siginfo sinfo; while (!list_empty(&udev->filelist)) { ps = list_entry(udev->filelist.next, struct dev_state, list); destroy_all_async(ps); wake_up_all(&ps->wait); list_del_init(&ps->list); if (ps->discsignr) { sinfo.si_signo = ps->discsignr; sinfo.si_errno = EPIPE; sinfo.si_code = SI_ASYNCIO; sinfo.si_addr = ps->disccontext; kill_pid_info_as_uid(ps->discsignr, &sinfo, ps->disc_pid, ps->disc_uid, ps->disc_euid, ps->secid); } } } #ifdef CONFIG_USB_DEVICE_CLASS static struct class *usb_classdev_class; static int usb_classdev_add(struct usb_device *dev) { struct device *cldev; cldev = device_create(usb_classdev_class, &dev->dev, dev->dev.devt, NULL, "usbdev%d.%d", dev->bus->busnum, dev->devnum); if (IS_ERR(cldev)) return PTR_ERR(cldev); dev->usb_classdev = cldev; return 0; } static void usb_classdev_remove(struct usb_device *dev) { if (dev->usb_classdev) device_unregister(dev->usb_classdev); } #else #define usb_classdev_add(dev) 0 #define usb_classdev_remove(dev) do {} while (0) #endif static int usbdev_notify(struct notifier_block *self, unsigned long action, void *dev) { switch (action) { case USB_DEVICE_ADD: if (usb_classdev_add(dev)) return NOTIFY_BAD; break; case USB_DEVICE_REMOVE: usb_classdev_remove(dev); usbdev_remove(dev); break; } return NOTIFY_OK; } static struct notifier_block usbdev_nb = { .notifier_call = usbdev_notify, }; static struct cdev usb_device_cdev; int __init usb_devio_init(void) { int retval; retval = register_chrdev_region(USB_DEVICE_DEV, USB_DEVICE_MAX, "usb_device"); if (retval) { printk(KERN_ERR "Unable to register minors for usb_device\n"); goto out; } cdev_init(&usb_device_cdev, &usbdev_file_operations); retval = cdev_add(&usb_device_cdev, USB_DEVICE_DEV, USB_DEVICE_MAX); if (retval) { printk(KERN_ERR "Unable to get usb_device major %d\n", USB_DEVICE_MAJOR); goto error_cdev; } #ifdef CONFIG_USB_DEVICE_CLASS usb_classdev_class = class_create(THIS_MODULE, "usb_device"); if (IS_ERR(usb_classdev_class)) { printk(KERN_ERR "Unable to register usb_device class\n"); retval = PTR_ERR(usb_classdev_class); cdev_del(&usb_device_cdev); usb_classdev_class = NULL; goto out; } /* devices of this class shadow the major:minor of their parent * device, so clear ->dev_kobj to prevent adding duplicate entries * to /sys/dev */ usb_classdev_class->dev_kobj = NULL; #endif usb_register_notify(&usbdev_nb); out: return retval; error_cdev: unregister_chrdev_region(USB_DEVICE_DEV, USB_DEVICE_MAX); goto out; } void usb_devio_cleanup(void) { usb_unregister_notify(&usbdev_nb); #ifdef CONFIG_USB_DEVICE_CLASS class_destroy(usb_classdev_class); #endif cdev_del(&usb_device_cdev); unregister_chrdev_region(USB_DEVICE_DEV, USB_DEVICE_MAX); }
futuretekinc/cortina-kernel-2.6.36
drivers/usb/core/devio.c
C
gpl-2.0
52,317
<?php // Forum Commands // Called from index.php // uses $_SESSION['override'] //###################################################################### //###### Forms ######################################################### //###################################################################### if (empty($_POST)){ global $game, $info, $duneMail, $duneForum; //############################################################## //## First Run ################################################# //############################################################## if (!isset($game['forum'])) { $game['forum'] = array(); $game['forum']['page'] = 1; } //############################################################## //## Every Run ################################################# //############################################################## echo '<h3>Forum</h3><br>'; //## Select Page ############################################### //## Print Forum ############################################### foreach ($duneForum as $x) { print $x['faction'].'<br>'; print $x['message'].'<br>'; print $x['time'].'<br>'; print '<br>'; } //## Post To Forum ############################################# echo '<form action="" method="post"> Post:<br> <input type="textarea" name="post"> <input type="submit" value="Submit"> </form> '; } //###################################################################### //###### Post ########################################################## //###################################################################### if (!empty($_POST)){ if (isset($_POST['post'])) { dune_postForum($_POST['post']); refreshPage(); } } //###################################################################### //###### Actions ####################################################### //###################################################################### ?>
DunePBM/DunePBM
html/.dune_pbm/forum.php
PHP
gpl-2.0
2,046
#!/usr/bin/env python #################################################################################################### #################################################################################################### ## ## ## Hove's Raspberry Pi Python Quadcopter Flight Controller. Open Source @ GitHub ## ## PiStuffing/Quadcopter under GPL for non-commercial application. Any code derived from ## ## this should retain this copyright comment. ## ## ## ## Copyright 2012 - 2018 Andy Baker (Hove) - andy@pistuffing.co.uk ## ## ## #################################################################################################### #################################################################################################### from __future__ import division from __future__ import with_statement import signal import socket import time import sys import getopt import math from array import * import smbus import select import os import io import logging import csv from RPIO import PWM import RPi.GPIO as GPIO import subprocess import ctypes from ctypes.util import find_library import picamera import struct import gps import serial MIN_SATS = 7 EARTH_RADIUS = 6371000 # meters GRAV_ACCEL = 9.80665 # meters per second per second RC_PASSIVE = 0 RC_TAKEOFF = 1 RC_FLYING = 2 RC_LANDING = 3 RC_DONE = 4 RC_ABORT = 5 rc_status_name = ["PASSIVE", "TAKEOFF", "FLYING", "LANDING", "DONE", "ABORT"] FULL_FIFO_BATCHES = 20 # << int(512 / 12) #################################################################################################### # # Adafruit i2c interface enhanced with performance / error handling enhancements # #################################################################################################### class I2C: def __init__(self, address, bus=smbus.SMBus(1)): self.address = address self.bus = bus self.misses = 0 def writeByte(self, value): self.bus.write_byte(self.address, value) def write8(self, reg, value): self.bus.write_byte_data(self.address, reg, value) def writeList(self, reg, list): self.bus.write_i2c_block_data(self.address, reg, list) def readU8(self, reg): result = self.bus.read_byte_data(self.address, reg) return result def readS8(self, reg): result = self.bus.read_byte_data(self.address, reg) result = result - 256 if result > 127 else result return result def readU16(self, reg): hibyte = self.bus.read_byte_data(self.address, reg) result = (hibyte << 8) + self.bus.read_byte_data(self.address, reg+1) return result def readS16(self, reg): hibyte = self.bus.read_byte_data(self.address, reg) hibyte = hibyte - 256 if hibyte > 127 else hibyte result = (hibyte << 8) + self.bus.read_byte_data(self.address, reg+1) return result def readList(self, reg, length): "Reads a byte array value from the I2C device. The content depends on the device. The " "FIFO read return sequential values from the same register. For all other, sequestial" "regester values are returned" result = self.bus.read_i2c_block_data(self.address, reg, length) return result #################################################################################################### # # Gyroscope / Accelerometer class for reading position / movement. Works with the Invensense IMUs: # # - MPU-6050 # - MPU-9150 # - MPU-9250 # #################################################################################################### class MPU6050: i2c = None # Registers/etc. __MPU6050_RA_SELF_TEST_XG = 0x00 __MPU6050_RA_SELF_TEST_YG = 0x01 __MPU6050_RA_SELF_TEST_ZG = 0x02 __MPU6050_RA_SELF_TEST_XA = 0x0D __MPU6050_RA_SELF_TEST_YA = 0x0E __MPU6050_RA_SELF_TEST_ZA = 0x0F __MPU6050_RA_XG_OFFS_USRH = 0x13 __MPU6050_RA_XG_OFFS_USRL = 0x14 __MPU6050_RA_YG_OFFS_USRH = 0x15 __MPU6050_RA_YG_OFFS_USRL = 0x16 __MPU6050_RA_ZG_OFFS_USRH = 0x17 __MPU6050_RA_ZG_OFFS_USRL = 0x18 __MPU6050_RA_SMPLRT_DIV = 0x19 __MPU6050_RA_CONFIG = 0x1A __MPU6050_RA_GYRO_CONFIG = 0x1B __MPU6050_RA_ACCEL_CONFIG = 0x1C __MPU9250_RA_ACCEL_CFG_2 = 0x1D __MPU6050_RA_FF_THR = 0x1D __MPU6050_RA_FF_DUR = 0x1E __MPU6050_RA_MOT_THR = 0x1F __MPU6050_RA_MOT_DUR = 0x20 __MPU6050_RA_ZRMOT_THR = 0x21 __MPU6050_RA_ZRMOT_DUR = 0x22 __MPU6050_RA_FIFO_EN = 0x23 __MPU6050_RA_I2C_MST_CTRL = 0x24 __MPU6050_RA_I2C_SLV0_ADDR = 0x25 __MPU6050_RA_I2C_SLV0_REG = 0x26 __MPU6050_RA_I2C_SLV0_CTRL = 0x27 __MPU6050_RA_I2C_SLV1_ADDR = 0x28 __MPU6050_RA_I2C_SLV1_REG = 0x29 __MPU6050_RA_I2C_SLV1_CTRL = 0x2A __MPU6050_RA_I2C_SLV2_ADDR = 0x2B __MPU6050_RA_I2C_SLV2_REG = 0x2C __MPU6050_RA_I2C_SLV2_CTRL = 0x2D __MPU6050_RA_I2C_SLV3_ADDR = 0x2E __MPU6050_RA_I2C_SLV3_REG = 0x2F __MPU6050_RA_I2C_SLV3_CTRL = 0x30 __MPU6050_RA_I2C_SLV4_ADDR = 0x31 __MPU6050_RA_I2C_SLV4_REG = 0x32 __MPU6050_RA_I2C_SLV4_DO = 0x33 __MPU6050_RA_I2C_SLV4_CTRL = 0x34 __MPU6050_RA_I2C_SLV4_DI = 0x35 __MPU6050_RA_I2C_MST_STATUS = 0x36 __MPU6050_RA_INT_PIN_CFG = 0x37 __MPU6050_RA_INT_ENABLE = 0x38 __MPU6050_RA_DMP_INT_STATUS = 0x39 __MPU6050_RA_INT_STATUS = 0x3A __MPU6050_RA_ACCEL_XOUT_H = 0x3B __MPU6050_RA_ACCEL_XOUT_L = 0x3C __MPU6050_RA_ACCEL_YOUT_H = 0x3D __MPU6050_RA_ACCEL_YOUT_L = 0x3E __MPU6050_RA_ACCEL_ZOUT_H = 0x3F __MPU6050_RA_ACCEL_ZOUT_L = 0x40 __MPU6050_RA_TEMP_OUT_H = 0x41 __MPU6050_RA_TEMP_OUT_L = 0x42 __MPU6050_RA_GYRO_XOUT_H = 0x43 __MPU6050_RA_GYRO_XOUT_L = 0x44 __MPU6050_RA_GYRO_YOUT_H = 0x45 __MPU6050_RA_GYRO_YOUT_L = 0x46 __MPU6050_RA_GYRO_ZOUT_H = 0x47 __MPU6050_RA_GYRO_ZOUT_L = 0x48 __MPU6050_RA_EXT_SENS_DATA_00 = 0x49 __MPU6050_RA_EXT_SENS_DATA_01 = 0x4A __MPU6050_RA_EXT_SENS_DATA_02 = 0x4B __MPU6050_RA_EXT_SENS_DATA_03 = 0x4C __MPU6050_RA_EXT_SENS_DATA_04 = 0x4D __MPU6050_RA_EXT_SENS_DATA_05 = 0x4E __MPU6050_RA_EXT_SENS_DATA_06 = 0x4F __MPU6050_RA_EXT_SENS_DATA_07 = 0x50 __MPU6050_RA_EXT_SENS_DATA_08 = 0x51 __MPU6050_RA_EXT_SENS_DATA_09 = 0x52 __MPU6050_RA_EXT_SENS_DATA_10 = 0x53 __MPU6050_RA_EXT_SENS_DATA_11 = 0x54 __MPU6050_RA_EXT_SENS_DATA_12 = 0x55 __MPU6050_RA_EXT_SENS_DATA_13 = 0x56 __MPU6050_RA_EXT_SENS_DATA_14 = 0x57 __MPU6050_RA_EXT_SENS_DATA_15 = 0x58 __MPU6050_RA_EXT_SENS_DATA_16 = 0x59 __MPU6050_RA_EXT_SENS_DATA_17 = 0x5A __MPU6050_RA_EXT_SENS_DATA_18 = 0x5B __MPU6050_RA_EXT_SENS_DATA_19 = 0x5C __MPU6050_RA_EXT_SENS_DATA_20 = 0x5D __MPU6050_RA_EXT_SENS_DATA_21 = 0x5E __MPU6050_RA_EXT_SENS_DATA_22 = 0x5F __MPU6050_RA_EXT_SENS_DATA_23 = 0x60 __MPU6050_RA_MOT_DETECT_STATUS = 0x61 __MPU6050_RA_I2C_SLV0_DO = 0x63 __MPU6050_RA_I2C_SLV1_DO = 0x64 __MPU6050_RA_I2C_SLV2_DO = 0x65 __MPU6050_RA_I2C_SLV3_DO = 0x66 __MPU6050_RA_I2C_MST_DELAY_CTRL = 0x67 __MPU6050_RA_SIGNAL_PATH_RESET = 0x68 __MPU6050_RA_MOT_DETECT_CTRL = 0x69 __MPU6050_RA_USER_CTRL = 0x6A __MPU6050_RA_PWR_MGMT_1 = 0x6B __MPU6050_RA_PWR_MGMT_2 = 0x6C __MPU6050_RA_BANK_SEL = 0x6D __MPU6050_RA_MEM_START_ADDR = 0x6E __MPU6050_RA_MEM_R_W = 0x6F __MPU6050_RA_DMP_CFG_1 = 0x70 __MPU6050_RA_DMP_CFG_2 = 0x71 __MPU6050_RA_FIFO_COUNTH = 0x72 __MPU6050_RA_FIFO_COUNTL = 0x73 __MPU6050_RA_FIFO_R_W = 0x74 __MPU6050_RA_WHO_AM_I = 0x75 #----------------------------------------------------------------------------------------------- # Compass output registers when using the I2C master / slave #----------------------------------------------------------------------------------------------- __MPU9250_RA_MAG_XOUT_L = 0x4A __MPU9250_RA_MAG_XOUT_H = 0x4B __MPU9250_RA_MAG_YOUT_L = 0x4C __MPU9250_RA_MAG_YOUT_H = 0x4D __MPU9250_RA_MAG_ZOUT_L = 0x4E __MPU9250_RA_MAG_ZOUT_H = 0x4F #----------------------------------------------------------------------------------------------- # Compass output registers when directly accessing via IMU bypass #----------------------------------------------------------------------------------------------- __AK893_RA_WIA = 0x00 __AK893_RA_INFO = 0x01 __AK893_RA_ST1 = 0x00 __AK893_RA_X_LO = 0x03 __AK893_RA_X_HI = 0x04 __AK893_RA_Y_LO = 0x05 __AK893_RA_Y_HI = 0x06 __AK893_RA_Z_LO = 0x07 __AK893_RA_Z_HI = 0x08 __AK893_RA_ST2 = 0x09 __AK893_RA_CNTL1 = 0x0A __AK893_RA_RSV = 0x0B __AK893_RA_ASTC = 0x0C __AK893_RA_TS1 = 0x0D __AK893_RA_TS2 = 0x0E __AK893_RA_I2CDIS = 0x0F __AK893_RA_ASAX = 0x10 __AK893_RA_ASAY = 0x11 __AK893_RA_ASAZ = 0x12 __RANGE_ACCEL = 8 #AB: +/- 8g __RANGE_GYRO = 250 #AB: +/- 250o/s __SCALE_GYRO = math.radians(2 * __RANGE_GYRO / 65536) __SCALE_ACCEL = 2 * __RANGE_ACCEL / 65536 def __init__(self, address=0x68, alpf=2, glpf=1): self.i2c = I2C(address) self.address = address self.min_az = 0.0 self.max_az = 0.0 self.min_gx = 0.0 self.max_gx = 0.0 self.min_gy = 0.0 self.max_gy = 0.0 self.min_gz = 0.0 self.max_gz = 0.0 self.ax_offset = 0.0 self.ay_offset = 0.0 self.az_offset = 0.0 self.gx_offset = 0.0 self.gy_offset = 0.0 self.gz_offset = 0.0 logger.info('Reseting MPU-6050') #------------------------------------------------------------------------------------------- # Reset all registers #------------------------------------------------------------------------------------------- self.i2c.write8(self.__MPU6050_RA_PWR_MGMT_1, 0x80) time.sleep(0.1) #------------------------------------------------------------------------------------------- # Sets sample rate to 1kHz/(1+0) = 1kHz or 1ms (note 1kHz assumes dlpf is on - setting # dlpf to 0 or 7 changes 1kHz to 8kHz and therefore will require sample rate divider # to be changed to 7 to obtain the same 1kHz sample rate. #------------------------------------------------------------------------------------------- sample_rate_divisor = int(round(adc_frequency / sampling_rate)) logger.warning("SRD:, %d", sample_rate_divisor) self.i2c.write8(self.__MPU6050_RA_SMPLRT_DIV, sample_rate_divisor - 1) time.sleep(0.1) #------------------------------------------------------------------------------------------- # Sets clock source to gyro reference w/ PLL #------------------------------------------------------------------------------------------- self.i2c.write8(self.__MPU6050_RA_PWR_MGMT_1, 0x01) time.sleep(0.1) #------------------------------------------------------------------------------------------- # Gyro DLPF => 1kHz sample frequency used above divided by the sample divide factor. # # 0x00 = 250Hz @ 8kHz sampling - DO NOT USE, THE ACCELEROMETER STILL SAMPLES AT 1kHz WHICH PRODUCES EXPECTED BUT NOT CODED FOR TIMING AND FIFO CONTENT PROBLEMS # 0x01 = 184Hz # 0x02 = 92Hz # 0x03 = 41Hz # 0x04 = 20Hz # 0x05 = 10Hz # 0x06 = 5Hz # 0x07 = 3600Hz @ 8kHz # # 0x0* FIFO overflow overwrites oldest FIFO contents # 0x4* FIFO overflow does not overwrite full FIFO contents #------------------------------------------------------------------------------------------- self.i2c.write8(self.__MPU6050_RA_CONFIG, 0x40 | glpf) time.sleep(0.1) #------------------------------------------------------------------------------------------- # Disable gyro self tests, scale of +/- 250 degrees/s # # 0x00 = +/- 250 degrees/s # 0x08 = +/- 500 degrees/s # 0x10 = +/- 1000 degrees/s # 0x18 = +/- 2000 degrees/s # See SCALE_GYRO for conversion from raw data to units of radians per second #------------------------------------------------------------------------------------------- self.i2c.write8(self.__MPU6050_RA_GYRO_CONFIG, int(round(math.log(self.__RANGE_GYRO / 250, 2))) << 3) time.sleep(0.1) #------------------------------------------------------------------------------------------- # Accel DLPF => 1kHz sample frequency used above divided by the sample divide factor. # # 0x00 = 460Hz # 0x01 = 184Hz # 0x02 = 92Hz # 0x03 = 41Hz # 0x04 = 20Hz # 0x05 = 10Hz # 0x06 = 5Hz # 0x07 = 460Hz #------------------------------------------------------------------------------------------- self.i2c.write8(self.__MPU9250_RA_ACCEL_CFG_2, alpf) time.sleep(0.1) #------------------------------------------------------------------------------------------- # Disable accel self tests, scale of +/-8g # # 0x00 = +/- 2g # 0x08 = +/- 4g # 0x10 = +/- 8g # 0x18 = +/- 16g # See SCALE_ACCEL for convertion from raw data to units of meters per second squared #------------------------------------------------------------------------------------------- self.i2c.write8(self.__MPU6050_RA_ACCEL_CONFIG, int(round(math.log(self.__RANGE_ACCEL / 2, 2))) << 3) time.sleep(0.1) #------------------------------------------------------------------------------------------- # Set INT pin to push/pull, latch 'til read, any read to clear #------------------------------------------------------------------------------------------- self.i2c.write8(self.__MPU6050_RA_INT_PIN_CFG, 0x30) time.sleep(0.1) #------------------------------------------------------------------------------------------- # Initialize the FIFO overflow interrupt 0x10 (turned off at startup). #------------------------------------------------------------------------------------------- self.i2c.write8(self.__MPU6050_RA_INT_ENABLE, 0x00) time.sleep(0.1) #------------------------------------------------------------------------------------------- # Enabled the FIFO. #------------------------------------------------------------------------------------------- self.i2c.write8(self.__MPU6050_RA_USER_CTRL, 0x40) #------------------------------------------------------------------------------------------- # Accelerometer / gyro goes into FIFO later on - see flushFIFO() #------------------------------------------------------------------------------------------- self.i2c.write8(self.__MPU6050_RA_FIFO_EN, 0x00) #------------------------------------------------------------------------------------------- # Read ambient temperature #------------------------------------------------------------------------------------------- temp = self.readTemperature() logger.critical("IMU core temp (boot): ,%f", temp / 333.86 + 21.0) def readTemperature(self): temp = self.i2c.readS16(self.__MPU6050_RA_TEMP_OUT_H) return temp def enableFIFOOverflowISR(self): #------------------------------------------------------------------------------------------- # Clear the interrupt status register and enable the FIFO overflow interrupt 0x10 #------------------------------------------------------------------------------------------- self.i2c.write8(self.__MPU6050_RA_INT_ENABLE, 0x10) self.i2c.readU8(self.__MPU6050_RA_INT_STATUS) def disableFIFOOverflowISR(self): #------------------------------------------------------------------------------------------- # Disable the FIFO overflow interrupt. #------------------------------------------------------------------------------------------- self.i2c.write8(self.__MPU6050_RA_INT_ENABLE, 0x00) def numFIFOBatches(self): #------------------------------------------------------------------------------------------- # The FIFO is 512 bytes long, and we're storing 6 signed shorts (ax, ay, az, gx, gy, gz) i.e. # 12 bytes per batch of sensor readings #------------------------------------------------------------------------------------------- fifo_bytes = self.i2c.readU16(self.__MPU6050_RA_FIFO_COUNTH) fifo_batches = int(fifo_bytes / 12) # This rounds down return fifo_batches def readFIFO(self, fifo_batches): #------------------------------------------------------------------------------------------- # Read n x 12 bytes of FIFO data averaging, and return the averaged values and inferred time # based upon the sampling rate and the number of samples. #------------------------------------------------------------------------------------------- ax = 0 ay = 0 az = 0 gx = 0 gy = 0 gz = 0 for ii in range(fifo_batches): sensor_data = [] fifo_batch = self.i2c.readList(self.__MPU6050_RA_FIFO_R_W, 12) for jj in range(0, 12, 2): hibyte = fifo_batch[jj] hibyte = hibyte - 256 if hibyte > 127 else hibyte lobyte = fifo_batch[jj + 1] sensor_data.append((hibyte << 8) + lobyte) ax += sensor_data[0] ay += sensor_data[1] az += sensor_data[2] gx += sensor_data[3] gy += sensor_data[4] gz += sensor_data[5] ''' self.max_az = self.max_az if sensor_data[2] < self.max_az else sensor_data[2] self.min_az = self.min_az if sensor_data[2] > self.min_az else sensor_data[2] self.max_gx = self.max_gx if sensor_data[3] < self.max_gx else sensor_data[3] self.min_gx = self.min_gx if sensor_data[3] > self.min_gx else sensor_data[3] self.max_gy = self.max_gy if sensor_data[4] < self.max_gy else sensor_data[4] self.min_gy = self.min_gy if sensor_data[4] > self.min_gy else sensor_data[4] self.max_gz = self.max_gz if sensor_data[5] < self.max_gz else sensor_data[5] self.min_gz = self.min_gz if sensor_data[5] > self.min_gz else sensor_data[5] ''' return ax / fifo_batches, ay / fifo_batches, az / fifo_batches, gx / fifo_batches, gy / fifo_batches, gz / fifo_batches, fifo_batches / sampling_rate def flushFIFO(self): #------------------------------------------------------------------------------------------- # First shut off the feed in the FIFO. #------------------------------------------------------------------------------------------- self.i2c.write8(self.__MPU6050_RA_FIFO_EN, 0x00) #------------------------------------------------------------------------------------------- # Empty the FIFO by reading whatever is there #------------------------------------------------------------------------------------------- SMBUS_MAX_BUF_SIZE = 32 fifo_bytes = self.i2c.readU16(self.__MPU6050_RA_FIFO_COUNTH) for ii in range(int(fifo_bytes / SMBUS_MAX_BUF_SIZE)): self.i2c.readList(self.__MPU6050_RA_FIFO_R_W, SMBUS_MAX_BUF_SIZE) fifo_bytes = self.i2c.readU16(self.__MPU6050_RA_FIFO_COUNTH) for ii in range(fifo_bytes): self.i2c.readU8(self.__MPU6050_RA_FIFO_R_W) #------------------------------------------------------------------------------------------- # Finally start feeding the FIFO with sensor data again #------------------------------------------------------------------------------------------- self.i2c.write8(self.__MPU6050_RA_FIFO_EN, 0x78) def setGyroOffsets(self, gx, gy, gz): self.gx_offset = gx self.gy_offset = gy self.gz_offset = gz def scaleSensors(self, ax, ay, az, gx, gy, gz): qax = (ax - self.ax_offset) * self.__SCALE_ACCEL qay = (ay - self.ay_offset) * self.__SCALE_ACCEL qaz = (az - self.az_offset) * self.__SCALE_ACCEL qrx = (gx - self.gx_offset) * self.__SCALE_GYRO qry = (gy - self.gy_offset) * self.__SCALE_GYRO qrz = (gz - self.gz_offset) * self.__SCALE_GYRO return qax, qay, qaz, qrx, qry, qrz def initCompass(self): #------------------------------------------------------------------------------------------- # Set up the I2C master pass through. #------------------------------------------------------------------------------------------- int_bypass = self.i2c.readU8(self.__MPU6050_RA_INT_PIN_CFG) self.i2c.write8(self.__MPU6050_RA_INT_PIN_CFG, int_bypass | 0x02) #------------------------------------------------------------------------------------------- # Connect directly to the bypassed magnetometer, and configured it for 16 bit continuous data #------------------------------------------------------------------------------------------- self.i2c_compass = I2C(0x0C) self.i2c_compass.write8(self.__AK893_RA_CNTL1, 0x16); def readCompass(self): compass_bytes = self.i2c_compass.readList(self.__AK893_RA_X_LO, 7) #------------------------------------------------------------------------------------------- # Convert the array of 6 bytes to 3 shorts - 7th byte kicks off another read. # Note compass X, Y, Z are aligned with GPS not IMU i.e. X = 0, Y = 1 => 0 degrees North #------------------------------------------------------------------------------------------- compass_data = [] for ii in range(0, 6, 2): lobyte = compass_bytes[ii] hibyte = compass_bytes[ii + 1] hibyte = hibyte - 256 if hibyte > 127 else hibyte compass_data.append((hibyte << 8) + lobyte) [mgx, mgy, mgz] = compass_data mgx = (mgx - self.mgx_offset) * self.mgx_gain mgy = (mgy - self.mgy_offset) * self.mgy_gain mgz = (mgz - self.mgz_offset) * self.mgz_gain return mgx, mgy, mgz def compassCheckCalibrate(self): rc = True while True: coc = raw_input("'check' or 'calibrate'? ") if coc == "check": self.checkCompass() break elif coc == "calibrate": rc = self.calibrateCompass() break return rc def checkCompass(self): print "Pop me on the ground pointing in a known direction based on another compass." raw_input("Press enter when that's done, and I'll tell you which way I think I'm pointing") self.loadCompassCalibration() mgx, mgy, mgz = self.readCompass() #------------------------------------------------------------------------------- # Convert compass vector into N, S, E, W variants. Get the compass angle in the # range of 0 - 359.99. #------------------------------------------------------------------------------- compass_angle = (math.degrees(math.atan2(mgx, mgy)) + 360) % 360 #------------------------------------------------------------------------------- # There are 16 possible compass directions when you include things like NNE at # 22.5 degrees. #------------------------------------------------------------------------------- compass_points = ("N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE", "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW") num_compass_points = len(compass_points) for ii in range(num_compass_points): angle_range_min = (360 * (ii - 0.5) / num_compass_points) angle_range_max = (360 * (ii + 0.5) / num_compass_points) if compass_angle > angle_range_min and compass_angle <= angle_range_max: break else: ii = 0 # Special case where max < min when north. print "I think I'm pointing %s?" % compass_points[ii] def calibrateCompass(self): self.mgx_offset = 0.0 self.mgy_offset = 0.0 self.mgz_offset = 0.0 self.mgx_gain = 1.0 self.mgy_gain = 1.0 self.mgz_gain = 1.0 offs_rc = False #------------------------------------------------------------------------------------------- # First we need gyro offset calibration. Flush the FIFO, collect roughly half a FIFO full # of samples and feed back to the gyro offset calibrations. #------------------------------------------------------------------------------------------- raw_input("First, put me on a stable surface, and press enter.") mpu6050.flushFIFO() time.sleep(FULL_FIFO_BATCHES / sampling_rate) nfb = mpu6050.numFIFOBatches() qax, qay, qaz, qrx, qry, qrz, dt = mpu6050.readFIFO(nfb) mpu6050.setGyroOffsets(qrx, qry, qrz) print "OK, thanks. That's the gyro calibrated." #------------------------------------------------------------------------------------------- # Open the offset file for this run #------------------------------------------------------------------------------------------- try: with open('CompassOffsets', 'ab') as offs_file: mgx, mgy, mgz = self.readCompass() max_mgx = mgx min_mgx = mgx max_mgy = mgy min_mgy = mgy max_mgz = mgz min_mgz = mgz #----------------------------------------------------------------------------------- # Collect compass X. Y compass values #------------------------------------------------------------------------------- GPIO.output(GPIO_BUZZER, GPIO.LOW) print "Now, pick me up and rotate me horizontally twice until the buzzing stop." raw_input("Press enter when you're ready to go.") self.flushFIFO() yaw = 0.0 total_dt = 0.0 print "ROTATION: ", number_len = 0 #------------------------------------------------------------------------------- # While integrated Z axis gyro < 2 pi i.e. 360 degrees, keep flashing the light #------------------------------------------------------------------------------- while abs(yaw) < 4 * math.pi: time.sleep(10 / sampling_rate) nfb = mpu6050.numFIFOBatches() ax, ay, az, gx, gy, gz, dt = self.readFIFO(nfb) ax, ay, az, gx, gy, gz = self.scaleSensors(ax, ay, az, gx, gy, gz) yaw += gz * dt total_dt += dt mgx, mgy, mgz = self.readCompass() max_mgx = mgx if mgx > max_mgx else max_mgx max_mgy = mgy if mgy > max_mgy else max_mgy min_mgx = mgx if mgx < min_mgx else min_mgx min_mgy = mgy if mgy < min_mgy else min_mgy if total_dt > 0.2: total_dt %= 0.2 number_text = str(abs(int(math.degrees(yaw)))) if len(number_text) == 2: number_text = " " + number_text elif len(number_text) == 1: number_text = " " + number_text print "\b\b\b\b%s" % number_text, sys.stdout.flush() GPIO.output(GPIO_BUZZER, not GPIO.input(GPIO_BUZZER)) print #------------------------------------------------------------------------------- # Collect compass Z values #------------------------------------------------------------------------------- GPIO.output(GPIO_BUZZER, GPIO.LOW) print "\nGreat! Now do the same but with my nose down." raw_input("Press enter when you're ready to go.") self.flushFIFO() rotation = 0.0 total_dt = 0.0 print "ROTATION: ", number_len = 0 #------------------------------------------------------------------------------- # While integrated X+Y axis gyro < 4 pi i.e. 720 degrees, keep flashing the light #------------------------------------------------------------------------------- while abs(rotation) < 4 * math.pi: time.sleep(10 / sampling_rate) nfb = self.numFIFOBatches() ax, ay, az, gx, gy, gz, dt = self.readFIFO(nfb) ax, ay, az, gx, gy, gz = self.scaleSensors(ax, ay, az, gx, gy, gz) rotation += math.pow(math.pow(gx, 2) + math.pow(gy, 2), 0.5) * dt total_dt += dt mgx, mgy, mgz = self.readCompass() max_mgz = mgz if mgz > max_mgz else max_mgz min_mgz = mgz if mgz < min_mgz else min_mgz if total_dt > 0.2: total_dt %= 0.2 number_text = str(abs(int(math.degrees(rotation)))) if len(number_text) == 2: number_text = " " + number_text elif len(number_text) == 1: number_text = " " + number_text print "\b\b\b\b%s" % number_text, sys.stdout.flush() GPIO.output(GPIO_BUZZER, not GPIO.input(GPIO_BUZZER)) print #------------------------------------------------------------------------------- # Turn the light off regardless of the result #------------------------------------------------------------------------------- GPIO.output(GPIO_BUZZER, GPIO.LOW) #------------------------------------------------------------------------------- # Write the good output to file. #------------------------------------------------------------------------------- mgx_offset = (max_mgx + min_mgx) / 2 mgy_offset = (max_mgy + min_mgy) / 2 mgz_offset = (max_mgz + min_mgz) / 2 mgx_gain = 1 / (max_mgx - min_mgx) mgy_gain = 1 / (max_mgy - min_mgy) mgz_gain = 1 / (max_mgz - min_mgz) offs_file.write("%f %f %f %f %f %f\n" % (mgx_offset, mgy_offset, mgz_offset, mgx_gain, mgy_gain, mgz_gain)) #------------------------------------------------------------------------------- # Sanity check. #------------------------------------------------------------------------------- print "\nLooking good, just one last check to confirm all's well." self.checkCompass() print "All done - ready to go!" offs_rc = True except EnvironmentError as e: print "Environment Error: '%s'" % e return offs_rc def loadCompassCalibration(self): self.mgx_offset = 0.0 self.mgy_offset = 0.0 self.mgz_offset = 0.0 self.mgx_gain = 1.0 self.mgy_gain = 1.0 self.mgz_gain = 1.0 offs_rc = False try: with open('CompassOffsets', 'rb') as offs_file: mgx_offset = 0.0 mgy_offset = 0.0 mgz_offset = 0.0 mgx_gain = 1.0 mgy_gain = 1.0 mgz_gain = 1.0 for line in offs_file: mgx_offset, mgy_offset, mgz_offset, mgx_gain, mgy_gain, mgz_gain = line.split() self.mgx_offset = float(mgx_offset) self.mgy_offset = float(mgy_offset) self.mgz_offset = float(mgz_offset) self.mgx_gain = float(mgx_gain) self.mgy_gain = float(mgy_gain) self.mgz_gain = float(mgz_gain) except EnvironmentError: #--------------------------------------------------------------------------------------- # Compass calibration is essential to exclude soft magnetic fields such as from local # metal; enforce a recalibration if not found. #--------------------------------------------------------------------------------------- print "Oops, something went wrong reading the compass offsets file 'CompassOffsets'" print "Have you calibrated it (--cc)?" offs_rc = False else: #--------------------------------------------------------------------------------------- # Calibration results were successful. #--------------------------------------------------------------------------------------- offs_rc = True finally: pass logger.warning("Compass Offsets:, %f, %f, %f, Compass Gains:, %f, %f, %f", self.mgx_offset, self.mgy_offset, self.mgz_offset, self.mgx_gain, self.mgy_gain, self.mgz_gain) return offs_rc def calibrate0g(self): ax_offset = 0.0 ay_offset = 0.0 az_offset = 0.0 offs_rc = False #------------------------------------------------------------------------------------------- # Open the ofset file for this run #------------------------------------------------------------------------------------------- try: with open('0gOffsets', 'ab') as offs_file: raw_input("Rest me on my props and press enter.") self.flushFIFO() time.sleep(FULL_FIFO_BATCHES / sampling_rate) fifo_batches = self.numFIFOBatches() ax, ay, az, gx, gy, gz, dt = self.readFIFO(fifo_batches) offs_file.write("%f %f %f\n" % (ax, ay, az)) except EnvironmentError: pass else: offs_rc = True return offs_rc def load0gCalibration(self): offs_rc = False try: with open('0gOffsets', 'rb') as offs_file: for line in offs_file: ax_offset, ay_offset, az_offset = line.split() self.ax_offset = float(ax_offset) self.ay_offset = float(ay_offset) self.az_offset = float(az_offset) except EnvironmentError: pass else: pass finally: #--------------------------------------------------------------------------------------- # For a while, I thought 0g calibration might help, but actually, it doesn't due to # temperature dependency, so it always returns default values now. #--------------------------------------------------------------------------------------- self.ax_offset = 0.0 self.ay_offset = 0.0 self.az_offset = 0.0 offs_rc = True logger.warning("0g Offsets:, %f, %f, %f", self.ax_offset, self.ay_offset, self.az_offset) return offs_rc def getStats(self): return (self.max_az * self.__SCALE_ACCEL, self.min_az * self.__SCALE_ACCEL, self.max_gx * self.__SCALE_GYRO, self.min_gx * self.__SCALE_GYRO, self.max_gy * self.__SCALE_GYRO, self.min_gy * self.__SCALE_GYRO, self.max_gz * self.__SCALE_GYRO, self.min_gz * self.__SCALE_GYRO) #################################################################################################### # # Garmin LiDAR-Lite v3 range finder # #################################################################################################### class GLLv3: i2c = None __GLL_ACQ_COMMAND = 0x00 __GLL_STATUS = 0x01 __GLL_SIG_COUNT_VAL = 0x02 __GLL_ACQ_CONFIG_REG = 0x04 __GLL_VELOCITY = 0x09 __GLL_PEAK_CORR = 0x0C __GLL_NOISE_PEAK = 0x0D __GLL_SIGNAL_STRENGTH = 0x0E __GLL_FULL_DELAY_HIGH = 0x0F __GLL_FULL_DELAY_LOW = 0x10 __GLL_OUTER_LOOP_COUNT = 0x11 __GLL_REF_COUNT_VAL = 0x12 __GLL_LAST_DELAY_HIGH = 0x14 __GLL_LAST_DELAY_LOW = 0x15 __GLL_UNIT_ID_HIGH = 0x16 __GLL_UNIT_ID_LOW = 0x17 __GLL_I2C_ID_HIGHT = 0x18 __GLL_I2C_ID_LOW = 0x19 __GLL_I2C_SEC_ADDR = 0x1A __GLL_THRESHOLD_BYPASS = 0x1C __GLL_I2C_CONFIG = 0x1E __GLL_COMMAND = 0x40 __GLL_MEASURE_DELAY = 0x45 __GLL_PEAK_BCK = 0x4C __GLL_CORR_DATA = 0x52 __GLL_CORR_DATA_SIGN = 0x53 __GLL_ACQ_SETTINGS = 0x5D __GLL_POWER_CONTROL = 0x65 def __init__(self, address=0x62, rate=10): self.i2c = I2C(address) self.rate = rate #------------------------------------------------------------------------------------------- # Set to continuous sampling after initial read. #------------------------------------------------------------------------------------------- self.i2c.write8(self.__GLL_OUTER_LOOP_COUNT, 0xFF) #------------------------------------------------------------------------------------------- # Set the sampling frequency as 2000 / Hz: # 10Hz = 0xc8 # 20Hz = 0x64 # 100Hz = 0x14 #------------------------------------------------------------------------------------------- self.i2c.write8(self.__GLL_MEASURE_DELAY, int(2000 / rate)) #------------------------------------------------------------------------------------------- # Include receiver bias correction 0x04 #AB: 0x04 | 0x01 should cause (falling edge?) GPIO_GLL_DR_INTERRUPT. Test GPIO handle this? #------------------------------------------------------------------------------------------- self.i2c.write8(self.__GLL_ACQ_COMMAND, 0x04 | 0x01) #------------------------------------------------------------------------------------------- # Acquisition config register: # 0x01 Data ready interrupt # 0x20 Take sampling rate from MEASURE_DELAY #------------------------------------------------------------------------------------------- self.i2c.write8(self.__GLL_ACQ_CONFIG_REG, 0x21) def read(self): #------------------------------------------------------------------------------------------- # Distance is in cm hence the 100s to convert to meters. # Velocity is in cm between consecutive reads; sampling rate converts these to a velocity. # Reading the list from 0x8F seems to get the previous reading, probably cached for the sake # of calculating the velocity next time round. #------------------------------------------------------------------------------------------- distance = self.i2c.readU16(self.__GLL_FULL_DELAY_HIGH) if distance == 1: raise ValueError("GLL out of range") return distance / 100 #################################################################################################### # # Garmin LiDAR-Lite v3HP range finder # #################################################################################################### class GLLv3HP: i2c = None __GLL_ACQ_COMMAND = 0x00 __GLL_STATUS = 0x01 __GLL_SIG_COUNT_VAL = 0x02 __GLL_ACQ_CONFIG_REG = 0x04 __GLL_LEGACY_RESET_EN = 0x06 __GLL_SIGNAL_STRENGTH = 0x0E __GLL_FULL_DELAY_HIGH = 0x0F __GLL_FULL_DELAY_LOW = 0x10 __GLL_REF_COUNT_VAL = 0x12 __GLL_UNIT_ID_HIGH = 0x16 __GLL_UNIT_ID_LOW = 0x17 __GLL_I2C_ID_HIGHT = 0x18 __GLL_I2C_ID_LOW = 0x19 __GLL_I2C_SEC_ADDR = 0x1A __GLL_THRESHOLD_BYPASS = 0x1C __GLL_I2C_CONFIG = 0x1E __GLL_PEAK_STACK_HIGH = 0x26 __GLL_PEAK_STACK_LOW = 0x27 __GLL_COMMAND = 0x40 __GLL_HEALTHY_STATUS = 0x48 __GLL_CORR_DATA = 0x52 __GLL_CORR_DATA_SIGN = 0x53 __GLL_POWER_CONTROL = 0x65 def __init__(self, address=0x62): self.i2c = I2C(address) self.i2c.write8(self.__GLL_SIG_COUNT_VAL, 0x80) self.i2c.write8(self.__GLL_ACQ_CONFIG_REG, 0x08) self.i2c.write8(self.__GLL_REF_COUNT_VAL, 0x05) self.i2c.write8(self.__GLL_THRESHOLD_BYPASS, 0x00) def read(self): acquired = False # Trigger acquisition self.i2c.write8(self.__GLL_ACQ_COMMAND, 0x01) # Poll acquired? while not acquired: acquired = not (self.i2c.readU8(self.__GLL_STATUS) & 0x01) else: distance = self.i2c.readU16(self.__GLL_FULL_DELAY_HIGH) if distance == 0: raise ValueError("GLL out of range") return distance / 100 #################################################################################################### # # PID algorithm to take input sensor readings, and target requirements, and output an arbirtrary # corrective value. # #################################################################################################### class PID: def __init__(self, p_gain, i_gain, d_gain): self.last_error = 0.0 self.p_gain = p_gain self.i_gain = i_gain self.d_gain = d_gain self.i_error = 0.0 def Error(self, input, target): return (target - input) def Compute(self, input, target, dt): #------------------------------------------------------------------------------------------- # Error is what the PID alogithm acts upon to derive the output #------------------------------------------------------------------------------------------- error = self.Error(input, target) #------------------------------------------------------------------------------------------- # The proportional term takes the distance between current input and target # and uses this proportially (based on Kp) to control the ESC pulse width #------------------------------------------------------------------------------------------- p_error = error #------------------------------------------------------------------------------------------- # The integral term sums the errors across many compute calls to allow for # external factors like wind speed and friction #------------------------------------------------------------------------------------------- self.i_error += (error + self.last_error) * dt i_error = self.i_error #------------------------------------------------------------------------------------------- # The differential term accounts for the fact that as error approaches 0, # the output needs to be reduced proportionally to ensure factors such as # momentum do not cause overshoot. #------------------------------------------------------------------------------------------- d_error = (error - self.last_error) / dt #------------------------------------------------------------------------------------------- # The overall output is the sum of the (P)roportional, (I)ntegral and (D)iffertial terms #------------------------------------------------------------------------------------------- p_output = self.p_gain * p_error i_output = self.i_gain * i_error d_output = self.d_gain * d_error #------------------------------------------------------------------------------------------- # Store off last error for integral and differential processing next time. #------------------------------------------------------------------------------------------- self.last_error = error #------------------------------------------------------------------------------------------- # Return the output, which has been tuned to be the increment / decrement in ESC PWM #------------------------------------------------------------------------------------------- return p_output, i_output, d_output #################################################################################################### # # PID algorithm subclass to come with the yaw angles error calculations. # #################################################################################################### class YAW_PID(PID): def Error(self, input, target): #------------------------------------------------------------------------------------------- # target and input are in the 0 - 2 pi range. This is asserted. Results are in the +/- pi # range to make sure we spin the shorted way. #------------------------------------------------------------------------------------------- assert (abs(input) <= math.pi), "yaw input out of range %f" % math.degrees(input) assert (abs(target) <= math.pi), "yaw target out of range %f" % math.degrees(target) error = ((target - input) + math.pi) % (2 * math.pi) - math.pi return error #################################################################################################### # # Class for managing each blade + motor configuration via its ESC # #################################################################################################### class ESC: def __init__(self, pin, location, rotation, name): #------------------------------------------------------------------------------------------- # The GPIO BCM numbered pin providing PWM signal for this ESC #------------------------------------------------------------------------------------------- self.bcm_pin = pin #------------------------------------------------------------------------------------------- # Physical parameters of the ESC / motors / propellers #------------------------------------------------------------------------------------------- self.motor_location = location self.motor_rotation = rotation #------------------------------------------------------------------------------------------- # Name - for logging purposes only #------------------------------------------------------------------------------------------- self.name = name #------------------------------------------------------------------------------------------- # Pulse width - for logging purposes only #------------------------------------------------------------------------------------------- self.pulse_width = 0 #------------------------------------------------------------------------------------------- # Initialize the RPIO DMA PWM for this ESC. #------------------------------------------------------------------------------------------- self.set(1000) def set(self, pulse_width): pulse_width = pulse_width if pulse_width >= 1000 else 1000 pulse_width = pulse_width if pulse_width <= 1999 else 1999 self.pulse_width = pulse_width PWM.add_channel_pulse(RPIO_DMA_CHANNEL, self.bcm_pin, 0, pulse_width) #################################################################################################### # # Get the rotation angles of pitch, roll and yaw from the fixed point of earth reference frame # gravity + lateral orientation (ultimately compass derived, but currently just the take-off # orientation) of 0, 0, 1 compared to where gravity is distrubuted across the X, Y and Z axes of the # accelerometer all based upon the right hand rule. # #################################################################################################### def GetRotationAngles(ax, ay, az): #----------------------------------------------------------------------------------------------- # What's the angle in the x and y plane from horizontal in radians? #----------------------------------------------------------------------------------------------- pitch = math.atan2(-ax, math.pow(math.pow(ay, 2) + math.pow(az, 2), 0.5)) roll = math.atan2(ay, az) return pitch, roll #################################################################################################### # # Absolute angles of tilt compared to the earth gravity reference frame. # #################################################################################################### def GetAbsoluteAngles(ax, ay, az): pitch = math.atan2(-ax, az) roll = math.atan2(ay, az) return pitch, roll #################################################################################################### # # Convert a body frame rotation rate to the rotation frames # #################################################################################################### def Body2EulerRates(qry, qrx, qrz, pa, ra): #=============================================================================================== # Axes: Convert a set of gyro body frame rotation rates into Euler frames # # Matrix # --------- # |err| | 1 , sin(ra) * tan(pa) , cos(ra) * tan(pa) | |qrx| # |epr| = | 0 , cos(ra) , -sin(ra) | |qry| # |eyr| | 0 , sin(ra) / cos(pa) , cos(ra) / cos(pa) | |qrz| # #=============================================================================================== c_pa = math.cos(pa) t_pa = math.tan(pa) c_ra = math.cos(ra) s_ra = math.sin(ra) err = qrx + qry * s_ra * t_pa + qrz * c_ra * t_pa epr = qry * c_ra - qrz * s_ra eyr = qry * s_ra / c_pa + qrz * c_ra / c_pa return epr, err, eyr #################################################################################################### # # Rotate a vector using Euler angles wrt Earth frame co-ordinate system, for example to take the # earth frame target flight plan vectors, and move it to the quad frame orientations vectors. # #################################################################################################### def RotateVector(evx, evy, evz, pa, ra, ya): #=============================================================================================== # Axes: Convert a vector from earth- to quadcopter frame # # Matrix # --------- # |qvx| | cos(pa) * cos(ya), cos(pa) * sin(ya), -sin(pa) | |evx| # |qvy| = | sin(ra) * sin(pa) * cos(ya) - cos(ra) * sin(ya), sin(ra) * sin(pa) * sin(ya) + cos(ra) * cos(ya), sin(ra) * cos(pa)| |evy| # |qvz| | cos(ra) * sin(pa) * cos(ya) + sin(ra) * sin(ya), cos(ra) * sin(pa) * sin(ya) - sin(ra) * cos(ya), cos(pa) * cos(ra)| |evz| # #=============================================================================================== c_pa = math.cos(pa) s_pa = math.sin(pa) c_ra = math.cos(ra) s_ra = math.sin(ra) c_ya = math.cos(ya) s_ya = math.sin(ya) qvx = evx * c_pa * c_ya + evy * c_pa * s_ya - evz * s_pa qvy = evx * (s_ra * s_pa * c_ya - c_ra * s_ya) + evy * (s_ra * s_pa * s_ya + c_ra * c_ya) + evz * s_ra * c_pa qvz = evx * (c_ra * s_pa * c_ya + s_ra * s_ya) + evy * (c_ra * s_pa * s_ya - s_ra * c_ya) + evz * c_pa * c_ra return qvx, qvy, qvz #################################################################################################### # # Butterwork IIR Filter calculator and actor - this is carried out in the earth frame as we are track # gravity drift over time from 0, 0, 1 (the primer values for egx, egy and egz) # # Code is derived from http://www.exstrom.com/journal/sigproc/bwlpf.c # #################################################################################################### class BUTTERWORTH: def __init__(self, sampling, cutoff, order, primer): self.n = int(round(order / 2)) self.A = [] self.d1 = [] self.d2 = [] self.w0 = [] self.w1 = [] self.w2 = [] a = math.tan(math.pi * cutoff / sampling) a2 = math.pow(a, 2.0) for ii in range(0, self.n): r = math.sin(math.pi * (2.0 * ii + 1.0) / (4.0 * self.n)) s = a2 + 2.0 * a * r + 1.0 self.A.append(a2 / s) self.d1.append(2.0 * (1 - a2) / s) self.d2.append(-(a2 - 2.0 * a * r + 1.0) / s) self.w0.append(primer / (self.A[ii] * 4)) self.w1.append(primer / (self.A[ii] * 4)) self.w2.append(primer / (self.A[ii] * 4)) def filter(self, input): for ii in range(0, self.n): self.w0[ii] = self.d1[ii] * self.w1[ii] + self.d2[ii] * self.w2[ii] + input output = self.A[ii] * (self.w0[ii] + 2.0 * self.w1[ii] + self.w2[ii]) self.w2[ii] = self.w1[ii] self.w1[ii] = self.w0[ii] return output #################################################################################################### # # Initialize hardware PWM # #################################################################################################### RPIO_DMA_CHANNEL = 1 def PWMInit(): #----------------------------------------------------------------------------------------------- # Set up the globally shared single PWM channel #----------------------------------------------------------------------------------------------- PWM.set_loglevel(PWM.LOG_LEVEL_ERRORS) PWM.setup(1) # 1us resolution pulses PWM.init_channel(RPIO_DMA_CHANNEL, 3000) # pulse every 3ms #################################################################################################### # # Cleanup hardware PWM # #################################################################################################### def PWMTerm(): PWM.cleanup() #################################################################################################### # # GPIO pins initialization for MPU6050 FIFO overflow interrupt # #################################################################################################### def GPIOInit(FIFOOverflowISR): GPIO.setmode(GPIO.BCM) GPIO.setup(GPIO_FIFO_OVERFLOW_INTERRUPT, GPIO.IN, GPIO.PUD_OFF) GPIO.add_event_detect(GPIO_FIFO_OVERFLOW_INTERRUPT, GPIO.RISING) #, FIFOOverflowISR) #AB: GPIO.setup(GPIO_POWER_BROWN_OUT_INTERRUPT, GPIO.IN, GPIO.PUD_OFF) #AB: GPIO.add_event_detect(GPIO_POWER_BROWN_OUT_INTERRUPT, GPIO.FALLING) ''' #AB! Regardless of the (UP, OFF, DOWN) * (RISING, FALLING), none of these option raise a DR interrupt #AB! in v3. v3HP seems to work at a glance. ''' GPIO.setup(GPIO_GLL_DR_INTERRUPT, GPIO.IN, GPIO.PUD_DOWN) GPIO.add_event_detect(GPIO_GLL_DR_INTERRUPT, GPIO.FALLING) GPIO.setup(GPIO_BUZZER, GPIO.OUT) GPIO.output(GPIO_BUZZER, GPIO.LOW) #################################################################################################### # # GPIO pins cleanup for MPU6050 FIFO overflow interrupt # #################################################################################################### def GPIOTerm(): #AB: GPIO.remove_event_detect(GPIO_FIFO_OVERFLOW_INTERRUPT) GPIO.remove_event_detect(GPIO_GLL_DR_INTERRUPT) GPIO.cleanup() #################################################################################################### # # Check CLI validity, set calibrate_sensors / fly or sys.exit(1) # #################################################################################################### def CheckCLI(argv): cli_fly = False cli_hover_pwm = 1000 #----------------------------------------------------------------------------------------------- # Other configuration defaults #----------------------------------------------------------------------------------------------- cli_test_case = 0 cli_diagnostics = False cli_tau = 7.5 cli_calibrate_0g = False cli_fp_filename = '' cli_cc_compass = False cli_file_control = False cli_yaw_control = False cli_gps_control = False cli_add_waypoint = False cli_clear_waypoints = False cli_rc_control = False hover_pwm_defaulted = True #----------------------------------------------------------------------------------------------- # Defaults for vertical distance PIDs #----------------------------------------------------------------------------------------------- cli_vdp_gain = 1.0 cli_vdi_gain = 0.0 cli_vdd_gain = 0.0 #----------------------------------------------------------------------------------------------- # Defaults for horizontal distance PIDs #----------------------------------------------------------------------------------------------- cli_hdp_gain = 1.0 cli_hdi_gain = 0.0 cli_hdd_gain = 0.0 #----------------------------------------------------------------------------------------------- # Defaults for horizontal velocity PIDs #----------------------------------------------------------------------------------------------- cli_hvp_gain = 1.5 cli_hvi_gain = 0.0 cli_hvd_gain = 0.0 #----------------------------------------------------------------------------------------------- # Per frame specific values. This is the only place where PID integrals are used to compansate # for stable forces such as gravity, weight imbalance in the frame. Yaw is included here to # account for frame unique momentum for required for rotation; however this does not need a # integral as there should not be a constant force that needs to be counteracted. #----------------------------------------------------------------------------------------------- if i_am_hermione or i_am_penelope: #------------------------------------------------------------------------------------------- # Hermione's PID configuration due to using her frame / ESCs / motors / props #------------------------------------------------------------------------------------------- cli_hover_pwm = 1600 #------------------------------------------------------------------------------------------- # Defaults for vertical velocity PIDs. #------------------------------------------------------------------------------------------- cli_vvp_gain = 360.0 cli_vvi_gain = 180.0 cli_vvd_gain = 0.0 #------------------------------------------------------------------------------------------- # Defaults for pitch rotation rate PIDs #------------------------------------------------------------------------------------------- cli_prp_gain = 100.0 cli_pri_gain = 1.0 cli_prd_gain = 0.0 #------------------------------------------------------------------------------------------- # Defaults for roll rotation rate PIDs #------------------------------------------------------------------------------------------- cli_rrp_gain = 100.0 cli_rri_gain = 1.0 cli_rrd_gain = 0.0 #------------------------------------------------------------------------------------------- # Defaults for yaw rotation rate PIDs #------------------------------------------------------------------------------------------- cli_yrp_gain = 180.0 cli_yri_gain = 1.8 cli_yrd_gain = 0.0 elif i_am_zoe: #------------------------------------------------------------------------------------------- # Zoe's PID configuration due to using her ESCs / motors / props #------------------------------------------------------------------------------------------- ''' #------------------------------------------------------------------------------------------- # T-motor antiGravity 9030 CF white props #------------------------------------------------------------------------------------------- cli_hover_pwm = 1300 #------------------------------------------------------------------------------------------- # Defaults for vertical velocity PIDs #------------------------------------------------------------------------------------------- cli_vvp_gain = 300.0 cli_vvi_gain = 150.0 cli_vvd_gain = 0.0 #------------------------------------------------------------------------------------------- # Defaults for pitch angle PIDs #------------------------------------------------------------------------------------------- cli_prp_gain = 16.0 cli_pri_gain = 0.16 cli_prd_gain = 0.0 #------------------------------------------------------------------------------------------- # Defaults for roll angle PIDs #------------------------------------------------------------------------------------------- cli_rrp_gain = 15.0 cli_rri_gain = 0.15 cli_rrd_gain = 0.0 #------------------------------------------------------------------------------------------- # Defaults for yaw angle PIDs #------------------------------------------------------------------------------------------- cli_yrp_gain = 40.0 cli_yri_gain = 0.4 cli_yrd_gain = 0.0 ''' #------------------------------------------------------------------------------------------- # GEMFAN 6040BC 3 Blade Nylon white props #------------------------------------------------------------------------------------------- cli_hover_pwm = 1450 #------------------------------------------------------------------------------------------- # Defaults for vertical velocity PIDs #------------------------------------------------------------------------------------------- cli_vvp_gain = 300.0 cli_vvi_gain = 150.0 cli_vvd_gain = 0.0 #------------------------------------------------------------------------------------------- # Defaults for pitch angle PIDs #------------------------------------------------------------------------------------------- cli_prp_gain = 35.0 cli_pri_gain = 0.35 cli_prd_gain = 0.0 #------------------------------------------------------------------------------------------- # Defaults for roll angle PIDs #------------------------------------------------------------------------------------------- cli_rrp_gain = 25.0 cli_rri_gain = 0.25 cli_rrd_gain = 0.0 #------------------------------------------------------------------------------------------- # Defaults for yaw angle PIDs #------------------------------------------------------------------------------------------- cli_yrp_gain = 50.0 cli_yri_gain = 5.0 cli_yrd_gain = 0.0 #----------------------------------------------------------------------------------------------- # Right, let's get on with reading the command line and checking consistency #----------------------------------------------------------------------------------------------- try: opts, args = getopt.getopt(argv,'df:gh:y', ['cc', 'rc', 'tc=', 'awp', 'cwp', 'gps', 'tau=', 'vdp=', 'vdi=', 'vdd=', 'vvp=', 'vvi=', 'vvd=', 'hdp=', 'hdi=', 'hdd=', 'hvp=', 'hvi=', 'hvd=', 'prp=', 'pri=', 'prd=', 'rrp=', 'rri=', 'rrd=', 'tau=', 'yrp=', 'yri=', 'yrd=']) except getopt.GetoptError: logger.critical('Must specify one of -f, --gps, --awp, --cwp, --cc or --tc') logger.critical(' sudo python ./qc.py') logger.critical(' -f set the flight plan CSV file') logger.critical(' -h set the hover PWM pulse width - default: %dus', cli_hover_pwm) logger.critical(' -d enable diagnostics') logger.critical(' -g calibrate X, Y axis 0g - futile, ignore!') logger.critical(' -y use yaw to control the direction of flight') logger.critical(' --cc check or calibrate compass') logger.critical(' --rc use the human control RC') logger.critical(' --tc select which testcase to run') logger.critical(' --awp add GPS waypoint to flight plan') logger.critical(' --cwp clear GPS waypoints from flight plan') logger.critical(' --gps use the GPS waypoint flight plan') logger.critical(' --tau set the angle CF -3dB point - default: %fs', cli_tau) logger.critical(' --vdp set vertical distance PID P gain - default: %f', cli_vvp_gain) logger.critical(' --vdi set vertical distance PID I gain - default: %f', cli_vvi_gain) logger.critical(' --vdd set vertical distance PID D gain - default: %f', cli_vvd_gain) logger.critical(' --vvp set vertical speed PID P gain - default: %f', cli_vvp_gain) logger.critical(' --vvi set vertical speed PID I gain - default: %f', cli_vvi_gain) logger.critical(' --vvd set vertical speed PID D gain - default: %f', cli_vvd_gain) logger.critical(' --hdp set horizontal speed PID P gain - default: %f', cli_hdp_gain) logger.critical(' --hdi set horizontal speed PID I gain - default: %f', cli_hdi_gain) logger.critical(' --hdd set horizontal speed PID D gain - default: %f', cli_hdd_gain) logger.critical(' --hvp set horizontal speed PID P gain - default: %f', cli_hvp_gain) logger.critical(' --hvi set horizontal speed PID I gain - default: %f', cli_hvi_gain) logger.critical(' --hvd set horizontal speed PID D gain - default: %f', cli_hvd_gain) logger.critical(' --prp set pitch rotation rate PID P gain - default: %f', cli_prp_gain) logger.critical(' --pri set pitch rotation rate PID I gain - default: %f', cli_pri_gain) logger.critical(' --prd set pitch rotation rate PID D gain - default: %f', cli_prd_gain) logger.critical(' --rrp set roll rotation rate PID P gain - default: %f', cli_rrp_gain) logger.critical(' --rri set roll rotation rate PID I gain - default: %f', cli_rri_gain) logger.critical(' --rrd set roll rotation rate PID D gain - default: %f', cli_rrd_gain) logger.critical(' --yrp set yaw rotation rate PID P gain - default: %f', cli_yrp_gain) logger.critical(' --yri set yaw rotation rate PID I gain - default: %f', cli_yri_gain) logger.critical(' --yrd set yaw rotation rate PID D gain - default: %f', cli_yrd_gain) raise ValueError("Invalid command line") for opt, arg in opts: if opt == '-f': cli_fly = True cli_file_control = True cli_fp_filename = arg elif opt in '-h': cli_hover_pwm = int(arg) hover_pwm_defaulted = False elif opt in '-d': cli_diagnostics = True elif opt in '-g': cli_calibrate_0g = True elif opt in '-y': cli_yaw_control = True elif opt in '--cc': cli_cc_compass = True elif opt in '--rc': cli_fly = True cli_rc_control = True elif opt in '--tc': cli_test_case = int(arg) elif opt in '--awp': cli_add_waypoint = True elif opt in '--cwp': cli_clear_waypoints = True elif opt in '--gps': cli_fly = True cli_gps_control = True cli_fp_filename = "GPSWaypoints.csv" elif opt in '--tau': cli_tau = float(arg) elif opt in '--vdp': cli_vdp_gain = float(arg) elif opt in '--vdi': cli_vdi_gain = float(arg) elif opt in '--vdd': cli_vdd_gain = float(arg) elif opt in '--vvp': cli_vvp_gain = float(arg) elif opt in '--vvi': cli_vvi_gain = float(arg) elif opt in '--vvd': cli_vvd_gain = float(arg) elif opt in '--hdp': cli_hdp_gain = float(arg) elif opt in '--hdi': cli_hdi_gain = float(arg) elif opt in '--hdd': cli_hdd_gain = float(arg) elif opt in '--hvp': cli_hvp_gain = float(arg) elif opt in '--hvi': cli_hvi_gain = float(arg) elif opt in '--hvd': cli_hvd_gain = float(arg) elif opt in '--prp': cli_prp_gain = float(arg) elif opt in '--pri': cli_pri_gain = float(arg) elif opt in '--prd': cli_prd_gain = float(arg) elif opt in '--rrp': cli_rrp_gain = float(arg) elif opt in '--rri': cli_rri_gain = float(arg) elif opt in '--rrd': cli_rrd_gain = float(arg) elif opt in '--yrp': cli_yrp_gain = float(arg) elif opt in '--yri': cli_yri_gain = float(arg) elif opt in '--yrd': cli_yrd_gain = float(arg) if not cli_fly and cli_test_case == 0 and not cli_calibrate_0g and not cli_cc_compass and not cli_add_waypoint and not cli_clear_waypoints: raise ValueError('Must specify one of -f, --awp, --cwp, --gps, --tc or --cc') elif cli_hover_pwm < 1000 or cli_hover_pwm > 1999: raise ValueError('Hover speed must lie in the following range: 1000 <= hover pwm < 2000') elif cli_test_case == 0 and cli_fly: if not (cli_file_control ^ cli_gps_control ^ cli_rc_control): raise ValueError('Only one of file, gps or rc control may be chosen') elif cli_file_control and not os.path.isfile(cli_fp_filename): raise ValueError('The flight plan file "%s" does not exist.' % cli_fp_filename) elif cli_gps_control and not os.path.isfile("GPSWaypoints.csv"): raise ValueError('We need at least the target waypoint set for GPS flight control') print 'Pre-flight checks passed, enjoy your flight, sir!' elif cli_test_case == 0 and cli_calibrate_0g: print 'Proceeding with 0g calibration' elif cli_test_case == 0 and cli_cc_compass: print "Proceeding with compass calibration" elif cli_test_case == 0 and cli_add_waypoint: print "Proceeding with GPS waypoint acquisition" elif cli_test_case == 0 and cli_clear_waypoints: print "Proceeding with GPS waypoint clearance" elif cli_test_case != 1 and cli_test_case != 2: raise ValueError('Only 1 or 2 are valid testcases') elif cli_test_case == 1 and hover_pwm_defaulted: raise ValueError('You must choose a specific hover speed (-h) for test case 1 - try 1150') return cli_fp_filename, cli_calibrate_0g, cli_cc_compass, cli_yaw_control, cli_file_control, cli_rc_control, cli_gps_control, cli_add_waypoint, cli_clear_waypoints, cli_hover_pwm, cli_vdp_gain, cli_vdi_gain, cli_vdd_gain, cli_vvp_gain, cli_vvi_gain, cli_vvd_gain, cli_hdp_gain, cli_hdi_gain, cli_hdd_gain, cli_hvp_gain, cli_hvi_gain, cli_hvd_gain, cli_prp_gain, cli_pri_gain, cli_prd_gain, cli_rrp_gain, cli_rri_gain, cli_rrd_gain, cli_yrp_gain, cli_yri_gain, cli_yrd_gain, cli_test_case, cli_tau, cli_diagnostics #################################################################################################### # # Flight plan management. Only used by an Pi0W as it only has a single CPU. # #################################################################################################### class FlightPlan(): X = 0 Y = 1 Z = 2 PERIOD = 3 NAME = 4 def __init__(self, quadcopter, fp_filename): self.quadcopter = quadcopter self.fp_prev_index = 0 self.elapsed_time = 0.0 self.fp = [] self.fp.append((0.0, 0.0, 0.0, 0.0, "RTF")) self.fp.append((0.0, 0.0, 0.5, 2.0, "TAKEOFF")) self.fp.append((0.0, 0.0, 0.0, 0.5, "HOVER")) self.edx_target = 0.0 self.edy_target = 0.0 self.edz_target = 0.0 with open(fp_filename, 'rb') as fp_csv: fp_reader = csv.reader(fp_csv) for fp_row in fp_reader: if len(fp_row) == 0 or (fp_row[0] != '' and fp_row[0][0] == '#'): continue if len(fp_row) != 5: break self.fp.append((float(fp_row[self.X]), float(fp_row[self.Y]), float(fp_row[self.Z]), float(fp_row[self.PERIOD]), fp_row[self.NAME].strip())) else: self.fp.append((0.0, 0.0, -0.25, 5.0, "LANDING")) # Extended landed for safety self.fp.append((0.0, 0.0, 0.0, 0.0, "STOP")) return raise ValueError("Error in CSV file; '%s'" % fp_row) def getTargets(self, delta_time): self.elapsed_time += delta_time fp_total_time = 0.0 for fp_index in range(len(self.fp)): fp_total_time += self.fp[fp_index][self.PERIOD] if self.elapsed_time < fp_total_time: break else: self.quadcopter.keep_looping = False if fp_index != self.fp_prev_index: logger.critical("%s", self.fp[fp_index][self.NAME]) self.fp_prev_index = fp_index evx_target = self.fp[fp_index][self.X] evy_target = self.fp[fp_index][self.Y] evz_target = self.fp[fp_index][self.Z] self.edx_target += evx_target * delta_time self.edy_target += evy_target * delta_time self.edz_target += evz_target * delta_time return evx_target, evy_target, evz_target, self.edx_target, self.edy_target, self.edz_target #################################################################################################### # # Functions to lock memory to prevent paging, and move child processes in different process groups # such that a Ctrl-C / SIGINT to one isn't distributed automatically to all children. # #################################################################################################### MCL_CURRENT = 1 MCL_FUTURE = 2 def mlockall(flags = MCL_CURRENT| MCL_FUTURE): libc_name = ctypes.util.find_library("c") libc = ctypes.CDLL(libc_name, use_errno=True) result = libc.mlockall(flags) if result != 0: raise Exception("cannot lock memory, errno=%s" % ctypes.get_errno()) def munlockall(): libc_name = ctypes.util.find_library("c") libc = ctypes.CDLL(libc_name, use_errno=True) result = libc.munlockall() if result != 0: raise Exception("cannot lock memory, errno=%s" % ctypes.get_errno()) def Daemonize(): #----------------------------------------------------------------------------------------------- # Discondect child processes so ctrl-C doesn't kill them # Increment priority such that Motion is -10, Autopilot and Video are -5, and Sweep and GPS are 0. #----------------------------------------------------------------------------------------------- os.setpgrp() os.nice(5) ''' #AB: ########################################################################################### #AB: # Consider here munlockall() to allow paging for lower priority processes i.e. all be main and video #AB: ########################################################################################### ''' #################################################################################################### # # Start the Scanse Sweep reading process. # #################################################################################################### def SweepProcessor(): SWEEP_IGNORE_BOUNDARY = 0.5 # 50cm from Sweep central and the prop tips. SWEEP_CRITICAL_BOUNDARY = 1.0 # 50cm or less beyond the ignore zone: Hermione's personal space encroached. SWEEP_WARNING_BOUNDARY = 1.5 # 50cm or less beyond the critical zone: Pause for thought what to do next. sent_critical = False warning_distance = 0.0 previous_degrees = 360.0 start_time = time.time() loops = 0 samples = 0 distance = 0.0 direction = 0.0 warning_distance = SWEEP_WARNING_BOUNDARY warning_radians = 0.0 with serial.Serial("/dev/ttySWEEP", baudrate = 115200, parity = serial.PARITY_NONE, bytesize = serial.EIGHTBITS, stopbits = serial.STOPBITS_ONE, xonxoff = False, rtscts = False, dsrdtr = False) as sweep: try: sweep.write("ID\n") resp = sweep.readline() sweep.write("DS\n") resp = sweep.readline() assert (len(resp) == 6), "SWEEP: Bad data" status = resp[2:4] assert status == "00", "SWEEP: Failed %s" % status with io.open("/dev/shm/sweep_stream", mode = "wb", buffering = 0) as sweep_fifo: log = open("sweep.csv", "wb") log.write("angle, distance, x, y\n") unpack_format = '=' + 'B' * 7 unpack_size = struct.calcsize(unpack_format) pack_format = '=??ff' while True: raw = sweep.read(unpack_size) assert (len(raw) == unpack_size), "Bad data read: %d" % len(raw) #------------------------------------------------------------------------------- # Sweep is spinning at 5Hz sampling at 600Hz. For large object detection within # SWEEP_CRITICAL range, we can discard 80% of all samples, hopefully providing # more efficient processing and limiting what's sent to the Autopilot. #AB: 600 samples in 1 seconds at 5 circles per seconds = resolution of 3 degrees. #AB: Hence 5 below = 15 degrees checking #------------------------------------------------------------------------------- samples += 1 if samples % 5 != 0: continue formatted = struct.unpack(unpack_format, raw) assert (len(formatted) == 7), "Bad data type conversion: %d" % len(formatted) #------------------------------------------------------------------------------- # Read the azimuth and convert to degrees. #------------------------------------------------------------------------------- azimuth_lo = formatted[1] azimuth_hi = formatted[2] angle_int = (azimuth_hi << 8) + azimuth_lo degrees = (angle_int >> 4) + (angle_int & 15) / 16 ''' #AB: ########################################################################### #AB: # SIX SERIAL REFLECTION FROM THE WIFI ANTENNA TAKES ITS 15CM DISTANCE TO 90CM #AB: # SMACK BANG IN THE CRITICAL ZONE!!! HENCE WE IGNORE THE RANGE OF ANGLES IT #AB: # IS SEEN IN!! #AB: ########################################################################### ''' if degrees > 95 and degrees < 97: continue #------------------------------------------------------------------------------- # We only send one warning and critical per loop (~0.2s); warnings happen at the start # of a new loop, criticals immediately. #------------------------------------------------------------------------------- if degrees < previous_degrees: loops += 1 output = None #--------------------------------------------------------------------------- # Did we get a proximity warning last loop? Send it if so. #--------------------------------------------------------------------------- if warning_distance < SWEEP_WARNING_BOUNDARY: output = struct.pack(pack_format, False, True, warning_distance, warning_radians) log_string = "WARNING: %fm @ %f degrees.\n" % (warning_distance , math.degrees(warning_radians) % 360) #--------------------------------------------------------------------------- # Have we already sent a critical proximity? No? Then all's clear. #AB: This could be improved; there's only a need to send a NONE if the previous loop #AB: sent a WARNING previously, and no WARNING this time round. #--------------------------------------------------------------------------- elif not sent_critical: output = struct.pack(pack_format, False, False, 0.0, 0.0) log_string = "PROXIMITY: %fm @ %f degrees.\n" % (distance, degrees % 360) if output != None: sweep_fifo.write(output) log.write(log_string) warning_distance = SWEEP_WARNING_BOUNDARY sent_critical = False previous_degrees = degrees #------------------------------------------------------------------------------- # Sweep rotates ACW = - 360, which when slung underneath equates to CW in the piDrone # frame POV. Convert to radians and set range to +/- pi radians. #------------------------------------------------------------------------------- radians = -((math.radians(degrees) + math.pi) % (2 * math.pi) - math.pi) #------------------------------------------------------------------------------- # Read the distance and convert to meters. #------------------------------------------------------------------------------- distance_lo = formatted[3] distance_hi = formatted[4] distance = ((distance_hi << 8) + distance_lo) / 100 ''' #------------------------------------------------------------------------------- # Convert the results to a vector aligned with quad frame. #------------------------------------------------------------------------------- x = distance * math.cos(radians) y = distance * math.sin(radians) log.write("%f, %f, %f, %f\n" % (degrees, distance, x, y)) ''' #------------------------------------------------------------------------------- # If a reported distance lies inside the danger zone, pass it over to the autopilot # to react to. #------------------------------------------------------------------------------- if distance < SWEEP_IGNORE_BOUNDARY: pass elif distance < SWEEP_CRITICAL_BOUNDARY and not sent_critical: output = struct.pack(pack_format, True, False, distance, radians) sweep_fifo.write(output) log.write("CRITICAL: %fm @ %f degrees.\n" % (distance, degrees % 360)) sent_critical = True elif distance < SWEEP_WARNING_BOUNDARY and warning_distance > distance: warning_distance = distance warning_radians = radians #------------------------------------------------------------------------------------------- # Catch Ctrl-C - the 'with' wrapped around the FIFO should have closed that by here. Has it? #------------------------------------------------------------------------------------------- except KeyboardInterrupt as e: if not sweep_fifo.closed: print "Sweep FIFO not closed! WTF!" #------------------------------------------------------------------------------------------- # Catch incorrect assumption bugs #------------------------------------------------------------------------------------------- except AssertionError as e: print e #------------------------------------------------------------------------------------------- # Cleanup regardless otherwise the next run picks up data from this #------------------------------------------------------------------------------------------- finally: sweep.write("DX\n") resp = sweep.read() log.write("Sweep loops: %d\n" % loops) log.write("Time taken: %f\n" % (time.time() - start_time)) log.write("Samples: %d\n" % samples) log.close() #################################################################################################### # # Process the Scanse Sweep data. # #################################################################################################### class SweepManager(): def __init__(self): #------------------------------------------------------------------------------------------- # Setup a shared memory based data stream for the Sweep output #------------------------------------------------------------------------------------------- os.mkfifo("/dev/shm/sweep_stream") self.sweep_process = subprocess.Popen(["python", __file__, "SWEEP"], preexec_fn = Daemonize) while True: try: self.sweep_fifo = io.open("/dev/shm/sweep_stream", mode="rb") except: continue else: break self.unpack_format = "=??ff" self.unpack_size = struct.calcsize(self.unpack_format) def flush(self): #------------------------------------------------------------------------------------------- # Read what should be the backlog of reads, and return how many there are. #------------------------------------------------------------------------------------------- raw_bytes = self.sweep_fifo.read(self.unpack_size) assert (len(raw_bytes) % self.unpack_size == 0), "Incomplete Sweep data received" return int(len(raw_bytes) / self.unpack_size) def read(self): raw_bytes = self.sweep_fifo.read(self.unpack_size) assert (len(raw_bytes) == self.unpack_size), "Incomplete data received from Sweep reader" critical, warning, distance, direction = struct.unpack(self.unpack_format, raw_bytes) return critical, warning, distance, direction def cleanup(self): #------------------------------------------------------------------------------------------- # Stop the Sweep process if it's still running, and clean up the FIFO. #------------------------------------------------------------------------------------------- try: if self.sweep_process.poll() == None: self.sweep_process.send_signal(signal.SIGINT) self.sweep_process.wait() except KeyboardInterrupt as e: pass self.sweep_fifo.close() os.unlink("/dev/shm/sweep_stream") #################################################################################################### # # Start the GPS reading process. # #################################################################################################### def GPSProcessor(): session = gps.gps() session.stream(gps.WATCH_ENABLE | gps.WATCH_NEWSTYLE) num_sats = 0 num_used_sats = 0 latitude = 0.0 altitude = 0.0 longitude = 0.0 ''' time = "" epx = 0.0 epy = 0.0 epv = 0.0 ept = 0.0 eps = 0.0 climb = 0.0 speed = 0.0 direction = 0.0 ''' new_lat = False new_lon = False pack_format = '=dddb' # latitude, longitude, altitude, num satellites with io.open("/dev/shm/gps_stream", mode = "wb", buffering = 0) as gps_fifo: log = open("gps.csv", "wb") log.write("latitude, longitude, altitude, satellites, epx, epy\n") while True: try: report = session.next() if report['class'] == 'TPV': if hasattr(report, 'lon'): # Longitude in degrees longitude = report.lon new_lon = True if hasattr(report, 'lat'): # Latitude in degrees latitude = report.lat new_lat = True if hasattr(report, 'alt'): # Altitude - meters altitude = report.alt ''' if hasattr(report, 'epx'): # Estimated longitude error - meters epx = report.epx if hasattr(report, 'time'): # Time time = report.time if hasattr(report, 'ept'): # Estimated timestamp error - seconds ept = report.ept if hasattr(report, 'epy'): # Estimated latitude error - meters epy = report.epy if hasattr(report, 'epv'): # Estimated altitude error - meters epv = report.epv if hasattr(report, 'track'): # Direction - degrees from true north direction = report.track if hasattr(report, 'epd'): # Estimated direction error - degrees epd = report.epd if hasattr(report, 'climb'): # Climb velocity - meters per second climb = report.climb if hasattr(report, 'epc'): # Estimated climb error - meters per seconds epc = report.epc if hasattr(report, 'speed'): # Speed over ground - meters per second speed = report.speed if hasattr(report, 'eps'): # Estimated speed error - meters per second eps = report.eps ''' if report['class'] == 'SKY': if hasattr(report, 'satellites'): num_sats = 0 num_used_sats = 0 for satellite in report.satellites: num_sats += 1 if hasattr(satellite, 'used') and satellite.used: num_used_sats += 1 #----------------------------------------------------------------------------- # Send the new batch. #----------------------------------------------------------------------------- if new_lon and new_lat: log.write("%.10f, %.10f, %.10f, %d, %d\n" % (latitude, longitude, altitude, num_sats, num_used_sats)) new_lon = False new_lat = False output = struct.pack(pack_format, latitude, longitude, altitude, num_used_sats) gps_fifo.write(output) except KeyError: pass except KeyboardInterrupt: break except StopIteration: session = None break finally: pass log.close() #################################################################################################### # # Process the GPS data. # #################################################################################################### class GPSManager(): def __init__(self): #------------------------------------------------------------------------------------------- # Setup a shared memory based data stream for the GPS output #------------------------------------------------------------------------------------------- os.mkfifo("/dev/shm/gps_stream") self.gps_process = subprocess.Popen(["python", __file__, "GPS"], preexec_fn = Daemonize) while True: try: self.gps_fifo = io.open("/dev/shm/gps_stream", mode="rb") except: continue else: break self.waypoints = [] self.unpack_format = '=dddb' # latitude, longitude, altitude, num satellites self.unpack_size = struct.calcsize(self.unpack_format) def flush(self): #------------------------------------------------------------------------------------------- # Read what should be the backlog of reads, and return how many there are. #------------------------------------------------------------------------------------------- raw_bytes = self.gps_fifo.read(self.unpack_size) assert (len(raw_bytes) % self.unpack_size == 0), "Incomplete GPS data received" return int(len(raw_bytes) / self.unpack_size) def cleanup(self): #------------------------------------------------------------------------------------------- # Stop the GPS process if it's still running, and clean up the FIFO. #------------------------------------------------------------------------------------------- try: if self.gps_process.poll() == None: self.gps_process.send_signal(signal.SIGINT) self.gps_process.wait() except KeyboardInterrupt as e: pass self.gps_fifo.close() os.unlink("/dev/shm/gps_stream") def acquireSatellites(self, num_sats = MIN_SATS): gps_lat = 0.0 gps_lon = 0.0 gps_alt = 0.0 gps_sats = 0 start_time = time.time() print "Gimme up to a minutes to acquire satellites... 0", sys.stdout.flush() while time.time() - start_time < 60: gps_lat, gps_lon, gps_alt, gps_sats = self.read() print "\b\b%d" % gps_sats, sys.stdout.flush() #--------------------------------------------------------------------------------------- # If we've gpt enough satellites, give up. #--------------------------------------------------------------------------------------- if gps_sats >= num_sats: print break else: #--------------------------------------------------------------------------------------- # We ran out of time trying to get the minimum number of satellites. Is what we did get # enough? #--------------------------------------------------------------------------------------- print rsp = raw_input("I only got %d. Good enough? " % gps_sats) if len(rsp) != 0 and rsp[0] != "y" and rsp[0] != "Y": raise EnvironmentError("I can't see enough satellites, I give up!") return gps_lat, gps_lon, gps_alt, gps_sats def read(self): raw_bytes = self.gps_fifo.read(self.unpack_size) assert (len(raw_bytes) == self.unpack_size), "Invalid data block received from GPS reader" latitude, longitude, altitude, satellites = struct.unpack(self.unpack_format, raw_bytes) return latitude, longitude, altitude, satellites #################################################################################################### # # Start the Autopilot reading process. Invoke the Infinite Improbabilty Drive with a strong cup of tea! # #################################################################################################### def AutopilotProcessor(sweep_installed, gps_installed, compass_installed, initial_orientation, file_control = False, gps_control = False, fp_filename = ""): edx_target = 0.0 edy_target = 0.0 edz_target = 0.0 #----------------------------------------------------------------------------------------------- # Create our poll object #----------------------------------------------------------------------------------------------- poll = select.poll() #----------------------------------------------------------------------------------------------- # Define the flight plan tuple indices. #----------------------------------------------------------------------------------------------- X = 0 Y = 1 Z = 2 PERIOD = 3 NAME = 4 #----------------------------------------------------------------------------------------------- # Set up the various flight plans. #----------------------------------------------------------------------------------------------- takeoff_fp = [] landing_fp = [] abort_fp = [] file_fp = [] gps_locating_fp = [] gps_tracking_fp = [] gps_waypoints = [] sats_search_start = 0.0 #----------------------------------------------------------------------------------------------- # Build the standard takeoff and landing flight plans. Takeoff is twice the speed of lander: # takeoff needs to clear the ground promply avoiding obstacles; # landing needs to hit the ground gently to avoid impact damage. #----------------------------------------------------------------------------------------------- takeoff_fp.append((0.0, 0.0, 0.0, 0.0, "RTF")) takeoff_fp.append((0.0, 0.0, 0.5, 3.0, "TAKEOFF")) takeoff_fp.append((0.0, 0.0, 0.0, 0.5, "HOVER")) landing_fp.append((0.0, 0.0, -0.25, 7.0, "LANDING")) # # Extended landed for safety #----------------------------------------------------------------------------------------------- # Build the initial post-takeoff GPS flight plan as a minutes hover pending GPS satellite acquisition. # If it fails, it drops automatically into landing after that minute. #----------------------------------------------------------------------------------------------- gps_locating_fp.append((0.0, 0.0, 0.0, 360, "GPS: WHERE AM I?")) gps_tracking_fp.append((0.0, 0.0, 0.0, 60, "GPS TRACKING: 0")) #----------------------------------------------------------------------------------------------- # None-existent object avoidance flight plan initially. #----------------------------------------------------------------------------------------------- oa_fp = None #----------------------------------------------------------------------------------------------- # Build the file-based flight plan if that's what we're using. #----------------------------------------------------------------------------------------------- if file_control: with open(fp_filename, 'rb') as fp_csv: fp_reader = csv.reader(fp_csv) for fp_row in fp_reader: if len(fp_row) == 0 or (fp_row[0] != '' and fp_row[0][0] == '#'): continue if len(fp_row) != 5: break file_fp.append((float(fp_row[0]), float(fp_row[1]), float(fp_row[2]), float(fp_row[3]), fp_row[4].strip())) #----------------------------------------------------------------------------------------------- # Build the GPS waypoint flight plan if that's what we're using. #----------------------------------------------------------------------------------------------- elif gps_control: with open(fp_filename, 'rb') as fp_csv: fp_reader = csv.reader(fp_csv) for fp_row in fp_reader: if len(fp_row) == 0 or (fp_row[0] != '' and fp_row[0][0] == '#'): continue if len(fp_row) != 4: break gps_waypoints.append((float(fp_row[0]), float(fp_row[1]), float(fp_row[2]), int(fp_row[3]))) else: #------------------------------------------------------------------------------------------- # Without file or GPS control, just a standard takeoff and landing happens. #------------------------------------------------------------------------------------------- pass #----------------------------------------------------------------------------------------------- # Start up the Sweep and GPS processes if installed #----------------------------------------------------------------------------------------------- running = True try: sweep_started = False gps_started = False #------------------------------------------------------------------------------------------- # Kick off sweep if necessary #------------------------------------------------------------------------------------------- if sweep_installed: sweepp = SweepManager() sweep_fd = sweepp.sweep_fifo.fileno() poll.register(sweep_fd, select.POLLIN | select.POLLPRI) sweep_started = True #------------------------------------------------------------------------------------------- # Kick off GPS if necessary #------------------------------------------------------------------------------------------- if gps_installed: gpsp = GPSManager() gps_fd = gpsp.gps_fifo.fileno() poll.register(gps_fd, select.POLLIN | select.POLLPRI) gps_started = True except: #------------------------------------------------------------------------------------------- # By setting this, we drop through the big while running the flight plans, and immediately # send a finished message to the autopilot processor #------------------------------------------------------------------------------------------- running = False #----------------------------------------------------------------------------------------------- # Loop for the period of the flight defined by the flight plan contents #----------------------------------------------------------------------------------------------- pack_format = '=3f20s?' # edx, edy and edz float targets, string state name, bool running log = open("autopilot.log", "wb") #------------------------------------------------------------------------------------------- # Off we go! #------------------------------------------------------------------------------------------- with io.open("/dev/shm/autopilot_stream", mode = "wb", buffering = 0) as autopilot_fifo: try: phase = [] prev_phase = [] #-------------------------------------------------------------------------------------- # Do not 'break' out of this loop; this will skip the else at the end doing post successfuk # flight cleanup. #-------------------------------------------------------------------------------------- active_fp = takeoff_fp afp_changed = True start_time = time.time() update_time = 0.1 elapsed_time = 0.0 while running: #----------------------------------------------------------------------------------- # How long is it since we were last here? Based on that, how long should we sleep (if # at all) before working out the next step in the flight plan. #----------------------------------------------------------------------------------- delta_time = time.time() - start_time - elapsed_time elapsed_time += delta_time sleep_time = update_time - delta_time if delta_time < update_time else 0.0 paused_time = 0.0 results = poll.poll(sleep_time * 1000) #---------------------------------------------------------------------------------- # Check whether there's input from Sweep or GPS to trigger a flight plan change #---------------------------------------------------------------------------------- for fd, event in results: if sweep_installed and fd == sweep_fd: try: sweep_critical, sweep_warning, sweep_distance, sweep_direction = sweepp.read() if active_fp == takeoff_fp or active_fp == landing_fp: #------------------------------------------------------------------- # Ignore sweep objects on takeoff and landing #------------------------------------------------------------------- continue elif sweep_critical: #------------------------------------------------------------------- # What target height has the flight achieved so far? Use this to # determine how long the descent must be at fixed velocity of 0.3m/s. # Add another second to make sure this really definitely lands! #------------------------------------------------------------------- descent_time = edz_target / 0.3 + 1.0 #------------------------------------------------------------------- # Override that standard landing_fp to this custom one. #------------------------------------------------------------------- landing_fp = [(0.0, 0.0, -0.3, descent_time, "PROXIMITY CRITICAL %.2fm" % sweep_distance),] #==================================================================# # FLIGHT PLAN CHANGE # #==================================================================# log.write("AP: PROXIMITY LANDING %.2f METERS\n" % edz_target) active_fp = landing_fp afp_changed = True #=================================================================== # FLIGHT PLAN CHANGE # #=================================================================== elif sweep_warning: #------------------------------------------------------------------- # If we're just hovering, there's nothing to do here. #------------------------------------------------------------------- if math.pow(evx_target, 2) + math.pow(evy_target, 2) == 0: continue #------------------------------------------------------------------- # Find the direction the frame should be going under the standard flight plan. #------------------------------------------------------------------- if active_fp != oa_fp: paused_direction = math.atan2(evy_target, evx_target) #------------------------------------------------------------------- # If the obstacle is behind the direction of travel, ignore it #------------------------------------------------------------------- if abs((paused_direction - sweep_direction + math.pi) % (math.pi * 2) - math.pi) > math.pi / 2: continue #------------------------------------------------------------------- # We've spotted an obstruction worth avoiding; if the oa_fp is not already # running, then save off the current flight plan. #------------------------------------------------------------------- if active_fp != oa_fp: paused_fp = active_fp paused_time = elapsed_time #------------------------------------------------------------------- # We're to move +/- 90 degrees parallel to the obstruction direction; # find out which is 'forwards' wrt the paused flight direction. #-------------------------------------------------------------------- if abs((sweep_direction - paused_direction + 3 * math.pi / 2) % (math.pi * 2) - math.pi) < math.pi / 2: oa_direction = (sweep_direction + 3 * math.pi / 2) % (math.pi * 2) - math.pi else: oa_direction = (sweep_direction + math.pi / 2) % (math.pi * 2) - math.pi #------------------------------------------------------------------- # Set up the object avoidance flight plan - slow down to 0.3m/s #------------------------------------------------------------------- oax_target = 0.3 * math.cos(oa_direction) oay_target = 0.3 * math.sin(oa_direction) oa_fp = [(oax_target, oay_target, 0.0, 10.0, "AVOID @ %d DEGREES" % int(math.degrees(sweep_direction))),] #==================================================================# # FLIGHT PLAN CHANGE # #==================================================================# log.write("AP: AVOIDING OBSTACLE @ %d DEGREES.\n" % int(math.degrees(sweep_direction))) active_fp = oa_fp afp_changed = True #=================================================================== # FLIGHT PLAN CHANGE # #=================================================================== else: #------------------------------------------------------------------- # Neither critial nor warning proximity; if we currently using the oa_fp, # now reinstated the paused flight plan stored when an obstacle was detected. #------------------------------------------------------------------- if active_fp == oa_fp: #==================================================================# # FLIGHT PLAN CHANGE # #==================================================================# log.write("AP: OBSTACLE AVOIDED, RESUME PAUSED\n") active_fp = paused_fp afp_changed = True #=================================================================== # FLIGHT PLAN CHANGE # #=================================================================== paused_fp = None oa_fp = None except AssertionError as e: ''' #GPS: Would it be better to set up landing, or is FINISHED / STOP better #GPS: as something is seriously wrong with object detection? We MUST #GPS: do either a landing or abort here; FINISHED will hover if not #GPS: landed first. ''' running = False continue if gps_installed and fd == gps_fd: #--------------------------------------------------------------------------- # Run the GPS Processor, and convert response to X, Y coordinate in earth NSEW # frame. #--------------------------------------------------------------------------- current_gps = gpsp.read() current_lat, current_lon, current_alt, current_sats = current_gps #--------------------------------------------------------------------------- # If we aren't using the GPS flight plan, then move to the next # poll.poll() results list (if any) - note that doing the read above is # necessary notheless to flush the FIFO. #--------------------------------------------------------------------------- if not gps_control: continue #--------------------------------------------------------------------------- # If we're currently not using a GPS flightplan, keep GPS processing # out of it. #--------------------------------------------------------------------------- if active_fp != gps_locating_fp and active_fp != gps_tracking_fp: continue #--------------------------------------------------------------------------- # First, make sure the new data comes from enough satellites #--------------------------------------------------------------------------- if current_sats < MIN_SATS and active_fp != gps_locating_fp: #======================================================================# # FLIGHT PLAN CHANGE # #======================================================================# log.write("AP: GPS TOO FEW SATS, LANDING...\n") active_fp = landing_fp afp_changed = True #======================================================================# # FLIGHT PLAN CHANGE # #======================================================================# continue #--------------------------------------------------------------------------- # If the active_fp is the gps_locating_fp, then get on with satellite # acquisition. #--------------------------------------------------------------------------- if active_fp == gps_locating_fp: if current_sats >= MIN_SATS: #------------------------------------------------------------------- # Set target to current here will trigger an update from the # waypoint list lower down. #------------------------------------------------------------------- target_gps = current_gps #==================================================================# # FLIGHT PLAN CHANGE # #==================================================================# log.write("AP: GPS TRACKING\n") active_fp = gps_tracking_fp afp_changed = True #==================================================================# # FLIGHT PLAN CHANGE # #==================================================================# elif time.time() - sats_search_start > 60.0: #==================================================================# # FLIGHT PLAN CHANGE # #==================================================================# log.write("AP: GPS SATS SHORTAGE, LANDING...\n") active_fp = landing_fp afp_changed = True #==================================================================# # FLIGHT PLAN CHANGE # #==================================================================# #--------------------------------------------------------------------------- # First best effort to determine our current orientations based on an the # initial forward flight. #--------------------------------------------------------------------------- if active_fp == gps_tracking_fp: #----------------------------------------------------------------------- # Latitude = North (+) / South (-) - 0.0 running E/W around the equator; # range is +/- 90 degrees # Longitude = East (+) / West (-) - 0.0 running N/S through Greenwich; # range is +/- 180 degrees # # With a base level longitude and latitude in degrees, we can calculate the # current X and Y coordinates in meters using equirectangular approximation: # # ns = movement North / South - movement in a northerly direction is positive # ew = movement East / West - movement in an easterly direction is positive # R = average radius of earth in meters = 6,371,000 meters # # ns = (lat2 - lat1) * R meters # ew = (long2 - long1) * cos ((lat1 + lat2) / 2) * R meters # # Note longitude / latitude are in degrees and need to be converted into # radians i.e degrees * pi / 180 both for the cos and also the EARTH_RADIUS scale # # More at http://www.movable-type.co.uk/scripts/latlong.html # #----------------------------------------------------------------------- #----------------------------------------------------------------------- # Have we reached our destination? #----------------------------------------------------------------------- wibble = True while wibble: #------------------------------------------------------------------- # Now get the direction from the current location to the target #------------------------------------------------------------------- target_lat, target_lon, target_alt, target_sats = target_gps target_ns = math.radians(target_lat - current_lat) * EARTH_RADIUS target_ew = math.radians((target_lon - current_lon) * math.cos(math.radians((target_lat + current_lat) / 2))) * EARTH_RADIUS target_direction = math.atan2(target_ew, target_ns) #------------------------------------------------------------------- # Are we near the target? #------------------------------------------------------------------- target_distance = math.pow((math.pow(target_ns, 2) + math.pow(target_ew, 2)), 0.5) if target_distance < 1.0: # meters #--------------------------------------------------------------- # We're within one meter of the target, dig out the new waypoint # if there is one, otherwise land. #--------------------------------------------------------------- if len(gps_waypoints) > 0: #----------------------------------------------------------- # Move to the next waypoint target, and loop back to reprocess # the new target_gps #----------------------------------------------------------- gps_waypoint = gps_waypoints.pop(0) log.write("AP: GPS NEW WAYPOINT\n") target_gps = gps_waypoint continue else: #==========================================================# # FLIGHT PLAN CHANGE # #==========================================================# log.write("AP: GPS @ TARGET, LANDING...\n") active_fp = landing_fp afp_changed = True #==========================================================# # FLIGHT PLAN CHANGE # #==========================================================# break else: #--------------------------------------------------------------- # We're not at the target yet, keep processing. #--------------------------------------------------------------- wibble = False else: #------------------------------------------------------------------- # If we're still tracking, sort out the processing. #------------------------------------------------------------------- if active_fp == gps_tracking_fp: #--------------------------------------------------------------- # Yaw target based on quad IMU not GPS POV hence... #--------------------------------------------------------------- yaw_target = (initial_orientation - target_direction + math.pi) % (2 * math.pi) - math.pi s_yaw = math.sin(yaw_target) c_yaw = math.cos(yaw_target) #--------------------------------------------------------------- # Because our max speed is 1m/s and we receive GPS updates at 1Hz # and each target is 'reached' when it's less than 1m away, we slow # down near the destination. #--------------------------------------------------------------- speed = 1.0 if target_distance > 5.0 else target_distance / 5.0 x = c_yaw * speed # m/s evx_target y = s_yaw * speed # m/s evy_target #--------------------------------------------------------------- # Pause for though for 0.5s (i.e. stop), then head of in new direction #--------------------------------------------------------------- gps_tracking_fp = [(x, y, 0.0, 3600, "GPS TARGET %dm %do" % (int(round(target_distance)), int(round(math.degrees(yaw_target)))))] #==============================================================# # FLIGHT PLAN CHANGE # #==============================================================# log.write("AP: GPS TRACKING UPDATE\n") active_fp = gps_tracking_fp afp_changed = True #==============================================================# # FLIGHT PLAN CHANGE # #==============================================================# else: #------------------------------------------------------------------------------- # Finished the poll.poll() results processing; has the world changed beneath our # feet? If so, reset the timings for the new flight plans, and processes. #------------------------------------------------------------------------------- if afp_changed: afp_changed = False elapsed_time = paused_time start_time = time.time() - elapsed_time #----------------------------------------------------------------------------------- # Based on the elapsed time since the flight plan started, find which of the flight # plan phases we are in. #----------------------------------------------------------------------------------- phase_time = 0.0 for phase in active_fp: phase_time += phase[PERIOD] if elapsed_time <= phase_time: break else: #------------------------------------------------------------------------------- # We've fallen out the end of one flight plan - change active_fp to the next in # line. #------------------------------------------------------------------------------- if active_fp == takeoff_fp: if gps_installed and gps_control: #----------------------------------------------------------------------- # Take a timestamp of this transition; it's used later to see whether we've # been unable to find enough satellites in 60s #----------------------------------------------------------------------- sats_search_start = time.time() #======================================================================# # FLIGHT PLAN CHANGE # #======================================================================# log.write("AP: # SATS: ...\n") active_fp = gps_locating_fp #======================================================================# # FLIGHT PLAN CHANGE # #======================================================================# elif file_control: #======================================================================# # FLIGHT PLAN CHANGE # #======================================================================# log.write("AP: FILE FLIGHT PLAN\n") active_fp = file_fp #======================================================================# # FLIGHT PLAN CHANGE # #======================================================================# else: #======================================================================# # FLIGHT PLAN CHANGE # #======================================================================# log.write("AP: LANDING...\n") active_fp = landing_fp #======================================================================# # FLIGHT PLAN CHANGE # #======================================================================# elif active_fp == gps_locating_fp: #--------------------------------------------------------------------------- # We've dropped off the end of the satellite acquisition flight plan i.e. it's # timed out without a good result. Swap to landing. #--------------------------------------------------------------------------- #==========================================================================# # FLIGHT PLAN CHANGE # #==========================================================================# log.write("AP: GPS SATS TIMEOUT, LANDING...\n") active_fp = landing_fp #==========================================================================# # FLIGHT PLAN CHANGE # #==========================================================================# elif active_fp == gps_tracking_fp: #--------------------------------------------------------------------------- # We're not going to get here as the tracking fp is set to 1 hour, and swaps # fp above when it reaches it's GPS target. Nevertheless, lets include it. # Swap to landing. #--------------------------------------------------------------------------- #==========================================================================# # FLIGHT PLAN CHANGE # #==========================================================================# log.write("AP: GPS TRACKING TIMEOUT, LANDING...\n") active_fp = landing_fp #==========================================================================# # FLIGHT PLAN CHANGE # #==========================================================================# elif active_fp == file_fp: #--------------------------------------------------------------------------- # We've finished the hard coded file flight plan, time to land. #--------------------------------------------------------------------------- #==========================================================================# # FLIGHT PLAN CHANGE # #==========================================================================# log.write("AP: FILE COMPLETE, LANDING...\n") active_fp = landing_fp #==========================================================================# # FLIGHT PLAN CHANGE # #==========================================================================# elif active_fp == oa_fp: #--------------------------------------------------------------------------- # Object avoidance has run out of time, land. #--------------------------------------------------------------------------- #==========================================================================# # FLIGHT PLAN CHANGE # #==========================================================================# log.write("AP: OA TIMEOUT, LANDING...\n") active_fp = landing_fp #==========================================================================# # FLIGHT PLAN CHANGE # #==========================================================================# elif active_fp != landing_fp: #--------------------------------------------------------------------------- # This shouldn't ever get hit; finished flight plans all have next steps # above, but may as well cover it. #--------------------------------------------------------------------------- #==========================================================================# # FLIGHT PLAN CHANGE # #==========================================================================# log.write("AP: UNEXPLAINED, LANDING...\n") active_fp = landing_fp #==========================================================================# # FLIGHT PLAN CHANGE # #==========================================================================# elif active_fp == landing_fp: #--------------------------------------------------------------------------- # If we've finished the landing flight plan, the autopilot's job is done. #--------------------------------------------------------------------------- log.write("AP: LANDING COMPLETE\n") running = False #------------------------------------------------------------------------------- # The flight plan has completed and moved onto the next, update the timing accordingly. #------------------------------------------------------------------------------- start_time = time.time() elapsed_time = 0.0 #----------------------------------------------------------------------------------- # Have we crossed into a new phase of the flight plan? Log it if so. #----------------------------------------------------------------------------------- phase_name = phase[NAME] phase_changed = False if phase != prev_phase: phase_changed = True prev_phase = phase #----------------------------------------------------------------------------------- # Get the velocity targets for this phase, and integrate to get distance. Distance # is used in the abort fp generation. #----------------------------------------------------------------------------------- evx_target = phase[X] evy_target = phase[Y] evz_target = phase[Z] edx_target += evx_target * delta_time edy_target += evy_target * delta_time edz_target += evz_target * delta_time #----------------------------------------------------------------------------------- # No point updating the main processor velocities if nothing has changed. #----------------------------------------------------------------------------------- if not phase_changed: continue log.write("AP: PHASE CHANGE: %s\n" % phase_name) output = struct.pack(pack_format, evx_target, evy_target, evz_target, phase_name, running) autopilot_fifo.write(output) else: #----------------------------------------------------------------------------------- # We've dropped out of the end of all flight plans - let the motion processor know we # are done. #----------------------------------------------------------------------------------- log.write("AP: FINISHED\n") output = struct.pack(pack_format, 0.0, 0.0, 0.0, "FINISHED", False) autopilot_fifo.write(output) except KeyboardInterrupt as e: #--------------------------------------------------------------------------------------- # The motion processor is finished with us, we should too, and we have by breaking out of # the with. #--------------------------------------------------------------------------------------- if not autopilot_fifo.closed: print "Autopilot FIFO not closed! WTF!" except Exception as e: log.write("AP: UNIDENTIFIED EXCEPTION: %s\n" % e) finally: #--------------------------------------------------------------------------------------- # Cleanup Sweep if installed. #--------------------------------------------------------------------------------------- if sweep_installed and sweep_started: print "Stopping Sweep... ", sweepp.cleanup() poll.unregister(sweep_fd) print "stopped." #--------------------------------------------------------------------------------------- # Cleanup GPS if installed. #--------------------------------------------------------------------------------------- if gps_installed and gps_started: print "Stopping GPS... ", gpsp.cleanup() poll.unregister(gps_fd) print "stopped." log.close() #################################################################################################### # # Process the Autopilot data. # #################################################################################################### class AutopilotManager(): def __init__(self, sweep_installed, gps_installed, compass_installed, initial_orientation, file_control, gps_control, fp_filename): #------------------------------------------------------------------------------------------- # Setup a shared memory based data stream for the Sweep output #------------------------------------------------------------------------------------------- os.mkfifo("/dev/shm/autopilot_stream") self.autopilot_process = subprocess.Popen(["python", __file__, "AUTOPILOT", "%s" % sweep_installed, "%s" % gps_installed, "%s" % compass_installed, "%f" % initial_orientation, "%s" % file_control, "%s" % gps_control, fp_filename], preexec_fn = Daemonize) while True: try: self.autopilot_fifo = io.open("/dev/shm/autopilot_stream", mode="rb") except: continue else: break self.unpack_format = "=3f20s?" self.unpack_size = struct.calcsize(self.unpack_format) def flush(self): #------------------------------------------------------------------------------------------- # Read what should be the backlog of reads, and return how many there are. #------------------------------------------------------------------------------------------- raw_bytes = self.autopilot_fifo.read(self.unpack_size) assert (len(raw_bytes) % self.unpack_size == 0), "Incomplete Autopilot data received" return int(len(raw_bytes) / self.unpack_size) def read(self): raw_bytes = self.autopilot_fifo.read(self.unpack_size) assert (len(raw_bytes) == self.unpack_size), "Incomplete data received from Autopilot reader" evx_target, evy_target, evz_target, state_name, keep_looping = struct.unpack(self.unpack_format, raw_bytes) return evx_target, evy_target, evz_target, state_name, keep_looping def cleanup(self): #------------------------------------------------------------------------------------------- # Stop the Autopilot process if it's still running, and cleanup the FIFO. #------------------------------------------------------------------------------------------- try: if self.autopilot_process.poll() == None: self.autopilot_process.send_signal(signal.SIGINT) self.autopilot_process.wait() except KeyboardInterrupt as e: pass self.autopilot_fifo.close() os.unlink("/dev/shm/autopilot_stream") #################################################################################################### # # Remote control manager # #################################################################################################### class RCManager(): def __init__(self): self.server = socket.socket() addr = "192.168.42.1" port = 31415 self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.server.bind((addr, port)) self.server.listen(5) def connect(self): pack_format = "=?" self.connection, addr = self.server.accept() connection_fd = self.connection.fileno() output = struct.pack(pack_format, True) self.connection.send(output) return connection_fd def send(self): pass def read(self): unpack_format = "=ffffb?" unpack_size = struct.calcsize(unpack_format) raw = self.connection.recv(unpack_size) assert (len(raw) == unpack_size), "Invalid data" #----------------------------------------------------------------------------------- # React on the action #----------------------------------------------------------------------------------- formatted = struct.unpack(unpack_format, raw) assert (len(formatted) == 6), "Bad formatted size" evz_target = formatted[0] yr_target = formatted[1] evx_target = formatted[2] evy_target = formatted[3] state = formatted[4] beep = formatted[5] return evx_target, evy_target, evz_target, yr_target, state, beep def disconnect(self): pack_format = "=?" output = struct.pack(pack_format, False) self.connection.send(output) self.connection.close() def close(self): self.server.shutdown(socket.SHUT_RDWR) self.server.close() #################################################################################################### # # Video at 10fps. Each frame is 320 x 320 pixels. Each macro-block is 16 x 16 pixels. Due to an # extra column of macro-blocks (dunno why), that means each frame breaks down into 21 columns by # 20 rows = 420 macro-blocks, each of which is 4 bytes - 1 signed byte X, 1 signed byte Y and 2 unsigned # bytes SAD (sum of absolute differences). # #################################################################################################### def VideoProcessor(frame_width, frame_height, frame_rate): with picamera.PiCamera() as camera: camera.resolution = (frame_width, frame_height) camera.framerate = frame_rate #------------------------------------------------------------------------------------------- # 50% contrast seems to work well - completely arbitrary. #------------------------------------------------------------------------------------------- camera.contrast = 42 with io.open("/dev/shm/video_stream", mode = "wb", buffering = 0) as vofi: camera.start_recording('/dev/null', format='h264', motion_output=vofi, quality=42) try: while True: camera.wait_recording(10) except KeyboardInterrupt: pass finally: camera.stop_recording() #################################################################################################### # # Class to process video frame macro-block motion tracking. # #################################################################################################### class VideoManager: def __init__(self, video_fifo, yaw_increment): self.video_fifo = video_fifo self.yaw_increment = yaw_increment self.phase = 0 mb_size = 16 # 16 x 16 pixels are combined to make a macro-block bytes_per_mb = 4 # Each macro-block is 4 bytes, 1 X, 1 Y and 2 SAD self.mbs_per_frame = int(round((frame_width / mb_size + 1) * (frame_height / mb_size))) self.bytes_per_frame = self.mbs_per_frame * bytes_per_mb def flush(self): #------------------------------------------------------------------------------------------- # Read what should be the backlog of frames, and return how many there are. #------------------------------------------------------------------------------------------- frame_bytes = self.video_fifo.read(self.bytes_per_frame) assert (len(frame_bytes) % self.bytes_per_frame == 0), "Incomplete video frames received: %f" % (len(frame_bytes) / self.bytes_per_frame) return (len(frame_bytes) / self.bytes_per_frame) def phase0(self): #------------------------------------------------------------------------------------------- # Read the video stream and parse into a list of macro-block vectors #------------------------------------------------------------------------------------------- self.vector_dict = {} self.vector_list = [] self.c_yaw = math.cos(self.yaw_increment) self.s_yaw = math.sin(self.yaw_increment) sign = 1 # Was '-1 if i_am_chloe else 1' as Chloe had the camera twisted by 180 degrees frames = self.video_fifo.read(self.bytes_per_frame) assert (len(frames) != 0), "Shouldn't be here, no bytes to read" assert (len(frames) % self.bytes_per_frame == 0), "Incomplete frame bytes read" num_frames = int(len(frames) / self.bytes_per_frame) assert (num_frames == 1), "Read more than one frame somehow?" #------------------------------------------------------------------------------------------- # Convert the data to byte, byte, ushort of x, y, sad structure and process them. The # exception here happens when a macro-block is filled with zeros, indicating either a full # reset or no movement, and hence no processing required. #------------------------------------------------------------------------------------------- format = '=' + 'bbH' * self.mbs_per_frame * num_frames iframe = struct.unpack(format, frames) assert (len(iframe) % 3 == 0), "iFrame size error" self.mbs_per_iframe = int(round(len(iframe) / 3 / num_frames)) assert (self.mbs_per_iframe == self.mbs_per_frame), "iframe mb count different to frame mb count" #--------------------------------------------------------------------------------------- # Split the iframe into a list of macro-block vectors. The mapping from each iframe # in idx, idy depends on how the camera is orientated WRT the frame. # This must be checked callibrated. # # Note: all macro-block vectors are even integers, so we divide them by 2 here for use # walking the vector dictionary for neighbours; we reinstate this at the end. # #--------------------------------------------------------------------------------------- for ii in range(self.mbs_per_iframe): idx = iframe[3 * ii + 1] idy = iframe[3 * ii] assert (idx % 2 == 0 and idy % 2 == 0), "Odd (not even) MB vector" idx = int(round(sign * idx / 2)) idy = int(round(sign * idy / 2)) if idx == 0 and idy == 0: continue self.vector_list.append((idx, idy)) #------------------------------------------------------------------------------------------- # If the dictionary is empty, this indicates a new frame; this is not an error strictly, # more of a reset to tell the outer world about. #------------------------------------------------------------------------------------------- if len(self.vector_list) == 0: raise ValueError("Empty Video Frame Object") def phase1(self): #------------------------------------------------------------------------------------------- # Unyaw the list of vectors, overwriting the yaw list #------------------------------------------------------------------------------------------- unyawed_vectors = [] #------------------------------------------------------------------------------------------- # Undo the yaw increment for better macro-block matching. Also, multiple interations of this # keeps the distance / direction in earth frame as is required for fusion. #------------------------------------------------------------------------------------------- for vector in self.vector_list: idx, idy = vector uvx = self.c_yaw * idx - self.s_yaw * idy uvy = self.s_yaw * idx + self.c_yaw * idy unyawed_vectors.append((int(round(uvx)), int(round(uvy)))) self.vector_list = unyawed_vectors def phase2(self): #------------------------------------------------------------------------------------------- # Build the dictionary of unyawed vectors; they score 2 because of the next phase #------------------------------------------------------------------------------------------- for (idx, idy) in self.vector_list: if (idx, idy) in self.vector_dict: self.vector_dict[(idx, idy)] += 2 else: self.vector_dict[(idx, idy)] = 2 def phase3(self): #------------------------------------------------------------------------------------------- # Pass again through the dictionary of vectors, building up clusters based on neighbours. #------------------------------------------------------------------------------------------- best_score = 0 self.best_vectors = [] for vector in self.vector_dict.keys(): vector_score = self.vector_dict[vector] for ii in range(-1, 2): for jj in range(-1, 2): if ii == 0 and jj == 0: continue vector_x, vector_y = vector neighbour = (vector_x + ii, vector_y + jj) if neighbour in self.vector_dict: vector_score += self.vector_dict[neighbour] if vector_score > best_score: best_score = vector_score self.best_vectors = [(vector, vector_score)] elif vector_score == best_score: self.best_vectors.append((vector, vector_score)) def phase4(self): #------------------------------------------------------------------------------------------- # Now we've collected the clusters of the best score vectors in the frame, average and reyaw # it before returning the result. #------------------------------------------------------------------------------------------- sum_score = 0 sum_x = 0 sum_y = 0 for (vector_x, vector_y), vector_score in self.best_vectors: sum_x += vector_x * vector_score sum_y += vector_y * vector_score sum_score += vector_score idx = self.c_yaw * sum_x + self.s_yaw * sum_y idy = -self.s_yaw * sum_x + self.c_yaw * sum_y return 2 * idx / sum_score, 2 * idy / sum_score def process(self): assert(self.phase < 5), "Phase shift in motion vector processing" #------------------------------------------------------------------------------------------- # Phase 0 - load the data and convert into a macro-block vector list #------------------------------------------------------------------------------------------- if self.phase == 0: self.phase0() rv = None #------------------------------------------------------------------------------------------- # Phase 1 - take the list of macro blocks and undo yaw #------------------------------------------------------------------------------------------- elif self.phase == 1: self.phase1() rv = None #------------------------------------------------------------------------------------------- # Phase 2 - build the dictionary of int rounded unyawed vectors #------------------------------------------------------------------------------------------- elif self.phase == 2: self.phase2() rv = None #------------------------------------------------------------------------------------------- # Phase 3 - walk the dictionary, looking for neighbouring clusters and score them #------------------------------------------------------------------------------------------- elif self.phase == 3: self.phase3() rv = None #------------------------------------------------------------------------------------------- # Phase 4 - average highest peak clusters, redo yaw, and return result #------------------------------------------------------------------------------------------- elif self.phase == 4: idx, idy = self.phase4() rv = idx, idy self.phase += 1 return rv #################################################################################################### # # Class to split initialation, flight startup and flight control # #################################################################################################### class Quadcopter: MOTOR_LOCATION_FRONT = 0b00000001 MOTOR_LOCATION_BACK = 0b00000010 MOTOR_LOCATION_LEFT = 0b00000100 MOTOR_LOCATION_RIGHT = 0b00001000 MOTOR_ROTATION_CW = 1 MOTOR_ROTATION_ACW = 2 keep_looping = False #=============================================================================================== # One-off initialization #=============================================================================================== def __init__(self): #------------------------------------------------------------------------------------------- # Who am I? #------------------------------------------------------------------------------------------- global i_am_zoe global i_am_hermione global i_am_penelope i_am_zoe = False i_am_hermione = False i_am_penelope = False my_name = os.uname()[1] if my_name == "zoe.local" or my_name == "zoe": print "Hi, I'm Zoe. Nice to meet you!" i_am_zoe = True elif my_name == "hermione.local" or my_name == "hermione": print "Hi, I'm Hermione. Nice to meet you!" i_am_hermione = True elif my_name == "penelope.local" or my_name == "penelope": print "Hi, I'm Penelope. Nice to meet you!" i_am_penelope = True else: print "Sorry, I'm not qualified to fly this piDrone." return #------------------------------------------------------------------------------------------- # Set up the global poll object #------------------------------------------------------------------------------------------- global poll poll = select.poll() #------------------------------------------------------------------------------------------- # Set up extra sensors based on quad identify. # - Zoe is a Pi0W with a single CPU; many features are turned off to avoid spawning multiple # processes within that single CPU. She runs one and a bit process - the bit is the Video # processing which is mostly handled by the GPU. # - Hermione is a B3 with 4 CPUs. As a result she can run the four and a bit process required # for all features to be enabled. # - Penelope is a B3+ with 4 CPUs. As a result she can run the four and a bit process required # for all features to be enabled. #------------------------------------------------------------------------------------------- X8 = False if i_am_zoe: self.compass_installed = False self.camera_installed = True self.gll_installed = True self.gps_installed = False self.sweep_installed = False self.autopilot_installed = False self.rc_installed = True elif i_am_hermione: self.compass_installed = True self.camera_installed = True self.gll_installed = True self.gps_installed = True self.sweep_installed = True self.autopilot_installed = True self.rc_installed = False X8 = True elif i_am_penelope: self.compass_installed = True self.camera_installed = True self.gll_installed = True self.gps_installed = True self.sweep_installed = False self.autopilot_installed = True self.rc_installed = False X8 = True assert (self.autopilot_installed ^ self.rc_installed), "Autopilot or RC but not both nor neither" ''' #AB! Swap the above to autonomous_control and manual_control ''' #------------------------------------------------------------------------------------------- # Lock code permanently in memory - no swapping to disk #------------------------------------------------------------------------------------------- mlockall() #------------------------------------------------------------------------------------------- # Set up the base logging #------------------------------------------------------------------------------------------- global logger logger = logging.getLogger('QC logger') logger.setLevel(logging.INFO) #------------------------------------------------------------------------------------------- # Create file and console logger handlers - the file is written into shared memory and only # dumped to disk / SD card at the end of a flight for performance reasons #------------------------------------------------------------------------------------------- global file_handler file_handler = logging.FileHandler("qcstats.csv", 'w') file_handler.setLevel(logging.WARNING) console_handler = logging.StreamHandler() console_handler.setLevel(logging.CRITICAL) #------------------------------------------------------------------------------------------- # Create a formatter and add it to both handlers #------------------------------------------------------------------------------------------- console_formatter = logging.Formatter('%(message)s') console_handler.setFormatter(console_formatter) file_formatter = logging.Formatter('[%(levelname)s] (%(threadName)-10s) %(funcName)s %(lineno)d, %(message)s') file_handler.setFormatter(file_formatter) #------------------------------------------------------------------------------------------- # Add both handlers to the logger #------------------------------------------------------------------------------------------- logger.addHandler(console_handler) logger.addHandler(file_handler) #------------------------------------------------------------------------------------------- # First log, whose flying and under what configuration #------------------------------------------------------------------------------------------- logger.warning("%s is flying.", "Zoe" if i_am_zoe else "Hermione" if i_am_hermione else "Penelope") #------------------------------------------------------------------------------------------- # Set the BCM pin assigned to the FIFO overflow #------------------------------------------------------------------------------------------- global GPIO_POWER_BROWN_OUT_INTERRUPT GPIO_POWER_BROWN_OUT_INTERRUPT = 35 global GPIO_FIFO_OVERFLOW_INTERRUPT GPIO_FIFO_OVERFLOW_INTERRUPT = 24 if X8 else 22 global GPIO_GLL_DR_INTERRUPT GPIO_GLL_DR_INTERRUPT = 5 global GPIO_BUZZER GPIO_BUZZER = 25 #------------------------------------------------------------------------------------------- # Enable RPIO for ESC PWM. This must be set up prior to adding the SignalHandler below or it # will override what we set thus killing the "Kill Switch".. #------------------------------------------------------------------------------------------- PWMInit() #------------------------------------------------------------------------------------------- # Enable GPIO for the FIFO overflow interrupt. #------------------------------------------------------------------------------------------- GPIOInit(self.fifoOverflowISR) #------------------------------------------------------------------------------------------- # Set the signal handler here so the core processing loop can be stopped (or not started) by # Ctrl-C. #------------------------------------------------------------------------------------------- signal.signal(signal.SIGINT, self.shutdownSignalHandler) #------------------------------------------------------------------------------------------- # Zoe is a Quad, Hermione and Penelope are X8 #------------------------------------------------------------------------------------------- ESC_BCM_FLT = 0 ESC_BCM_FRT = 0 ESC_BCM_BLT = 0 ESC_BCM_BRT = 0 ESC_BCM_FLU = 0 ESC_BCM_FRU = 0 ESC_BCM_BLU = 0 ESC_BCM_BRU = 0 if not X8: ESC_BCM_FLT = 27 ESC_BCM_FRT = 17 ESC_BCM_BLT = 26 ESC_BCM_BRT = 19 else: ESC_BCM_FLT = 27 ESC_BCM_FRT = 17 ESC_BCM_BLT = 26 ESC_BCM_BRT = 20 ESC_BCM_FLU = 22 ESC_BCM_FRU = 23 ESC_BCM_BLU = 16 ESC_BCM_BRU = 19 pin_list = [ESC_BCM_FLT, ESC_BCM_FRT, ESC_BCM_BLT, ESC_BCM_BRT, ESC_BCM_FLU, ESC_BCM_FRU, ESC_BCM_BLU, ESC_BCM_BRU] location_list = [self.MOTOR_LOCATION_FRONT | self.MOTOR_LOCATION_LEFT, self.MOTOR_LOCATION_FRONT | self.MOTOR_LOCATION_RIGHT, self.MOTOR_LOCATION_BACK | self.MOTOR_LOCATION_LEFT, self.MOTOR_LOCATION_BACK | self.MOTOR_LOCATION_RIGHT, self.MOTOR_LOCATION_FRONT | self.MOTOR_LOCATION_LEFT, self.MOTOR_LOCATION_FRONT | self.MOTOR_LOCATION_RIGHT, self.MOTOR_LOCATION_BACK | self.MOTOR_LOCATION_LEFT, self.MOTOR_LOCATION_BACK | self.MOTOR_LOCATION_RIGHT] rotation_list = [self.MOTOR_ROTATION_ACW, self.MOTOR_ROTATION_CW, self.MOTOR_ROTATION_CW, self.MOTOR_ROTATION_ACW, self.MOTOR_ROTATION_CW, self.MOTOR_ROTATION_ACW, self.MOTOR_ROTATION_ACW, self.MOTOR_ROTATION_CW] name_list = ['front left topside', 'front right topside', 'back left topside', 'back right topside', 'front left underside', 'front right underside', 'back left underside', 'back right underside'] #------------------------------------------------------------------------------------------- # Prime the ESCs to stop their annoying beeping! All 3 of P, H & Z use the T-motor ESCs # with the same ESC firmware so have the same spin_pwm #------------------------------------------------------------------------------------------- global stfu_pwm global spin_pwm stfu_pwm = 1000 spin_pwm = 0 if i_am_zoe: spin_pwm = 1150 elif i_am_hermione: spin_pwm = 1150 elif i_am_penelope: spin_pwm = 1150 self.esc_list = [] for esc_index in range(8 if X8 else 4): esc = ESC(pin_list[esc_index], location_list[esc_index], rotation_list[esc_index], name_list[esc_index]) self.esc_list.append(esc) #=========================================================================================== # Globals for the IMU setup # adc_frequency - the sampling rate of the ADC # sampling_rate - the data sampling rate and thus data ready interrupt rate # motion processing. # motion_rate - the target frequency motion processing occurs under perfect conditions. # fusion_rate - the sampling rate of the GLL and the video frame rate # alpf - the accelerometer low pass filter # glpf - the gyrometer low pass filter #=========================================================================================== global adc_frequency global sampling_rate global motion_rate global fusion_rate adc_frequency = 1000 # defined by dlpf >= 1; DO NOT USE ZERO => 8000 adc_frequency fusion_rate = 10 if self.camera_installed or self.gll_installed: if i_am_hermione: sampling_rate = 500 # Hz motion_rate = 75 # Hz elif i_am_penelope: sampling_rate = 500 # Hz motion_rate = 75 # Hz elif i_am_zoe: sampling_rate = 333 # Hz motion_rate = 66 # Hz else: sampling_rate = 500 # Hz - thought 1000 should work, but not motion_rate = 75 # Hz - thought 100 should work, but not glpf = 1 # 184Hz #------------------------------------------------------------------------------------------- # This is not for antialiasing: the accelerometer low pass filter happens between the ADC # rate and our IMU sampling rate. ADC rate is 1kHz through this case. However, I've seen poor # behavious in double integration when IMU sampling rate is 500Hz and alpf = 460Hz. #------------------------------------------------------------------------------------------- if sampling_rate == 1000: # SRD = 0 (1kHz) alpf = 0 # alpf = 460Hz elif sampling_rate == 500: # SRD = 1 (500Hz) alpf = 1 # alpf = 184Hz elif sampling_rate >= 200: # SRD = 2, 3, 4 (333, 250, 200Hz) alpf = 2 # alpf = 92Hz elif sampling_rate >= 100: # SRD = 5, 6, 7, 8, 9 (166, 143, 125, 111, 100Hz) alpf = 3 # alpf = 41Hz else: #-------------------------------------------------------------------------------------- # There's no point going less than 100Hz IMU sampling; we need about 100Hz motion # processing for some degree of level of stability. #-------------------------------------------------------------------------------------- print "SRD + alpf useless: forget it!" return global mpu6050 mpu6050 = MPU6050(0x68, alpf, glpf) #------------------------------------------------------------------------------------------- # Scheduling parameters defining standard, and critical FIFO block counts # # FIFO_MINIMUM - The least number of batches of collect and average for running them through # the motion processor # FIFO_MAXIMUM - The most number of batches to be allowed through the motion processor; any # higher risks FIFO overflow. # # 512/12 is the maximum number of batches in the IMU FIFO # #------------------------------------------------------------------------------------------- self.FIFO_MINIMUM = int(round(sampling_rate / motion_rate)) self.FIFO_MAXIMUM = int(round(512 / 12)) - self.FIFO_MINIMUM #------------------------------------------------------------------------------------------- # Initialize the compass object. #------------------------------------------------------------------------------------------- if self.compass_installed: mpu6050.initCompass() #------------------------------------------------------------------------------------------- # Initialize the Garmin LiDAR-Lite V3 at 10Hz - this is also used for the camera frame rate. #AB? The only time I tried 20 on a dimly lit lawn, it leapt up and crashed down. #------------------------------------------------------------------------------------------- if self.gll_installed: global gll if i_am_penelope or i_am_zoe: gll = GLLv3HP() else: gll = GLLv3(rate = fusion_rate) #=============================================================================================== # Keyboard / command line input between flights for CLI update etc #=============================================================================================== def go(self): cli_argv = "" if self.rc_installed: self.rc = RCManager() self.rc_status = RC_DONE shutdown = False while not shutdown: print "============================================" cli_argv = raw_input("Wassup? ") print "============================================" if len(cli_argv) != 0 and (cli_argv == 'exit' or cli_argv == 'quit'): shutdown = True continue self.argv = sys.argv[1:] + cli_argv.split() #--------------------------------------------------------------------------------------- # Check the command line for calibration or flight parameters #--------------------------------------------------------------------------------------- print "Just checking a few details. Gimme a few seconds..." try: cli_parms = CheckCLI(self.argv) except ValueError, err: print "Command line error: %s" % err continue self.fly(cli_parms) else: if self.rc_installed: self.rc.close() self.shutdown() #=============================================================================================== # Per-flight configuration, initializations and flight control itself #=============================================================================================== def fly(self, cli_parms): print "Just checking a few details. Gimme a few seconds..." #------------------------------------------------------------------------------------------- # Check the command line for calibration or flight parameters #------------------------------------------------------------------------------------------- fp_filename, calibrate_0g, cc_compass, yaw_control, file_control, rc_control, gps_control, add_waypoint, clear_waypoints, hover_pwm, vdp_gain, vdi_gain, vdd_gain, vvp_gain, vvi_gain, vvd_gain, hdp_gain, hdi_gain, hdd_gain, hvp_gain, hvi_gain, hvd_gain, prp_gain, pri_gain, prd_gain, rrp_gain, rri_gain, rrd_gain, yrp_gain, yri_gain, yrd_gain, test_case, atau, diagnostics = cli_parms logger.warning("fp_filename = %s, calibrate_0g = %d, check / calibrate compass = %s, yaw_control = %s, file_control = %s, gps_control = %s, add_waypoint = %s, clear_waypoints = %s, hover_pwm = %d, vdp_gain = %f, vdi_gain = %f, vdd_gain= %f, vvp_gain = %f, vvi_gain = %f, vvd_gain= %f, hdp_gain = %f, hdi_gain = %f, hdd_gain = %f, hvp_gain = %f, hvi_gain = %f, hvd_gain = %f, prp_gain = %f, pri_gain = %f, prd_gain = %f, rrp_gain = %f, rri_gain = %f, rrd_gain = %f, yrp_gain = %f, yri_gain = %f, yrd_gain = %f, test_case = %d, atau = %f, diagnostics = %s", fp_filename, calibrate_0g, cc_compass, yaw_control, file_control, gps_control, add_waypoint, clear_waypoints, hover_pwm, vdp_gain, vdi_gain, vdd_gain, vvp_gain, vvi_gain, vvd_gain, hdp_gain, hdi_gain, hdd_gain, hvp_gain, hvi_gain, hvd_gain, prp_gain, pri_gain, prd_gain, rrp_gain, rri_gain, rrd_gain, yrp_gain, yri_gain, yrd_gain, test_case, atau, diagnostics) #------------------------------------------------------------------------------------------- # Calibrate gravity or use previous settings #------------------------------------------------------------------------------------------- if calibrate_0g: if not mpu6050.calibrate0g(): print "0g calibration error, abort" return elif not mpu6050.load0gCalibration(): print "0g calibration data not found." return #------------------------------------------------------------------------------------------- # Calibrate compass. #------------------------------------------------------------------------------------------- if self.compass_installed: if cc_compass: if not mpu6050.compassCheckCalibrate(): print "Compass check / calibration error, abort" return elif not mpu6050.loadCompassCalibration(): print "Compass calibration data not found" return elif cc_compass: print "Compass not installed, check / calibration not possible." return #------------------------------------------------------------------------------------------- # Sanity check that if we are using RC flight plan, then RC needs to have been installed. #------------------------------------------------------------------------------------------- if rc_control and not self.rc_installed: print "Can't do RC processing without RC installed!" return #------------------------------------------------------------------------------------------- # Sanity check that if we are using a GPS flight plan, then GPS needs to have been installed. #------------------------------------------------------------------------------------------- if (gps_control or add_waypoint) and not self.gps_installed: print "Can't do GPS processing without GPS installed!" return #------------------------------------------------------------------------------------------- # Add GPS waypoint. #------------------------------------------------------------------------------------------- if add_waypoint: gpsp = GPSManager() try: lat, lon, alt, sats = gpsp.acquireSatellites() except EnvironmentError as e: print e else: with open("GPSWaypoints.csv", "ab") as gps_waypoints: gps_waypoints.write("%.10f, %.10f, %.10f, %d\n" % (lat, lon, alt, sats)) finally: gpsp.cleanup() gpsp = None return #------------------------------------------------------------------------------------------- # Clear GPS waypoints. #------------------------------------------------------------------------------------------- if clear_waypoints: try: os.remove("GPSWaypoints.csv") except OSError: pass return #------------------------------------------------------------------------------------------- # START TESTCASE 1 CODE: spin up each blade individually for 5s each and check they all turn # the right way. At the same time, log X, Y and Z accelerometer readings # to measure noise from the motors and props due to possible prop and motor # damage. #------------------------------------------------------------------------------------------- if test_case == 1: print "TESTCASE 1: Check props are spinning as expected" for esc in self.esc_list: print "%s prop should rotate %s." % (esc.name, "anti-clockwise" if esc.motor_rotation == self.MOTOR_ROTATION_ACW else "clockwise") #----------------------------------------------------------------------------------- # Get the prop up to the configured spin rate. Sleep for 5s then stop and move # on to the next prop. #----------------------------------------------------------------------------------- esc.set(hover_pwm) time.sleep(5) esc.set(stfu_pwm) return #------------------------------------------------------------------------------------------- # END TESTCASE 1 CODE: spin up each blade individually for 10s each and check they all turn the # right way #------------------------------------------------------------------------------------------- #=========================================================================================== # OK, we're in flight mode, better get on with it #=========================================================================================== self.keep_looping = True edx_target = 0.0 edy_target = 0.0 edz_target = 0.0 evx_target = 0.0 evy_target = 0.0 evz_target = 0.0 eyr_target = 0.0 ya_target = 0.0 qdx_input = 0.0 qdy_input = 0.0 qdz_input = 0.0 qvx_input = 0.0 qvy_input = 0.0 qvz_input = 0.0 edx_fuse = 0.0 edy_fuse = 0.0 edz_fuse = 0.0 evx_fuse = 0.0 evy_fuse = 0.0 evz_fuse = 0.0 qdx_fuse = 0.0 qdy_fuse = 0.0 qdz_fuse = 0.0 qvx_fuse = 0.0 qvy_fuse = 0.0 qvz_fuse = 0.0 #=========================================================================================== # Tuning: Set up the PID gains - some are hard coded mathematical approximations, some come # from the CLI parameters to allow for tuning - 12 in all! # - Quad X axis distance # - Quad Y axis distance # - Quad Z axis distance # - Quad X axis velocity # - Quad Y axis velocity # - Quad Z axis velocity # - Pitch angle # - Pitch rotation rate # - Roll angle # - Roll rotation rate # - Yaw angle # = Yaw rotation rate #=========================================================================================== #------------------------------------------------------------------------------------------- # The quad X axis PID controls fore / aft distance #------------------------------------------------------------------------------------------- PID_QDX_P_GAIN = hdp_gain PID_QDX_I_GAIN = hdi_gain PID_QDX_D_GAIN = hdd_gain #------------------------------------------------------------------------------------------- # The quad Y axis PID controls left / right distance #------------------------------------------------------------------------------------------- PID_QDY_P_GAIN = hdp_gain PID_QDY_I_GAIN = hdi_gain PID_QDY_D_GAIN = hdd_gain #------------------------------------------------------------------------------------------- # The quad Z axis PID controls up / down distance #------------------------------------------------------------------------------------------- PID_QDZ_P_GAIN = vdp_gain PID_QDZ_I_GAIN = vdi_gain PID_QDZ_D_GAIN = vdd_gain #------------------------------------------------------------------------------------------- # The quad X axis speed controls fore / aft speed #------------------------------------------------------------------------------------------- PID_QVX_P_GAIN = hvp_gain PID_QVX_I_GAIN = hvi_gain PID_QVX_D_GAIN = hvd_gain #------------------------------------------------------------------------------------------- # The quad Y axis speed PID controls left / right speed #------------------------------------------------------------------------------------------- PID_QVY_P_GAIN = hvp_gain PID_QVY_I_GAIN = hvi_gain PID_QVY_D_GAIN = hvd_gain #------------------------------------------------------------------------------------------- # The quad Z axis speed PID controls up / down speed #------------------------------------------------------------------------------------------- PID_QVZ_P_GAIN = vvp_gain PID_QVZ_I_GAIN = vvi_gain PID_QVZ_D_GAIN = vvd_gain #------------------------------------------------------------------------------------------- # The roll angle PID controls stable angles around the Y-axis #------------------------------------------------------------------------------------------- PID_PA_P_GAIN = 2.0 # pap_gain PID_PA_I_GAIN = 0.0 # pai_gain PID_PA_D_GAIN = 0.0 # pad_gain #------------------------------------------------------------------------------------------- # The pitch rate PID controls stable rotation rate around the Y-axis #------------------------------------------------------------------------------------------- PID_PR_P_GAIN = prp_gain PID_PR_I_GAIN = pri_gain PID_PR_D_GAIN = prd_gain #------------------------------------------------------------------------------------------- # The roll angle PID controls stable angles around the X-axis #------------------------------------------------------------------------------------------- PID_RA_P_GAIN = 2.0 # rap_gain PID_RA_I_GAIN = 0.0 # rai_gain PID_RA_D_GAIN = 0.0 # rad_gain #------------------------------------------------------------------------------------------- # The roll rate PID controls stable rotation rate around the X-axis #------------------------------------------------------------------------------------------- PID_RR_P_GAIN = rrp_gain PID_RR_I_GAIN = rri_gain PID_RR_D_GAIN = rrd_gain #------------------------------------------------------------------------------------------- # The yaw angle PID controls stable angles around the Z-axis #------------------------------------------------------------------------------------------- PID_YA_P_GAIN = 8.0 # yap_gain PID_YA_I_GAIN = 0.0 # yai_gain PID_YA_D_GAIN = 0.0 # yad_gain #------------------------------------------------------------------------------------------- # The yaw rate PID controls stable rotation speed around the Z-axis #------------------------------------------------------------------------------------------- PID_YR_P_GAIN = yrp_gain PID_YR_I_GAIN = yri_gain PID_YR_D_GAIN = yrd_gain #------------------------------------------------------------------------------------------- # Start the X, Y (horizontal) and Z (vertical) distance PID #------------------------------------------------------------------------------------------- qdx_pid = PID(PID_QDX_P_GAIN, PID_QDX_I_GAIN, PID_QDX_D_GAIN) qdy_pid = PID(PID_QDY_P_GAIN, PID_QDY_I_GAIN, PID_QDY_D_GAIN) qdz_pid = PID(PID_QDZ_P_GAIN, PID_QDZ_I_GAIN, PID_QDZ_D_GAIN) #------------------------------------------------------------------------------------------- # Start the X, Y (horizontal) and Z (vertical) velocity PIDs #------------------------------------------------------------------------------------------- qvx_pid = PID(PID_QVX_P_GAIN, PID_QVX_I_GAIN, PID_QVX_D_GAIN) qvy_pid = PID(PID_QVY_P_GAIN, PID_QVY_I_GAIN, PID_QVY_D_GAIN) qvz_pid = PID(PID_QVZ_P_GAIN, PID_QVZ_I_GAIN, PID_QVZ_D_GAIN) #------------------------------------------------------------------------------------------- # Start the pitch, roll and yaw angle PID - note the different PID class for yaw. #------------------------------------------------------------------------------------------- pa_pid = PID(PID_PA_P_GAIN, PID_PA_I_GAIN, PID_PA_D_GAIN) ra_pid = PID(PID_RA_P_GAIN, PID_RA_I_GAIN, PID_RA_D_GAIN) ya_pid = YAW_PID(PID_YA_P_GAIN, PID_YA_I_GAIN, PID_YA_D_GAIN) #------------------------------------------------------------------------------------------- # Start the pitch, roll and yaw rotation rate PIDs #------------------------------------------------------------------------------------------- pr_pid = PID(PID_PR_P_GAIN, PID_PR_I_GAIN, PID_PR_D_GAIN) rr_pid = PID(PID_RR_P_GAIN, PID_RR_I_GAIN, PID_RR_D_GAIN) yr_pid = PID(PID_YR_P_GAIN, PID_YR_I_GAIN, PID_YR_D_GAIN) #------------------------------------------------------------------------------------------- # Set up the constants for motion fusion used if we have lateral and vertical distance / velocity # sensors. # - vvf, hvf, vdf, hdf flag set true for fusion to be triggered # - fusion_tau used for the fusion complementary filter #------------------------------------------------------------------------------------------- vvf = False hvf = False vdf = False hdf = False fusion_tau = 10 / fusion_rate #------------------------------------------------------------------------------------------ # Set the props spinning at their base rate to ensure initial kick-start doesn't get spotted # by the sensors messing up the flight thereafter. spin_pwm is determined by running testcase 1 # multiple times incrementing -h slowly until a level of PWM is found where all props just spin. # This depends on the firmware in the ESCs #------------------------------------------------------------------------------------------ print "Starting up the motors..." for esc in self.esc_list: esc.set(spin_pwm) #------------------------------------------------------------------------------------------- # Initialize the base setting of earth frame take-off height - i.e. the vertical distance from # the height sensor or the take-off platform / leg height if no sensor is available. #------------------------------------------------------------------------------------------- eftoh = 0.0 #------------------------------------------------------------------------------------------- # Get an initial take-off height #------------------------------------------------------------------------------------------- g_dist = 0.0 if self.gll_installed: print "Couple of seconds to let the LiDAR settle..." for ii in range(2 * fusion_rate): time.sleep(1 / fusion_rate) try: g_dist = gll.read() except ValueError as e: break eftoh += g_dist eftoh /= (2 * fusion_rate) #------------------------------------------------------------------------------------------- # The distance from grounds to the GLLv3 can't be measured accurately; hard code them. #------------------------------------------------------------------------------------------- if i_am_zoe: eftoh = 0.04 # meters elif i_am_penelope: eftoh = 0.18 # meters else: assert i_am_hermione, "Hey, I'm not supported" eftoh = 0.23 # meters #------------------------------------------------------------------------------------------- # Set up the GLL base values for the very rate case that g_* don't get set up (as they always # should) by gll.read() down in the core. #------------------------------------------------------------------------------------------- g_distance = eftoh g_velocity = 0.0 #------------------------------------------------------------------------------------------- # Set up the video macro-block parameters # Video supported upto 1080p @ 30Hz but restricted by speed of macro-block processing. #------------------------------------------------------------------------------------------- vmp = None vmpt = 0.0 pvmpt = 0.0 if self.camera_installed: print "Couple of seconds to let the video settle..." global frame_width global frame_height if i_am_penelope: # RPi 3B+ frame_width = 400 # an exact multiple of mb_size (16) elif i_am_hermione: # RPi 3B frame_width = 320 # an exact multiple of mb_size (16) elif i_am_zoe: # RPi 0W frame_width = 240 # an exact multiple of mb_size (16) frame_height = frame_width frame_rate = fusion_rate video_update = False #------------------------------------------------------------------------------------------ # Scale is the convertion from macro-blocks to meters at a given height. # - V1 camera angle of view (aov): 54 x 41 degrees # - V2 camera angle of view (aov): 62.2 x 48.8 degrees. # Because we're shooting a 320 x 320 video from with a V2 camera this means a macro-block is # 2 x height (h) x tan ( aov / 2) / 320 meters: # # ^ # /|\ # / | \ # / | \ # / h \ # / | \ # / | \ # / | \ # /_______v_______\ # # \______/V\______/ # # aov = 48.8 degrees # # The macro-block vector is the movement in pixels between frames. This is guessed by the # fact each vector can only be between +/- 128 in X and Y which allows for shifts up to # +/- 2048 pixels in a frame which seems reasonable given the h.264 compression. # # Testing has proven this true - all errors are just a percent or so - well within the # scope of the "nut behind the wheel" error. # # scale just needs to be multiplied by (macro-block shift x height) to produce the increment of # horizontal movement in meters. #------------------------------------------------------------------------------------------ camera_version = 2 aov = math.radians(48.8 if camera_version == 2 else 41) scale = 2 * math.tan(aov / 2) / frame_width #--------------------------------------------------------------------------------------- # Setup a shared memory based data stream for the PiCamera video motion output #--------------------------------------------------------------------------------------- os.mkfifo("/dev/shm/video_stream") video_process = subprocess.Popen(["python", __file__, "VIDEO", str(frame_width), str(frame_height), str(frame_rate)], preexec_fn = Daemonize) while True: try: video_fifo = io.open("/dev/shm/video_stream", mode="rb") except: continue else: break #--------------------------------------------------------------------------------------- # Register fd for polling #--------------------------------------------------------------------------------------- video_fd = video_fifo.fileno() poll.register(video_fd, select.POLLIN | select.POLLPRI) logger.warning("Video @, %d, %d, pixels, %d, fps", frame_width, frame_height, frame_rate) #-------------------------------------------------------------------------------------------- # Last chance to change your mind about the flight if all's ok so far #-------------------------------------------------------------------------------------------- rtg = "" if rc_control else raw_input("Ready when you are!") if len(rtg) != 0: print "OK, I'll skip at the next possible opportunity." self.keep_looping = False print "" print "################################################################################" print "# #" print "# Thunderbirds are go! #" print "# #" print "################################################################################" print "" ################################### INITIAL IMU READINGS ################################### #------------------------------------------------------------------------------------------- # Get IMU takeoff info. # Note the use of qr? as gyrometer results (i.e. rotation); qg? is gravity. #------------------------------------------------------------------------------------------- mpu6050.flushFIFO() qax = 0.0 qay = 0.0 qaz = 0.0 qrx = 0.0 qry = 0.0 qrz = 0.0 sigma_dt = 0.0 loops = 0 while sigma_dt < 1.0: # seconds time.sleep(FULL_FIFO_BATCHES / sampling_rate) nfb = mpu6050.numFIFOBatches() ax, ay, az, rx, ry, rz, dt = mpu6050.readFIFO(nfb) loops += 1 sigma_dt += dt qax += ax qay += ay qaz += az qrx += rx qry += ry qrz += rz qax /= loops qay /= loops qaz /= loops qrx /= loops qry /= loops qrz /= loops temp = mpu6050.readTemperature() logger.critical("IMU core temp (start): ,%f", temp / 333.86 + 21.0) #------------------------------------------------------------------------------------------- # Feed back the gyro offset calibration #------------------------------------------------------------------------------------------- mpu6050.setGyroOffsets(qrx, qry, qrz) #------------------------------------------------------------------------------------------- # Read the IMU acceleration to obtain angles and gravity. #------------------------------------------------------------------------------------------- qax, qay, qaz, qrx, qry, qrz = mpu6050.scaleSensors(qax, qay, qaz, qrx, qry, qrz) #------------------------------------------------------------------------------------------- # Calculate the angles - ideally takeoff should be on a horizontal surface but a few degrees # here or there won't matter. #------------------------------------------------------------------------------------------- pa, ra = GetRotationAngles(qax, qay, qaz) ya = 0.0 apa, ara = GetAbsoluteAngles(qax, qay, qaz) aya = 0.0 aya_fused = 0.0 # used for compass fusion apa_increment = 0.0 ara_increment = 0.0 aya_increment = 0.0 #------------------------------------------------------------------------------------------- # Get the value for gravity. #------------------------------------------------------------------------------------------- egx, egy, egz = RotateVector(qax, qay, qaz, -pa, -ra, -ya) eax = egx eay = egy eaz = egz #------------------------------------------------------------------------------------------- # Setup and prime the butterworth - 0.1Hz 8th order, primed with the stable measured above. #------------------------------------------------------------------------------------------- bfx = BUTTERWORTH(motion_rate, 0.1, 8, egx) bfy = BUTTERWORTH(motion_rate, 0.1, 8, egy) bfz = BUTTERWORTH(motion_rate, 0.1, 8, egz) #------------------------------------------------------------------------------------------- # The tilt ratio is used to compensate sensor height (and thus velocity) for the fact the # sensors are leaning. # # tilt ratio is derived from cos(tilt angle); # - tilt angle a = arctan(sqrt(x*x + y*y) / z) # - cos(arctan(a)) = 1 / (sqrt(1 + a*a)) # This all collapses down to the following. 0 <= Tilt ratio <= 1 #------------------------------------------------------------------------------------------- tilt_ratio = qaz / egz eftoh *= tilt_ratio #------------------------------------------------------------------------------------------- # Log the critical parameters from this warm-up: the take-off surface tilt, and gravity. # Note that some of the variables used above are used in the main processing loop. Messing # with the above code can have very unexpected effects in flight. #------------------------------------------------------------------------------------------- logger.warning("pitch, %f, roll, %f", math.degrees(pa), math.degrees(ra)) logger.warning("egx, %f, egy, %f, egz %f", egx, egy, egz) logger.warning("based upon %d samples", sigma_dt * sampling_rate) logger.warning("EFTOH:, %f", eftoh) #------------------------------------------------------------------------------------------- # Prime the direction vector of the earth's magnetic core to provide long term yaw stability. #------------------------------------------------------------------------------------------- mgx = 0.0 mgy = 0.0 mgz = 0.0 cya = 0.0 cya_base = 0.0 initial_orientation = 0.0 if self.compass_installed: #--------------------------------------------------------------------------------------- # Take 100 samples at the sampling rate #--------------------------------------------------------------------------------------- mgx_ave = 0.0 mgy_ave = 0.0 mgz_ave = 0.0 for ii in range(100): mgx, mgy, mgz = mpu6050.readCompass() mgx_ave += mgx mgy_ave += mgy mgz_ave += mgz time.sleep(1 / sampling_rate) mgx = mgx_ave / 100 mgy = mgy_ave / 100 mgz = mgz_ave / 100 #--------------------------------------------------------------------------------------- # Rotate compass readings back to earth plane and tweak to be 0 - 2 pi radians. # Local magnetic declination is -1o 5'. Declination is the angle between true and magnetic # north i.e. true + declination = magnetic #--------------------------------------------------------------------------------------- cay, cax, caz = RotateVector(mgy, -mgx, -mgz, -pa, -ra, 0.0) initial_orientation = (-math.atan2(cax, cay) + math.radians(1 + 5/60) + math.pi) % (2 * math.pi) - math.pi cya_base = math.atan2(cax, cay) logger.critical("Initial GPS orientation:, %f" % math.degrees(initial_orientation)) logger.critical("Initial yaw:, %f." % (math.degrees(cya_base))) ######################################### GO GO GO! ######################################## if self.autopilot_installed: #--------------------------------------------------------------------------------------- # Start the autopilot - use compass angle plus magnetic declination angle (1o 5') to pass # through the take-off orientation angle wrt GPS / true north #--------------------------------------------------------------------------------------- app = AutopilotManager(self.sweep_installed, self.gps_installed, self.compass_installed, initial_orientation, file_control, gps_control, fp_filename) autopilot_fifo = app.autopilot_fifo autopilot_fd = autopilot_fifo.fileno() elif not rc_control: #--------------------------------------------------------------------------------------- # Register the flight plan with the authorities #--------------------------------------------------------------------------------------- try: fp = FlightPlan(self, fp_filename) except Exception, err: print "%s error: %s" % (fp_filename, err) return #------------------------------------------------------------------------------------------- # Set up the various timing constants and stats. #------------------------------------------------------------------------------------------- start_flight = time.time() motion_dt = 0.0 fusion_dt = 0.0 gll_dt = 0.0 rc_dt = 0.0 sampling_loops = 0 motion_loops = 0 fusion_loops = 0 gll_loops = 0 video_loops = 0 autopilot_loops = 0 gll_dr_interrupts = 0 gll_misses = 0 #------------------------------------------------------------------------------------------- # Diagnostic log header #------------------------------------------------------------------------------------------- if diagnostics: pwm_header = "FL PWM, FR PWM, BL PWM, BR PWM" if i_am_zoe else "FLT PWM, FRT PWM, BLT PWM, BRT PWM, FLB PWM, FRB PWM, BLB PWM, BRB PWM" logger.warning("time, dt, loops, " + "temperature, " + "mgx, mgy, mgz, cya, " + "edx_fuse, edy_fuse, edz_fuse, " + "evx_fuse, evy_fuse, evz_fuse, " + "edx_target, edy_target, edz_target, " + "evx_target, evy_target, evz_target, " + "qrx, qry, qrz, " + "qax, qay, qaz, " + "eax, eay, eaz, " + "qgx, qgy, qgz, " + "egx, egy, egz, " + "pitch, roll, yaw, cya, ya_fused, " + # "qdx_input, qdy_input, qdz_input, " + # "qdx_target, qdy_target, qdz_target' " + # "qvx_input, qvy_input, qvz_input, " + # "qvx_target, qvy_target, qvz_target, " + # "qvz_out, " + # "pa_input, ra_input, ya_input, " + # "pa_target, ra_target, ya_target, " + # "pr_input, rr_input, yr_input, " + # "pr_target, rr_target, yr_target, " + # "pr_out, rr_out, yr_out, " + # "qdx_input, qdx_target, qvx_input, qvx_target, pa_input, pa_target, pr_input, pr_target, pr_out, " + # "qdy_input, qdy_target, qvy_input, qvy_target, ra_input, ra_target, rr_input, rr_target, rr_out, " + # "qdz_input, qdz_target, qvz_input, qvz_target, qvz_out, " + "ya_input, ya_target, yr_input, yr_target, yr_out, " + pwm_header) #------------------------------------------------------------------------------------------- # Flush the video motion FIFO - historically sweep and GPS fed into here too, hence the OTT # way of emptying what's now just video #------------------------------------------------------------------------------------------- if self.camera_installed: vmp = VideoManager(video_fifo, 0) video_flush = 0 flushing = True while flushing: results = poll.poll(0.0) for fd, event in results: if fd == video_fd: video_flush += vmp.flush() else: if len(results) == 0: flushing = False else: print "Video Flush: %d" % video_flush vmp = None #------------------------------------------------------------------------------------------- # Only once the video FIFO has been flushed can the autopilot / rc fd be added to the polling. #------------------------------------------------------------------------------------------- if self.autopilot_installed: poll.register(autopilot_fd, select.POLLIN | select.POLLPRI) elif rc_control: #--------------------------------------------------------------------------------------- # Accept RC connection and send go-go-go #--------------------------------------------------------------------------------------- rc_fd = self.rc.connect() poll.register(rc_fd, select.POLLIN | select.POLLPRI) #------------------------------------------------------------------------------------------- # Flush the IMU FIFO and enable the FIFO overflow interrupt #------------------------------------------------------------------------------------------- GPIO.event_detected(GPIO_FIFO_OVERFLOW_INTERRUPT) mpu6050.flushFIFO() mpu6050.enableFIFOOverflowISR() #=========================================================================================== # # Motion and PID processing loop naming conventions # # qd* = quad frame distance # qv* = quad frame velocity # qa? = quad frame acceleration # qg? = quad frame gravity # qr? = quad frame rotation # ea? = earth frame acceleration # eg? = earth frame gravity # ua? = euler angles between frames # ur? = euler rotation between frames # a?a = absoluted angles between frames # #=========================================================================================== while self.keep_looping: ############################### SENSOR INPUT SCHEDULING ################################ #--------------------------------------------------------------------------------------- # Check on the number of IMU batches already stashed in the FIFO, and if not enough, # check autopilot and video, and ultimate sleep. #--------------------------------------------------------------------------------------- nfb = mpu6050.numFIFOBatches() if nfb >= self.FIFO_MAXIMUM: logger.critical("ABORT: FIFO too full risking overflow: %d.", nfb) if vmp != None: logger.critical(" Next VFP phase: %d", vmp.phase) break if nfb < self.FIFO_MINIMUM: #----------------------------------------------------------------------------------- # Assume that initially we have time to wait for external sensors #----------------------------------------------------------------------------------- timeout = (self.FIFO_MINIMUM - nfb) / sampling_rate #----------------------------------------------------------------------------------- # We have some spare time before we need to run the next motion processing; see if # there's any processing we can do. First, have we already got a video frame we can # continue processing? #----------------------------------------------------------------------------------- if vmp != None: result = vmp.process() if result != None: vvx, vvy = result vvx *= scale vvy *= scale video_update = True vmp = None #------------------------------------------------------------------------------- # If we've done a video loop, still check the other sensors, but don't sleep polling. # Previously, this was a 'continue'; this gives a better priorities over these # inputs but risks completely ruling out below inputs if video processing takes too long. #------------------------------------------------------------------------------- if True: timeout = 0.0 else: continue #----------------------------------------------------------------------------------- # Check for other external data sources with lower priority or performance impact. #----------------------------------------------------------------------------------- try: results = poll.poll(timeout * 1000) except: logger.critical("ABORT: poll error") break for fd, event in results: if self.autopilot_installed and fd == autopilot_fd: #--------------------------------------------------------------------------- # Run the Autopilot Processor to get the latest stage of the flight plan. #--------------------------------------------------------------------------- autopilot_loops += 1 evx_target, evy_target, evz_target, state_name, self.keep_looping = app.read() logger.critical(state_name) if "PROXIMITY" in state_name: if not GPIO.input(GPIO_BUZZER): GPIO.output(GPIO_BUZZER, GPIO.HIGH) elif GPIO.input(GPIO_BUZZER): GPIO.output(GPIO_BUZZER, GPIO.LOW) if rc_control and fd == rc_fd: #--------------------------------------------------------------------------- # Get the WiFi targets etc e.g. make sure keep_looping from rc is triggered # somehow between flights #--------------------------------------------------------------------------- evx_target, evy_target, evz_target, eyr_target, rc_status, rc_beep = self.rc.read() if rc_status != self.rc_status: self.rc_status = rc_status logger.critical(rc_status_name[rc_status]) if self.rc_status == RC_DONE or self.rc_status == RC_ABORT: self.keep_looping = False rc_dt = 0.0 if self.camera_installed and fd == video_fd and vmp == None and not video_update: #--------------------------------------------------------------------------- # Run the Video Motion Processor. #--------------------------------------------------------------------------- vmp_dt = vmpt - pvmpt pvmpt = vmpt apa_fusion = apa_increment ara_fusion = ara_increment aya_fusion = aya_increment apa_increment = 0.0 ara_increment = 0.0 aya_increment = 0.0 try: vmp = VideoManager(video_fifo, aya_fusion) ''' #---------------------------------------------------------------------- # Annoyingly, despite having flushed the video stream just above prior to # takeoff, it only seems to flush the last 32 MBs max meaning there are # several backlogged at this point. vmp_dt == 0.0 signifies backlog which # all gets clearer prior to any significant processing below. I don't # like this, but can't see how to stop it. #---------------------------------------------------------------------- ''' if vmp_dt == 0.0: vmp.flush() vmp = None else: video_loops += 1 vmp.process() except ValueError as e: #----------------------------------------------------------------------- # First pass of the video frame shows no movement detected, and thus no # further processing. #----------------------------------------------------------------------- vmp = None #----------------------------------------------------------------------------------- # We had free time, do we still? Better check. #----------------------------------------------------------------------------------- continue ####################################### IMU FIFO ####################################### #--------------------------------------------------------------------------------------- # Before proceeding further, check the FIFO overflow interrupt to ensure we didn't sleep # too long #--------------------------------------------------------------------------------------- ''' if GPIO.event_detected(GPIO_FIFO_OVERFLOW_INTERRUPT): logger.critical("ABORT: FIFO overflow.") break ''' #--------------------------------------------------------------------------------------- # Power brownout check - doesn't work on 3B onwards #--------------------------------------------------------------------------------------- ''' if GPIO.event_detected(GPIO_POWER_BROWN_OUT_INTERRUPT): logger.critical("ABORT: Brown-out.") break ''' #--------------------------------------------------------------------------------------- # Now get the batch of averaged data from the FIFO. #--------------------------------------------------------------------------------------- try: qax, qay, qaz, qrx, qry, qrz, motion_dt = mpu6050.readFIFO(nfb) except IOError as err: logger.critical("ABORT: IMU problem.") for arg in err.args: logger.critical(" %s", arg) break #--------------------------------------------------------------------------------------- # Sort out units and calibration for the incoming data #--------------------------------------------------------------------------------------- qax, qay, qaz, qrx, qry, qrz = mpu6050.scaleSensors(qax, qay, qaz, qrx, qry, qrz) #--------------------------------------------------------------------------------------- # Track the number of motion loops and sampling loops. motion_dt on which their are based # are the core timing provided by the IMU and are used for all timing events later such # as integration and PID Intergral and Differential factors. #--------------------------------------------------------------------------------------- motion_loops += 1 sampling_loops += motion_dt * sampling_rate fusion_dt += motion_dt gll_dt += motion_dt rc_dt += motion_dt vmpt += motion_dt #--------------------------------------------------------------------------------------- # If we're on RC control, and we've heard nothing from it in 0.5 seconds, abort. The RC # sends requests at 5Hz. #AB: Ideally this should be an ordered landing by permanently override the flights #AB: but this'll do for now. #--------------------------------------------------------------------------------------- if rc_control and rc_dt > 0.5: # seconds logger.critical("ABORT: RC lost") break ################################## ANGLES PROCESSING ################################### #--------------------------------------------------------------------------------------- # Euler angle fusion: Merge the 'integral' of the previous euler rotation rates with # the noisy accelermeter current values. Keep yaw within +/- pi radians #--------------------------------------------------------------------------------------- urp, urr, ury = Body2EulerRates(qry, qrx, qrz, pa, ra) pa += urp * motion_dt ra += urr * motion_dt ya += ury * motion_dt ya = (ya + math.pi) % (2 * math.pi) - math.pi upa, ura = GetRotationAngles(qax, qay, qaz) atau_fraction = atau / (atau + motion_dt) pa = atau_fraction * pa + (1 - atau_fraction) * upa ra = atau_fraction * ra + (1 - atau_fraction) * ura #--------------------------------------------------------------------------------------- # Absolute angle fusion: Merge the 'integral' of the gyro rotation rates with # the noisy accelermeter current values. Keep yaw within +/- pi radians #--------------------------------------------------------------------------------------- apa += qry * motion_dt ara += qrx * motion_dt aya += qrz * motion_dt aya = (aya + math.pi) % (2 * math.pi) - math.pi upa, ura = GetAbsoluteAngles(qax, qay, qaz) atau_fraction = atau / (atau + motion_dt) apa = atau_fraction * apa + (1 - atau_fraction) * upa ara = atau_fraction * ara + (1 - atau_fraction) * ura apa_increment += qry * motion_dt ara_increment += qrx * motion_dt aya_increment += qrz * motion_dt ''' #AB! If apa or ara > 90 degrees, abort? Problem here is then falling on her side which #AB! may be worst than flipping. Is it better to have combination of acceleration and gll_installed #AB! both suggesting upside down? ''' ############################### IMU VELOCITY / DISTANCE ################################ #--------------------------------------------------------------------------------------- # Low pass butterworth filter to account for long term drift to the IMU due to temperature # drift - this happens significantly in a cold environment. # Note the butterworth can be disabled by deleting one surrounding pair of '''. #--------------------------------------------------------------------------------------- ''' eax, eay, eaz = RotateVector(qax, qay, qaz, -pa, -ra, -ya) egx = bfx.filter(eax) egy = bfy.filter(eay) egz = bfz.filter(eaz) ''' qgx, qgy, qgz = RotateVector(egx, egy, egz, pa, ra, ya) #--------------------------------------------------------------------------------------- # The tilt ratio is the ratio of gravity measured in the quad-frame Z axis and total gravity. # It's used to compensate for LiDAR height (and thus velocity) for the fact the laser may # not be pointing directly vertically down. # # - tilt angle a = arctan(sqrt(x*x + y*y) / z) # - compensated height = cos(arctan(a)) = 1 / (sqrt(1 + a*a)) # # http://www.rapidtables.com/math/trigonometry/arctan/cos-of-arctan.htm # #--------------------------------------------------------------------------------------- tilt_ratio = qgz / egz #==================== Velocity and Distance Increment processing ======================= #--------------------------------------------------------------------------------------- # Delete reorientated gravity from raw accelerometer readings and integrate over time # to make velocity all in quad frame. #--------------------------------------------------------------------------------------- qvx_increment = (qax - qgx) * GRAV_ACCEL * motion_dt qvy_increment = (qay - qgy) * GRAV_ACCEL * motion_dt qvz_increment = (qaz - qgz) * GRAV_ACCEL * motion_dt qvx_input += qvx_increment qvy_input += qvy_increment qvz_input += qvz_increment #--------------------------------------------------------------------------------------- # Integrate again the velocities to get distance. #--------------------------------------------------------------------------------------- qdx_increment = qvx_input * motion_dt qdy_increment = qvy_input * motion_dt qdz_increment = qvz_input * motion_dt qdx_input += qdx_increment qdy_input += qdy_increment qdz_input += qdz_increment ######################## ABSOLUTE DISTANCE / ORIENTATION SENSORS ####################### #--------------------------------------------------------------------------------------- # Read the compass to determine yaw and orientation. #--------------------------------------------------------------------------------------- if self.compass_installed: mgx, mgy, mgz = mpu6050.readCompass() #----------------------------------------------------------------------------------- # Rotate compass readings back to earth plane and align with gyro rotation direction. #----------------------------------------------------------------------------------- cay, cax, caz = RotateVector(mgy, -mgx, -mgz, -pa, -ra, 0.0) cya = math.atan2(cax, cay) cya = ((cya - cya_base) + math.pi) % (2 * math.pi) - math.pi ya_tau = 1.0 ya_fraction = ya_tau / (ya_tau + motion_dt) aya_fused = ya_fraction * (aya_fused + qrz * motion_dt) + (1 - ya_fraction) * cya aya_fused = (aya_fused + math.pi) % (2 * math.pi) - math.pi ''' #AB!-------------------------------------------------------------------------------- #AB! For the moment, yaw fusion of compass and integrated gyro is disabled. #AB: 1. yaw_control with a setting of yaw change of 180 degrees will cause an awful #AB! mess due to the 'noise' causing compass flipping backways and forwards between #AB! +/- 180. #AB! 2. Hermione is too heavy, meaning to perform intentional yaw results in PWM #AB! overflow - this is very bad as it actually stops the motors; lowing the yaw #AB! and yaw rate PID gains to prevent this then reduced stability in !yaw_control. #AB! 3. Worse than the above, the motors seem to produce variable magnetic fields #AB! such that the compass value shift as the motors rates changes. Even in a #AB! zero-yaw target flight, this shifts the compass by 40 degrees from the #AB! unpowered motor compass calibration values. #AB!-------------------------------------------------------------------------------- aya = aya_fused ''' #======================================================================================= # Acquire vertical distance (height) first, prioritizing the best sensors, # Garmin LiDAR-Lite first. We need get this every motion processing loop so it's always # up to date at the point we use it for camera lateral tracking. #======================================================================================= ''' #AB! Can we get a data ready interrupt working here? Failed so far. Better if so to reduce #AB! motion processing and as a result, perhaps be Zoe working. Until that's available, #AB! then next best option is to only read the GLL when we have video data worth processing. if GPIO.event_detected(GPIO_GLL_DR_INTERRUPT): gll_dr_interrupts += 1 ''' if self.gll_installed and video_update: gll_loops += 1 try: g_distance = gll.read() except ValueError as e: #------------------------------------------------------------------------------- # Too far or poor reflection (windy wobbles?) for the GLL to work. #------------------------------------------------------------------------------- gll_misses += 1 else: pass finally: #------------------------------------------------------------------------------- # We may have a new value, or may be using the previous one. This is the best # compromise that then is used below for video lateral tracking. #------------------------------------------------------------------------------- evz_fuse = ((g_distance * tilt_ratio - eftoh) - edz_fuse) / gll_dt edz_fuse = g_distance * tilt_ratio - eftoh gll_dt = 0.0 #------------------------------------------------------------------------------- # Set the flags for vertical velocity and distance fusion #------------------------------------------------------------------------------- vvf = True vdf = True gll_update = True #======================================================================================= # Acquire horizontal distance next, again with prioritization of accuracy #======================================================================================= #--------------------------------------------------------------------------------------- # If the camera is installed, and we have an absolute height measurement, get the horizontal # distance and velocity. #AB: gll_update if added above and test here would always be true. #--------------------------------------------------------------------------------------- if self.camera_installed and video_update and self.gll_installed and gll_update: #----------------------------------------------------------------------------------- # Take the increment of the scaled X and Y distance, and muliply by the height to # get the absolute position, allowing for tilt increment. #----------------------------------------------------------------------------------- edx_increment = g_distance * tilt_ratio * (vvx + apa_fusion) edy_increment = g_distance * tilt_ratio * (vvy - ara_fusion) #----------------------------------------------------------------------------------- # Unraw the video results back to get true earth frame direction increments. #----------------------------------------------------------------------------------- edx_increment, edy_increment, __ = RotateVector(edx_increment, edy_increment, 0.0, 0.0, 0.0, -ya) #----------------------------------------------------------------------------------- # Add the incremental distance to the total distance, and differentiate against time for # velocity. #----------------------------------------------------------------------------------- edx_fuse += edx_increment edy_fuse += edy_increment evx_fuse = edx_increment / vmp_dt evy_fuse = edy_increment / vmp_dt #----------------------------------------------------------------------------------- # Set the flags for horizontal distance and velocity fusion #----------------------------------------------------------------------------------- hdf = True hvf = True video_update = False gll_update = False ######################################## FUSION ######################################## #--------------------------------------------------------------------------------------- # If we have new full set of data, fuse it. #--------------------------------------------------------------------------------------- if vvf and vdf and hvf and hdf: qdx_fuse, qdy_fuse, qdz_fuse = RotateVector(edx_fuse, edy_fuse, edz_fuse, pa, ra, ya) qvx_fuse, qvy_fuse, qvz_fuse = RotateVector(evx_fuse, evy_fuse, evz_fuse, pa, ra, ya) fusion_fraction = fusion_tau / (fusion_tau + fusion_dt) qvx_input = fusion_fraction * qvx_input + (1 - fusion_fraction) * qvx_fuse qdx_input = fusion_fraction * qdx_input + (1 - fusion_fraction) * qdx_fuse qvy_input = fusion_fraction * qvy_input + (1 - fusion_fraction) * qvy_fuse qdy_input = fusion_fraction * qdy_input + (1 - fusion_fraction) * qdy_fuse qvz_input = fusion_fraction * qvz_input + (1 - fusion_fraction) * qvz_fuse qdz_input = fusion_fraction * qdz_input + (1 - fusion_fraction) * qdz_fuse fusion_loops += 1 fusion_dt = 0.0 #----------------------------------------------------------------------------------- # Clear the flags for vertical distance and velocity fusion #----------------------------------------------------------------------------------- hdf = False hvf = False vdf = False vvf = False ########################### VELOCITY / DISTANCE PID TARGETS ############################ if not self.autopilot_installed and not rc_control: #----------------------------------------------------------------------------------- # Check the flight plan for earth frame velocity and distance targets. #----------------------------------------------------------------------------------- evx_target, evy_target, evz_target, edx_target, edy_target, edz_target = fp.getTargets(motion_dt) if edz_fuse > edz_target + 0.5: logger.critical("ABORT: Height breach! %f target, %f actual", edz_target, edz_fuse) break #--------------------------------------------------------------------------------------- # Convert earth-frame distance targets to quadcopter frame. #--------------------------------------------------------------------------------------- edx_target += evx_target * motion_dt edy_target += evy_target * motion_dt edz_target += evz_target * motion_dt qdx_target, qdy_target, qdz_target = RotateVector(edx_target, edy_target, edz_target, pa, ra, ya) #--------------------------------------------------------------------------------------- # If using RC, take yaw from the rotation and integrated rotation rate target to yaw angle target #--------------------------------------------------------------------------------------- if rc_control: qdx_target, qdy_target, qdz_target = RotateVector(edx_target, edy_target, edz_target, pa, ra, 0.0) ya_target += eyr_target * motion_dt ya_target = (ya_target + math.pi) % (2 * math.pi) - math.pi ########### QUAD FRAME VELOCITY / DISTANCE / ANGLE / ROTATION PID PROCESSING ########### #======================================================================================= # Distance PIDs #======================================================================================= [p_out, i_out, d_out] = qdx_pid.Compute(qdx_input, qdx_target, motion_dt) qvx_target = p_out + i_out + d_out [p_out, i_out, d_out] = qdy_pid.Compute(qdy_input, qdy_target, motion_dt) qvy_target = p_out + i_out + d_out [p_out, i_out, d_out] = qdz_pid.Compute(qdz_input, qdz_target, motion_dt) qvz_target = p_out + i_out + d_out if yaw_control and not (abs(evx_target) + abs(evy_target) == 0.0): #----------------------------------------------------------------------------------- # Under yaw control, the piDrone only moves forwards, and it's yaw which manages # turning to do the right direction. Hence force qv?_input and targets such they only # do that. #----------------------------------------------------------------------------------- qvx_target = math.pow(math.pow(qvx_target, 2) + math.pow(qvy_target, 2), 0.5) qvy_target = 0.0 ''' ''' #--------------------------------------------------------------------------------------- # Constrain the target velocity to 1.5m/s. #--------------------------------------------------------------------------------------- MAX_VEL = 1.5 qvx_target = qvx_target if abs(qvx_target) < MAX_VEL else (qvx_target / abs(qvx_target) * MAX_VEL) qvy_target = qvy_target if abs(qvy_target) < MAX_VEL else (qvy_target / abs(qvy_target) * MAX_VEL) qvz_target = qvz_target if abs(qvz_target) < MAX_VEL else (qvz_target / abs(qvz_target) * MAX_VEL) ''' ''' #======================================================================================= # Velocity PIDs #======================================================================================= [p_out, i_out, d_out] = qvx_pid.Compute(qvx_input, qvx_target, motion_dt) qax_target = p_out + i_out + d_out [p_out, i_out, d_out] = qvy_pid.Compute(qvy_input, qvy_target, motion_dt) qay_target = p_out + i_out + d_out [p_out, i_out, d_out] = qvz_pid.Compute(qvz_input, qvz_target, motion_dt) qaz_out = p_out + i_out + d_out #--------------------------------------------------------------------------------------- # We now need to convert desired acceleration to desired angles before running the angular # PIDs. Via the right hand rule: # # A positive x-axis acceleration (fore) needs a nose-down lean which is a positive # rotation around the y axis # A positive y-axis acceleration (port) needs a port-down lean which is a negative # rotation around the x axis # # If yaw control is enabled, the yaw angle target is set such that she's facing the way # she should be travelling based upon the earth frame velocity targets. If these # targets are zero, then no yaw happens. # # If yaw control is disabled, the yaw angle target is zero - she always points in the # direction she took off in. # # Note this must use atan2 to safely handle division by 0. #--------------------------------------------------------------------------------------- pa_target = math.atan(qax_target) ra_target = -math.atan(qay_target) ya_target = ya_target if not yaw_control else (ya_target if (abs(evx_target) + abs(evy_target)) == 0 else math.atan2(evy_target, evx_target)) ''' ''' #--------------------------------------------------------------------------------------- # Constrain the target pitch / roll angle to 30 degrees. #--------------------------------------------------------------------------------------- MAX_ANGLE = math.pi / 6 pa_target = pa_target if abs(pa_target) < MAX_ANGLE else (pa_target / abs(pa_target) * MAX_ANGLE) ra_target = ra_target if abs(ra_target) < MAX_ANGLE else (ra_target / abs(ra_target) * MAX_ANGLE) ''' ''' #====================================================================================== # Angle PIDs #====================================================================================== [p_out, i_out, d_out] = pa_pid.Compute(apa, pa_target, motion_dt) pr_target = p_out + i_out + d_out [p_out, i_out, d_out] = ra_pid.Compute(ara, ra_target, motion_dt) rr_target = p_out + i_out + d_out [p_out, i_out, d_out] = ya_pid.Compute(aya, ya_target, motion_dt) yr_target = p_out + i_out + d_out ''' ''' #--------------------------------------------------------------------------------------- # Constrain the target yaw rotation rate to 90 degrees / second. #--------------------------------------------------------------------------------------- MAX_RATE = math.pi / 2 # per-second yr_target = yr_target if abs(yr_target) < MAX_RATE else (yr_target / abs(yr_target) * MAX_RATE) ''' ''' #======================================================================================= # Rotation rate PIDs #======================================================================================= #--------------------------------------------------------------------------------------- # START TESTCASE 2 CODE: Override motion processing results; take-off from horizontal # platform, tune the pr*_gain and rr*_gain PID gains for # stability. #--------------------------------------------------------------------------------------- if test_case == 2: pr_target = 0.0 rr_target = 0.0 yr_target = 0.0 #--------------------------------------------------------------------------------------- # END TESTCASE 2 CODE: Override motion processing results; take-off from horizontal # platform, tune the pr*_gain and rr*_gain PID gains for # stability. #--------------------------------------------------------------------------------------- [p_out, i_out, d_out] = pr_pid.Compute(qry, pr_target, motion_dt) pr_out = p_out + i_out + d_out [p_out, i_out, d_out] = rr_pid.Compute(qrx, rr_target, motion_dt) rr_out = p_out + i_out + d_out [p_out, i_out, d_out] = yr_pid.Compute(qrz, yr_target, motion_dt) yr_out = p_out + i_out + d_out ################################## PID OUTPUT -> PWM CONVERSION ######################## #--------------------------------------------------------------------------------------- # Convert the vertical velocity PID output direct to ESC input PWM pulse width. #--------------------------------------------------------------------------------------- vert_out = hover_pwm + qaz_out #--------------------------------------------------------------------------------------- # Convert the rotation rate PID outputs direct to ESC input PWM pulse width #--------------------------------------------------------------------------------------- pr_out /= 2 rr_out /= 2 yr_out /= 2 #======================================================================================= # PID output distribution: Walk through the ESCs, and apply the PID outputs i.e. the # updates PWM pulse widths according to where the ESC is sited on the frame #======================================================================================= for esc in self.esc_list: #----------------------------------------------------------------------------------- # Update all blades' power in accordance with the z error #----------------------------------------------------------------------------------- pulse_width = vert_out #----------------------------------------------------------------------------------- # For a left downwards roll, the x gyro goes negative, so the PID error is positive, # meaning PID output is positive, meaning this needs to be added to the left blades # and subtracted from the right. #----------------------------------------------------------------------------------- pulse_width -= (rr_out if esc.motor_location & self.MOTOR_LOCATION_RIGHT else -rr_out) #----------------------------------------------------------------------------------- # For a forward downwards pitch, the y gyro goes positive The PID error is negative as a # result, meaning PID output is negative, meaning this needs to be subtracted from the # front blades and added to the back. #----------------------------------------------------------------------------------- pulse_width += (pr_out if esc.motor_location & self.MOTOR_LOCATION_BACK else -pr_out) #----------------------------------------------------------------------------------- # For CW yaw, the z gyro goes negative, so the PID error is postitive, meaning PID # output is positive, meaning this need to be added to the ACW (FL and BR) blades and # subtracted from the CW (FR & BL) blades. #----------------------------------------------------------------------------------- pulse_width += (yr_out if esc.motor_rotation == self.MOTOR_ROTATION_CW else -yr_out) #----------------------------------------------------------------------------------- # Ensure the props don't stop in poorly tuned scenarios. #----------------------------------------------------------------------------------- if pulse_width < spin_pwm: pulse_width = spin_pwm ''' logger.critical("PWM BREACH!") ''' #----------------------------------------------------------------------------------- # Apply the blended outputs to the esc PWM signal #----------------------------------------------------------------------------------- esc.set(int(round(pulse_width))) ''' esc.set(stfu_pwm) ''' #--------------------------------------------------------------------------------------- # Diagnostic log - every motion loop #--------------------------------------------------------------------------------------- if diagnostics: temp = mpu6050.readTemperature() pwm_data = "%d, %d, %d, %d" % (self.esc_list[0].pulse_width, self.esc_list[1].pulse_width, self.esc_list[2].pulse_width, self.esc_list[3].pulse_width) if i_am_zoe else "%d, %d, %d, %d, %d, %d, %d, %d" % (self.esc_list[0].pulse_width, self.esc_list[1].pulse_width, self.esc_list[2].pulse_width, self.esc_list[3].pulse_width, self.esc_list[4].pulse_width, self.esc_list[5].pulse_width, self.esc_list[6].pulse_width, self.esc_list[7].pulse_width) logger.warning("%f, %f, %d, " % (sampling_loops / sampling_rate, motion_dt, sampling_loops) + "%f, " % (temp / 333.86 + 21) + "%f, %f, %f, %f, " % (mgx, mgy, mgz, math.degrees(cya)) + "%f, %f, %f, " % (edx_fuse, edy_fuse, edz_fuse) + "%f, %f, %f, " % (evx_fuse, evy_fuse, evz_fuse) + "%f, %f, %f, " % (edx_target, edy_target, edz_target) + "%f, %f, %f, " % (evx_target, evy_target, evz_target) + "%f, %f, %f, " % (qrx, qry, qrz) + "%f, %f, %f, " % (qax, qay, qaz) + "%f, %f, %f, " % (eax, eay, eaz) + "%f, %f, %f, " % (qgx, qgy, qgz) + "%f, %f, %f, " % (egx, egy, egz) + "%f, %f, %f, %f, %f, " % (math.degrees(pa), math.degrees(ra), math.degrees(ya), math.degrees(cya), math.degrees(aya_fused)) + # "%f, %f, %f, " % (qdx_input, qdy_input, qdz_input) + # "%f, %f, %f, " % (qdx_target, qdy_target, qdz_target) + # "%f, %f, %f, " % (qvx_input, qvy_input, qvz_input) + # "%f, %f, %f, " % (qvx_target, qvy_target, qvz_target) + # "%f, " % qvz_out + # "%f, %f, %f, " % (math.degrees(apa), math.degrees(ara), math.degrees(aya)) + # "%f, %f, %f, " % (math.degrees(pa_target), math.degrees(ra_target), math.degrees(ya_target) + # "%f, %f, %f, " % (math.degrees(qry), math.degrees(qrx), math.degrees(qrz)) + # "%f, %f, %f, " % (math.degrees(pr_target), math.degrees(rr_target), math.degrees(yr_target)) + # "%f, %f, %f, " % (math.degrees(pr_out), math.degrees(rr_out), math.degrees(yr_out)) + # "%f, %f, %f, %f, %f, %f, %f, %f, %d, " % (qdx_input, qdx_target, qvx_input, qvx_target, math.degrees(apa), math.degrees(pa_target), math.degrees(qry), math.degrees(pr_target), pr_out) + # "%f, %f, %f, %f, %f, %f, %f, %f, %d, " % (qdy_input, qdy_target, qvy_input, qvy_target, math.degrees(ara), math.degrees(ra_target), math.degrees(qrx), math.degrees(rr_target), rr_out) + # "%f, %f, %f, %f, %d, " % (qdz_input, qdz_target, qvz_input, qvz_target, qaz_out) + "%f, %f, %f, %f, %d, " % (math.degrees(aya), math.degrees(ya_target), math.degrees(qrz), math.degrees(yr_target), yr_out) + pwm_data) logger.critical("Flight time %f", time.time() - start_flight) logger.critical("Sampling loops: %d", sampling_loops) logger.critical("Motion processing loops: %d", motion_loops) logger.critical("Fusion processing loops: %d", fusion_loops) logger.critical("Autopilot processing loops: %d.", autopilot_loops) logger.critical("GLL processing loops: %d", gll_loops) logger.critical("GLL missed: %d", gll_misses) logger.critical("GLL DR Interrupts: %d.", gll_dr_interrupts) if sampling_loops != 0: logger.critical("Video frame rate: %f", video_loops * sampling_rate / sampling_loops ) temp = mpu6050.readTemperature() logger.critical("IMU core temp (end): ,%f", temp / 333.86 + 21.0) max_az, min_az, max_gx, min_gx, max_gy, min_gy, max_gz, min_gz, = mpu6050.getStats() logger.critical("Max Z acceleration: %f", max_az) logger.critical("Min Z acceleration: %f", min_az) logger.critical("Max X gyrometer: %f", max_gx) logger.critical("Min X gyrometer: %f", min_gx) logger.critical("Max Y gyrometer: %f", max_gy) logger.critical("Min Y gyrometer: %f", min_gy) logger.critical("Max Z gyrometer: %f", max_gz) logger.critical("Min Z gyrometer: %f", min_gz) #------------------------------------------------------------------------------------------- # Stop the PWM and FIFO overflow interrupt between flights #------------------------------------------------------------------------------------------- for esc in self.esc_list: esc.set(stfu_pwm) mpu6050.disableFIFOOverflowISR() #------------------------------------------------------------------------------------------- # Stop the buzzer. #------------------------------------------------------------------------------------------- GPIO.output(GPIO_BUZZER, GPIO.LOW) #------------------------------------------------------------------------------------------- # Unregister poll registrars #------------------------------------------------------------------------------------------- if self.autopilot_installed: poll.unregister(autopilot_fd) if self.camera_installed: poll.unregister(video_fd) if rc_control: poll.unregister(rc_fd) self.rc.disconnect() #------------------------------------------------------------------------------------------- # Stop the Camera process if it's still running, and clean up the FIFO. #------------------------------------------------------------------------------------------- if self.camera_installed: print "Stopping video... ", try: if video_process.poll() == None: video_process.send_signal(signal.SIGINT) video_process.wait() except KeyboardInterrupt as e: pass video_fifo.close() os.unlink("/dev/shm/video_stream") print "stopped." #------------------------------------------------------------------------------------------- # Stop the autopilot #------------------------------------------------------------------------------------------- if self.autopilot_installed: print "Stopping autopilot... ", app.cleanup() print "stopped." ################################################################################################ # # Shutdown triggered by early Ctrl-C or end of script # ################################################################################################ def shutdown(self): #------------------------------------------------------------------------------------------- # Stop the signal handler #------------------------------------------------------------------------------------------- signal.signal(signal.SIGINT, signal.SIG_IGN) #------------------------------------------------------------------------------------------- # Stop the blades spinning #------------------------------------------------------------------------------------------- for esc in self.esc_list: esc.set(stfu_pwm) #------------------------------------------------------------------------------------------- # Close stats logging file. #------------------------------------------------------------------------------------------- file_handler.close() #------------------------------------------------------------------------------------------- # Unlock memory we've used from RAM #------------------------------------------------------------------------------------------- munlockall() #------------------------------------------------------------------------------------------- # Clean up PWM / GPIO, but pause beforehand to give the ESCs time to stop properly #------------------------------------------------------------------------------------------- time.sleep(1.0) PWMTerm() #------------------------------------------------------------------------------------------- # Clean up the GPIO FIFO Overflow ISR #------------------------------------------------------------------------------------------- GPIOTerm() #------------------------------------------------------------------------------------------- # Reset the signal handler to default #------------------------------------------------------------------------------------------- signal.signal(signal.SIGINT, signal.SIG_DFL) sys.exit(0) #################################################################################################### # # Signal handler for Ctrl-C => abort cleanly; should really be just a "try: except KeyboardInterrupt:" # #################################################################################################### def shutdownSignalHandler(self, signal, frame): if not self.keep_looping: self.shutdown() self.keep_looping = False #################################################################################################### # # Interrupt Service Routine for FIFO overflow => abort flight cleanly - RETIRED, JUST POLL NOW # #################################################################################################### def fifoOverflowISR(self, pin): if self.keep_looping: print "FIFO OVERFLOW, ABORT" self.keep_looping = False #################################################################################################### # If we've been called directly, this is the spawned video, GPS, Sweep or autopilot process or a # misinformed user trying to start the code. #################################################################################################### if __name__ == '__main__': if len(sys.argv) >= 2: #------------------------------------------------------------------------------------------- # Start the process recording video macro-blocks #------------------------------------------------------------------------------------------- if sys.argv[1] == "VIDEO": assert (len(sys.argv) == 5), "Bad parameters for Video" frame_width = int(sys.argv[2]) frame_height = int(sys.argv[3]) frame_rate = int(sys.argv[4]) VideoProcessor(frame_width, frame_height, frame_rate) #------------------------------------------------------------------------------------------- # Start the process recording GPS #------------------------------------------------------------------------------------------- elif sys.argv[1] == "GPS": assert (len(sys.argv) == 2), "Bad parameters for GPS" GPSProcessor() #------------------------------------------------------------------------------------------- # Start the process recording Sweep #------------------------------------------------------------------------------------------- elif sys.argv[1] == "SWEEP": assert (len(sys.argv) == 2), "Bad parameters for Sweep" SweepProcessor() #------------------------------------------------------------------------------------------- # Start the process recording Autopilot #------------------------------------------------------------------------------------------- elif sys.argv[1] == "AUTOPILOT": assert (len(sys.argv) == 9), "Bad parameters for Autopilot" sweep_installed = True if (sys.argv[2] == "True") else False gps_installed = True if (sys.argv[3] == "True") else False compass_installed = True if (sys.argv[4] == "True") else False initial_orientation = float(sys.argv[5]) file_control = True if (sys.argv[6] == "True") else False gps_control = True if (sys.argv[7] == "True") else False fp_filename = sys.argv[8] AutopilotProcessor(sweep_installed, gps_installed, compass_installed, initial_orientation, file_control, gps_control, fp_filename) else: assert (False), "Invalid process request." else: print "If you're trying to run me, use 'sudo python ./qc.py'"
PiStuffing/Quadcopter
Quadcopter.py
Python
gpl-2.0
267,801
/* * Cirrus Logic EP93xx ethernet MAC / MII driver. * * Copyright (C) 2009 Matthias Kaehlcke <matthias@kaehlcke.net> * * Copyright (C) 2004, 2005 * Cory T. Tusar, Videon Central, Inc., <ctusar@videon-central.com> * * Based on the original eth.[ch] Cirrus Logic EP93xx Rev D. Ethernet Driver, * which is * * (C) Copyright 2002 2003 * Adam Bezanson, Network Audio Technologies, Inc. * <bezanson@netaudiotech.com> * * See file CREDITS for list of people who contributed to this project. * * 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., * 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <common.h> #include <command.h> #include <init.h> #include <malloc.h> #include <io.h> #include <linux/types.h> #include <mach/ep93xx-regs.h> #include <linux/phy.h> #include "ep93xx.h" #define EP93XX_MAX_PKT_SIZE 1536 static int ep93xx_phy_read(struct mii_bus *bus, int phy_addr, int phy_reg); static int ep93xx_phy_write(struct mii_bus *bus, int phy_addr, int phy_reg, u16 value); static inline struct ep93xx_eth_priv *ep93xx_get_priv(struct eth_device *edev) { return (struct ep93xx_eth_priv *)edev->priv; } static inline struct mac_regs *ep93xx_get_regs(struct eth_device *edev) { struct ep93xx_eth_priv *priv = ep93xx_get_priv(edev); return priv->regs; } #if defined(EP93XX_MAC_DEBUG) /** * Dump ep93xx_mac values to the terminal. */ static void dump_dev(struct eth_device *edev) { struct ep93xx_eth_priv *priv = ep93xx_get_priv(edev); int i; printf("\ndump_dev()\n"); printf(" rx_dq.base %p\n", priv->rx_dq.base); printf(" rx_dq.current %p\n", priv->rx_dq.current); printf(" rx_dq.end %p\n", priv->rx_dq.end); printf(" rx_sq.base %p\n", priv->rx_sq.base); printf(" rx_sq.current %p\n", priv->rx_sq.current); printf(" rx_sq.end %p\n", priv->rx_sq.end); for (i = 0; i < NUMRXDESC; i++) printf(" rx_buffer[%2.d] %p\n", i, NetRxPackets[i]); printf(" tx_dq.base %p\n", priv->tx_dq.base); printf(" tx_dq.current %p\n", priv->tx_dq.current); printf(" tx_dq.end %p\n", priv->tx_dq.end); printf(" tx_sq.base %p\n", priv->tx_sq.base); printf(" tx_sq.current %p\n", priv->tx_sq.current); printf(" tx_sq.end %p\n", priv->tx_sq.end); } /** * Dump all RX descriptor queue entries to the terminal. */ static void dump_rx_descriptor_queue(struct eth_device *edev) { struct ep93xx_eth_priv *priv = ep93xx_get_priv(edev); int i; printf("\ndump_rx_descriptor_queue()\n"); printf(" descriptor address word1 word2\n"); for (i = 0; i < NUMRXDESC; i++) { printf(" [ %p ] %08X %08X\n", priv->rx_dq.base + i, (priv->rx_dq.base + i)->word1, (priv->rx_dq.base + i)->word2); } } /** * Dump all RX status queue entries to the terminal. */ static void dump_rx_status_queue(struct eth_device *edev) { struct ep93xx_eth_priv *priv = ep93xx_get_priv(edev); int i; printf("\ndump_rx_status_queue()\n"); printf(" descriptor address word1 word2\n"); for (i = 0; i < NUMRXDESC; i++) { printf(" [ %p ] %08X %08X\n", priv->rx_sq.base + i, (priv->rx_sq.base + i)->word1, (priv->rx_sq.base + i)->word2); } } /** * Dump all TX descriptor queue entries to the terminal. */ static void dump_tx_descriptor_queue(struct eth_device *edev) { struct ep93xx_eth_priv *priv = ep93xx_get_priv(edev); int i; printf("\ndump_tx_descriptor_queue()\n"); printf(" descriptor address word1 word2\n"); for (i = 0; i < NUMTXDESC; i++) { printf(" [ %p ] %08X %08X\n", priv->tx_dq.base + i, (priv->tx_dq.base + i)->word1, (priv->tx_dq.base + i)->word2); } } /** * Dump all TX status queue entries to the terminal. */ static void dump_tx_status_queue(struct eth_device *edev) { struct ep93xx_eth_priv *priv = ep93xx_get_priv(edev); int i; printf("\ndump_tx_status_queue()\n"); printf(" descriptor address word1\n"); for (i = 0; i < NUMTXDESC; i++) { printf(" [ %p ] %08X\n", priv->rx_sq.base + i, (priv->rx_sq.base + i)->word1); } } #else #define dump_dev(x) #define dump_rx_descriptor_queue(x) #define dump_rx_status_queue(x) #define dump_tx_descriptor_queue(x) #define dump_tx_status_queue(x) #endif /* defined(EP93XX_MAC_DEBUG) */ /** * Reset the EP93xx MAC by twiddling the soft reset bit and spinning until * it's cleared. */ static void ep93xx_eth_reset(struct eth_device *edev) { struct mac_regs *regs = ep93xx_get_regs(edev); uint32_t value; pr_debug("+ep93xx_eth_reset\n"); value = readl(&regs->selfctl); value |= SELFCTL_RESET; writel(value, &regs->selfctl); while (readl(&regs->selfctl) & SELFCTL_RESET) ; /* noop */ pr_debug("-ep93xx_eth_reset\n"); } static int ep93xx_eth_init_dev(struct eth_device *edev) { pr_debug("+ep93xx_eth_init_dev\n"); pr_debug("-ep93xx_eth_init_dev\n"); return 0; } static int ep93xx_eth_open(struct eth_device *edev) { struct ep93xx_eth_priv *priv = ep93xx_get_priv(edev); struct mac_regs *regs = ep93xx_get_regs(edev); int i; int ret; pr_debug("+ep93xx_eth_open\n"); ret = phy_device_connect(edev, &priv->miibus, 0, NULL, 0, PHY_INTERFACE_MODE_NA); if (ret) return ret; ep93xx_eth_reset(edev); /* Reset the descriptor queues' current and end address values */ priv->tx_dq.current = priv->tx_dq.base; priv->tx_dq.end = (priv->tx_dq.base + NUMTXDESC); priv->tx_sq.current = priv->tx_sq.base; priv->tx_sq.end = (priv->tx_sq.base + NUMTXDESC); priv->rx_dq.current = priv->rx_dq.base; priv->rx_dq.end = (priv->rx_dq.base + NUMRXDESC); priv->rx_sq.current = priv->rx_sq.base; priv->rx_sq.end = (priv->rx_sq.base + NUMRXDESC); /* * Set the transmit descriptor and status queues' base address, * current address, and length registers. Set the maximum frame * length and threshold. Enable the transmit descriptor processor. */ writel((uint32_t)priv->tx_dq.base, &regs->txdq.badd); writel((uint32_t)priv->tx_dq.base, &regs->txdq.curadd); writel(sizeof(struct tx_descriptor) * NUMTXDESC, &regs->txdq.blen); writel((uint32_t)priv->tx_sq.base, &regs->txstsq.badd); writel((uint32_t)priv->tx_sq.base, &regs->txstsq.curadd); writel(sizeof(struct tx_status) * NUMTXDESC, &regs->txstsq.blen); writel(0x00040000, &regs->txdthrshld); writel(0x00040000, &regs->txststhrshld); writel((TXSTARTMAX << 0) | (EP93XX_MAX_PKT_SIZE << 16), &regs->maxfrmlen); writel(BMCTL_TXEN, &regs->bmctl); /* * Set the receive descriptor and status queues' base address, * current address, and length registers. Enable the receive * descriptor processor. */ writel((uint32_t)priv->rx_dq.base, &regs->rxdq.badd); writel((uint32_t)priv->rx_dq.base, &regs->rxdq.curadd); writel(sizeof(struct rx_descriptor) * NUMRXDESC, &regs->rxdq.blen); writel((uint32_t)priv->rx_sq.base, &regs->rxstsq.badd); writel((uint32_t)priv->rx_sq.base, &regs->rxstsq.curadd); writel(sizeof(struct rx_status) * NUMRXDESC, &regs->rxstsq.blen); writel(0x00040000, &regs->rxdthrshld); writel(BMCTL_RXEN, &regs->bmctl); writel(0x00040000, &regs->rxststhrshld); /* Wait until the receive descriptor processor is active */ while (!(readl(&regs->bmsts) & BMSTS_RXACT)) ; /* noop */ /* * Initialize the RX descriptor queue. Clear the TX descriptor queue. * Clear the RX and TX status queues. Enqueue the RX descriptor and * status entries to the MAC. */ for (i = 0; i < NUMRXDESC; i++) { /* set buffer address */ (priv->rx_dq.base + i)->word1 = (uint32_t)NetRxPackets[i]; /* set buffer length, clear buffer index and NSOF */ (priv->rx_dq.base + i)->word2 = EP93XX_MAX_PKT_SIZE; } memset(priv->tx_dq.base, 0, (sizeof(struct tx_descriptor) * NUMTXDESC)); memset(priv->rx_sq.base, 0, (sizeof(struct rx_status) * NUMRXDESC)); memset(priv->tx_sq.base, 0, (sizeof(struct tx_status) * NUMTXDESC)); writel(NUMRXDESC, &regs->rxdqenq); writel(NUMRXDESC, &regs->rxstsqenq); /* Turn on RX and TX */ writel(RXCTL_IA0 | RXCTL_BA | RXCTL_SRXON | RXCTL_RCRCA | RXCTL_MA, &regs->rxctl); writel(TXCTL_STXON, &regs->txctl); /* Dump data structures if we're debugging */ dump_dev(edev); dump_rx_descriptor_queue(edev); dump_rx_status_queue(edev); dump_tx_descriptor_queue(edev); dump_tx_status_queue(edev); pr_debug("-ep93xx_eth_open\n"); return 0; } /** * Halt EP93xx MAC transmit and receive by clearing the TxCTL and RxCTL * registers. */ static void ep93xx_eth_halt(struct eth_device *edev) { struct mac_regs *regs = ep93xx_get_regs(edev); pr_debug("+ep93xx_eth_halt\n"); writel(0x00000000, &regs->rxctl); writel(0x00000000, &regs->txctl); pr_debug("-ep93xx_eth_halt\n"); } /** * Copy a frame of data from the MAC into the protocol layer for further * processing. */ static int ep93xx_eth_rcv_packet(struct eth_device *edev) { struct ep93xx_eth_priv *priv = ep93xx_get_priv(edev); struct mac_regs *regs = ep93xx_get_regs(edev); int ret = -1; pr_debug("+ep93xx_eth_rcv_packet\n"); if (RX_STATUS_RFP(priv->rx_sq.current)) { if (RX_STATUS_RWE(priv->rx_sq.current)) { /* * We have a good frame. Extract the frame's length * from the current rx_status_queue entry, and copy * the frame's data into NetRxPackets[] of the * protocol stack. We track the total number of * bytes in the frame (nbytes_frame) which will be * used when we pass the data off to the protocol * layer via net_receive(). */ net_receive((uchar *)priv->rx_dq.current->word1, RX_STATUS_FRAME_LEN(priv->rx_sq.current)); pr_debug("reporting %d bytes...\n", RX_STATUS_FRAME_LEN(priv->rx_sq.current)); ret = 0; } else { /* Do we have an erroneous packet? */ pr_err("packet rx error, status %08X %08X\n", priv->rx_sq.current->word1, priv->rx_sq.current->word2); dump_rx_descriptor_queue(edev); dump_rx_status_queue(edev); } /* * Clear the associated status queue entry, and * increment our current pointers to the next RX * descriptor and status queue entries (making sure * we wrap properly). */ memset((void *)priv->rx_sq.current, 0, sizeof(struct rx_status)); priv->rx_sq.current++; if (priv->rx_sq.current >= priv->rx_sq.end) priv->rx_sq.current = priv->rx_sq.base; priv->rx_dq.current++; if (priv->rx_dq.current >= priv->rx_dq.end) priv->rx_dq.current = priv->rx_dq.base; /* * Finally, return the RX descriptor and status entries * back to the MAC engine, and loop again, checking for * more descriptors to process. */ writel(1, &regs->rxdqenq); writel(1, &regs->rxstsqenq); } else { ret = 0; } pr_debug("-ep93xx_eth_rcv_packet %d\n", ret); return ret; } /** * Send a block of data via ethernet. */ static int ep93xx_eth_send_packet(struct eth_device *edev, void *packet, int length) { struct ep93xx_eth_priv *priv = ep93xx_get_priv(edev); struct mac_regs *regs = ep93xx_get_regs(edev); int ret = -1; pr_debug("+ep93xx_eth_send_packet\n"); /* * Initialize the TX descriptor queue with the new packet's info. * Clear the associated status queue entry. Enqueue the packet * to the MAC for transmission. */ /* set buffer address */ priv->tx_dq.current->word1 = (uint32_t)packet; /* set buffer length and EOF bit */ priv->tx_dq.current->word2 = length | TX_DESC_EOF; /* clear tx status */ priv->tx_sq.current->word1 = 0; /* enqueue the TX descriptor */ writel(1, &regs->txdqenq); /* wait for the frame to become processed */ while (!TX_STATUS_TXFP(priv->tx_sq.current)) ; /* noop */ if (!TX_STATUS_TXWE(priv->tx_sq.current)) { pr_err("packet tx error, status %08X\n", priv->tx_sq.current->word1); dump_tx_descriptor_queue(edev); dump_tx_status_queue(edev); /* TODO: Add better error handling? */ goto eth_send_failed_0; } ret = 0; /* Fall through */ eth_send_failed_0: pr_debug("-ep93xx_eth_send_packet %d\n", ret); return ret; } static int ep93xx_eth_get_ethaddr(struct eth_device *edev, unsigned char *mac_addr) { struct mac_regs *regs = ep93xx_get_regs(edev); uint32_t value; value = readl(&regs->indad); mac_addr[0] = value & 0xFF; mac_addr[1] = (value >> 8) & 0xFF; mac_addr[2] = (value >> 16) & 0xFF; mac_addr[3] = (value >> 24) & 0xFF; value = readl(&regs->indad_upper); mac_addr[4] = value & 0xFF; mac_addr[5] = (value >> 8) & 0xFF; return 0; } static int ep93xx_eth_set_ethaddr(struct eth_device *edev, unsigned char *mac_addr) { struct mac_regs *regs = ep93xx_get_regs(edev); writel(AFP_IAPRIMARY, &regs->afp); writel(mac_addr[0] | (mac_addr[1] << 8) | (mac_addr[2] << 16) | (mac_addr[3] << 24), &regs->indad); writel(mac_addr[4] | (mac_addr[5] << 8), &regs->indad_upper); return 0; } static int ep93xx_eth_probe(struct device_d *dev) { struct eth_device *edev; struct ep93xx_eth_priv *priv; int ret = -1; pr_debug("ep93xx_eth_probe()\n"); edev = xzalloc(sizeof(struct eth_device) + sizeof(struct ep93xx_eth_priv)); edev->priv = (struct ep93xx_eth_priv *)(edev + 1); priv = edev->priv; priv->regs = (struct mac_regs *)MAC_BASE; edev->init = ep93xx_eth_init_dev; edev->open = ep93xx_eth_open; edev->send = ep93xx_eth_send_packet; edev->recv = ep93xx_eth_rcv_packet; edev->halt = ep93xx_eth_halt; edev->get_ethaddr = ep93xx_eth_get_ethaddr; edev->set_ethaddr = ep93xx_eth_set_ethaddr; edev->parent = dev; priv->miibus.read = ep93xx_phy_read; priv->miibus.write = ep93xx_phy_write; priv->miibus.parent = dev; priv->miibus.priv = edev; priv->tx_dq.base = calloc(NUMTXDESC, sizeof(struct tx_descriptor)); if (priv->tx_dq.base == NULL) { pr_err("calloc() failed: tx_dq.base"); goto eth_probe_failed_0; } priv->tx_sq.base = calloc(NUMTXDESC, sizeof(struct tx_status)); if (priv->tx_sq.base == NULL) { pr_err("calloc() failed: tx_sq.base"); goto eth_probe_failed_1; } priv->rx_dq.base = calloc(NUMRXDESC, sizeof(struct rx_descriptor)); if (priv->rx_dq.base == NULL) { pr_err("calloc() failed: rx_dq.base"); goto eth_probe_failed_2; } priv->rx_sq.base = calloc(NUMRXDESC, sizeof(struct rx_status)); if (priv->rx_sq.base == NULL) { pr_err("calloc() failed: rx_sq.base"); goto eth_probe_failed_3; } mdiobus_register(&priv->miibus); eth_register(edev); ret = 0; goto eth_probe_done; eth_probe_failed_3: free(priv->rx_dq.base); /* Fall through */ eth_probe_failed_2: free(priv->tx_sq.base); /* Fall through */ eth_probe_failed_1: free(priv->tx_dq.base); /* Fall through */ eth_probe_failed_0: /* Fall through */ eth_probe_done: return ret; } /* ----------------------------------------------------------------------------- * EP93xx ethernet MII functionality. */ /** * Maximum MII address we support */ #define MII_ADDRESS_MAX 31 /** * Maximum MII register address we support */ #define MII_REGISTER_MAX 31 /** * Read a 16-bit value from an MII register. */ static int ep93xx_phy_read(struct mii_bus *bus, int phy_addr, int phy_reg) { struct mac_regs *regs = ep93xx_get_regs(bus->priv); int value = -1; uint32_t self_ctl; pr_debug("+ep93xx_phy_read\n"); /* * Save the current SelfCTL register value. Set MAC to suppress * preamble bits. Wait for any previous MII command to complete * before issuing the new command. */ self_ctl = readl(&regs->selfctl); #if defined(CONFIG_MII_SUPPRESS_PREAMBLE) /* TODO */ writel(self_ctl & ~(1 << 8), &regs->selfctl); #endif /* defined(CONFIG_MII_SUPPRESS_PREAMBLE) */ while (readl(&regs->miists) & MIISTS_BUSY) ; /* noop */ /* * Issue the MII 'read' command. Wait for the command to complete. * Read the MII data value. */ writel(MIICMD_OPCODE_READ | ((uint32_t)phy_addr << 5) | (uint32_t)phy_reg, &regs->miicmd); while (readl(&regs->miists) & MIISTS_BUSY) ; /* noop */ value = (unsigned short)readl(&regs->miidata); /* Restore the saved SelfCTL value and return. */ writel(self_ctl, &regs->selfctl); pr_debug("-ep93xx_phy_read\n"); return value; } /** * Write a 16-bit value to an MII register. */ static int ep93xx_phy_write(struct mii_bus *bus, int phy_addr, int phy_reg, u16 value) { struct mac_regs *regs = ep93xx_get_regs(bus->priv); uint32_t self_ctl; pr_debug("+ep93xx_phy_write\n"); /* * Save the current SelfCTL register value. Set MAC to suppress * preamble bits. Wait for any previous MII command to complete * before issuing the new command. */ self_ctl = readl(&regs->selfctl); #if defined(CONFIG_MII_SUPPRESS_PREAMBLE) /* TODO */ writel(self_ctl & ~(1 << 8), &regs->selfctl); #endif /* defined(CONFIG_MII_SUPPRESS_PREAMBLE) */ while (readl(&regs->miists) & MIISTS_BUSY) ; /* noop */ /* Issue the MII 'write' command. Wait for the command to complete. */ writel((uint32_t)value, &regs->miidata); writel(MIICMD_OPCODE_WRITE | ((uint32_t)phy_addr << 5) | phy_reg, &regs->miicmd); while (readl(&regs->miists) & MIISTS_BUSY) ; /* noop */ /* Restore the saved SelfCTL value and return. */ writel(self_ctl, &regs->selfctl); pr_debug("-ep93xx_phy_write\n"); return 0; } static struct driver_d ep93xx_eth_driver = { .name = "ep93xx_eth", .probe = ep93xx_eth_probe, }; static int ep93xx_eth_init(void) { platform_driver_register(&ep93xx_eth_driver); return 0; } device_initcall(ep93xx_eth_init);
RobertCNelson/barebox-boards
drivers/net/ep93xx.c
C
gpl-2.0
17,776
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_11) on Thu Jul 31 14:36:29 CDT 2014 --> <title>Uses of Class termo.activityModel.WilsonActivityModelTest</title> <meta name="date" content="2014-07-31"> <link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class termo.activityModel.WilsonActivityModelTest"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../termo/activityModel/WilsonActivityModelTest.html" title="class in termo.activityModel">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-files/index-1.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../index.html?termo/activityModel/class-use/WilsonActivityModelTest.html" target="_top">Frames</a></li> <li><a href="WilsonActivityModelTest.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class termo.activityModel.WilsonActivityModelTest" class="title">Uses of Class<br>termo.activityModel.WilsonActivityModelTest</h2> </div> <div class="classUseContainer">No usage of termo.activityModel.WilsonActivityModelTest</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../termo/activityModel/WilsonActivityModelTest.html" title="class in termo.activityModel">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-files/index-1.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../index.html?termo/activityModel/class-use/WilsonActivityModelTest.html" target="_top">Frames</a></li> <li><a href="WilsonActivityModelTest.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
HugoRedon/Materia
doc/termo/activityModel/class-use/WilsonActivityModelTest.html
HTML
gpl-2.0
4,357
<?php /** * @file * Contains Drupal\system\Tests\Theme\EntityFilteringThemeTest. */ namespace Drupal\system\Tests\Theme; use Drupal\Core\Extension\ExtensionDiscovery; use Drupal\comment\CommentInterface; use Drupal\comment\Plugin\Field\FieldType\CommentItemInterface; use Drupal\simpletest\WebTestBase; /** * Tests themed output for each entity type in all available themes to ensure * entity labels are filtered for XSS. * * @group Theme */ class EntityFilteringThemeTest extends WebTestBase { /** * Use the standard profile. * * We test entity theming with the default node, user, comment, and taxonomy * configurations at several paths in the standard profile. * * @var string */ protected $profile = 'standard'; /** * A list of all available themes. * * @var \Drupal\Core\Extension\Extension[] */ protected $themes; /** * A test user. * * @var \Drupal\user\User */ protected $user; /** * A test node. * * @var \Drupal\node\Node */ protected $node; /** * A test taxonomy term. * * @var \Drupal\taxonomy\Term */ protected $term; /** * A test comment. * * @var \Drupal\comment\Comment */ protected $comment; /** * A string containing markup and JS. * * @string */ protected $xss_label = "string with <em>HTML</em> and <script>alert('JS');</script>"; function setUp() { parent::setUp(); // Enable all available non-testing themes. $listing = new ExtensionDiscovery(); $this->themes = $listing->scan('theme', FALSE); theme_enable(array_keys($this->themes)); // Create a test user. $this->user = $this->drupalCreateUser(array('access content', 'access user profiles')); $this->user->name = $this->xss_label; $this->user->save(); $this->drupalLogin($this->user); // Create a test term. $this->term = entity_create('taxonomy_term', array( 'name' => $this->xss_label, 'vid' => 1, )); $this->term->save(); // Add a comment field. $this->container->get('comment.manager')->addDefaultField('node', 'article', 'comment', CommentItemInterface::OPEN); // Create a test node tagged with the test term. $this->node = $this->drupalCreateNode(array( 'title' => $this->xss_label, 'type' => 'article', 'promote' => NODE_PROMOTED, 'field_tags' => array(array('target_id' => $this->term->id())), )); // Create a test comment on the test node. $this->comment = entity_create('comment', array( 'entity_id' => $this->node->id(), 'entity_type' => 'node', 'field_name' => 'comment', 'status' => CommentInterface::PUBLISHED, 'subject' => $this->xss_label, 'comment_body' => array($this->randomName()), )); $this->comment->save(); } /** * Checks each themed entity for XSS filtering in available themes. */ function testThemedEntity() { // Check paths where various view modes of the entities are rendered. $paths = array( 'user', 'node', 'node/' . $this->node->id(), 'taxonomy/term/' . $this->term->id(), ); // Check each path in all available themes. foreach ($this->themes as $name => $theme) { \Drupal::config('system.theme') ->set('default', $name) ->save(); foreach ($paths as $path) { $this->drupalGet($path); $this->assertResponse(200); $this->assertNoRaw($this->xss_label); } } } }
england9911/matteng.land
core/modules/system/src/Tests/Theme/EntityFilteringThemeTest.php
PHP
gpl-2.0
3,503
/* * Copyright (c) 2005, Bull S.A.. All rights reserved. * Created by: Sebastien Decugis * This program is free software; you can redistribute it and/or modify it * under the terms of version 2 of the GNU General Public License as * published by the Free Software Foundation. * * This program is distributed in the hope that it would be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * You should have received a copy of the GNU General Public License along * with this program; if not, write the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * This sample test aims to check the following assertions: * * If SA_NODEFER is not set in sa_flags, the caught signal is added to the * thread's signal mask during the handler execution. * The steps are: * -> register a signal handler for SIGTSTP * -> raise SIGTSTP * -> In handler, check for reentrance then raise SIGTSTP again. * The test fails if signal handler if reentered or signal is not pending when raised again. */ /* We are testing conformance to IEEE Std 1003.1, 2003 Edition */ #define _POSIX_C_SOURCE 200112L /******************************************************************************/ /*************************** standard includes ********************************/ /******************************************************************************/ #include <pthread.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <signal.h> #include <errno.h> /******************************************************************************/ /*************************** Test framework *******************************/ /******************************************************************************/ #include "../testfrmw/testfrmw.h" #include "../testfrmw/testfrmw.c" /* This header is responsible for defining the following macros: * UNRESOLVED(ret, descr); * where descr is a description of the error and ret is an int * (error code for example) * FAILED(descr); * where descr is a short text saying why the test has failed. * PASSED(); * No parameter. * * Both three macros shall terminate the calling process. * The testcase shall not terminate in any other maneer. * * The other file defines the functions * void output_init() * void output(char * string, ...) * * Those may be used to output information. */ /******************************************************************************/ /**************************** Configuration ***********************************/ /******************************************************************************/ #ifndef VERBOSE #define VERBOSE 1 #endif #define SIGNAL SIGTSTP /******************************************************************************/ /*************************** Test case ***********************************/ /******************************************************************************/ int called = 0; void handler(int sig) { int ret; sigset_t pending; called++; if (called == 2) { FAILED("Signal was not masked in signal handler"); } if (called == 1) { /* Raise the signal again. It should be masked */ ret = raise(SIGNAL); if (ret != 0) { UNRESOLVED(ret, "Failed to raise SIGTSTP again"); } /* check the signal is pending */ ret = sigpending(&pending); if (ret != 0) { UNRESOLVED(ret, "Failed to get pending signal set"); } ret = sigismember(&pending, SIGNAL); if (ret != 1) { FAILED("signal is not pending"); } } called++; } /* main function */ int main() { int ret; struct sigaction sa; /* Initialize output */ output_init(); /* Set the signal handler */ sa.sa_flags = 0; sa.sa_handler = handler; ret = sigemptyset(&sa.sa_mask); if (ret != 0) { UNRESOLVED(ret, "Failed to empty signal set"); } /* Install the signal handler for SIGTSTP */ ret = sigaction(SIGNAL, &sa, 0); if (ret != 0) { UNRESOLVED(ret, "Failed to set signal handler"); } ret = raise(SIGNAL); if (ret != 0) { UNRESOLVED(ret, "Failed to raise SIGTSTP"); } while (called != 4) sched_yield(); /* Test passed */ #if VERBOSE > 0 output("Test passed\n"); #endif PASSED; }
shubmit/shub-ltp
testcases/open_posix_testsuite/conformance/interfaces/sigaction/23-14.c
C
gpl-2.0
4,306
<?xml version="1.0" encoding="iso-8859-1"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <!-- /home/test1/tmp/qtopia/qtopia-opensource-4.3.4/src/qtopiadesktop/doc/src/qdsyncprotocol.qdocpp --> <head> <title>331</title> <link href="classic.css" rel="stylesheet" type="text/css" /> </head> <body> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr> <td align="left" valign="top" width="32"><img src="images/qpelogo.png" align="left" width="32" height="32" border="0" /></td> <td width="1">&nbsp;&nbsp;</td><td class="postheader" valign="center"><a href="../index.html"><font color="#004faf">Qtopia Home</font></a>&nbsp;&middot; <a href="index.html"><font color="#004faf">Index</font></a>&nbsp;&middot; <a href="classes.html"><font color="#004faf">Classes</font></a>&nbsp;&middot; <a href="headers.html"><font color="#004faf">Headers</font></a>&nbsp;&middot; <a href="overviews.html"><font color="#004faf">Overviews</font></a> </td> <td align="right" valign="top"><img src="images/codeless.png" align="right" border="0" /></td></tr></table><h1 class="title">331<br /><span class="subtitle"></span> </h1> <a name="usage"></a> <h3>Usage</h3> <p>This command includes an untranslated status message that can be ignored.</p> <pre> 331 User name ok, need password</pre> <a name="description"></a> <h3>Description</h3> <p>Sent from the device to the desktop in response to a <a href="qdsync-user-1.html">USER</a> command.</p> <p>After this command is sent the device will expect to receive a <a href="qdsync-pass-1.html">PASS</a> command.</p> <p>See also <a href="qdsync-commands.html">qdsync Protocol</a>.</p> <p /><address><hr /><div align="center"> <table width="100%" cellspacing="0" border="0"><tr class="address"> <td align="left">Copyright &copy; 2008 Trolltech</td> <td align="right">Qtopia Sync Agent Documentation</td> </tr></table></div></address></body> </html>
muromec/qtopia-ezx
src/qtopiadesktop/doc/html/qdsync-331-1.html
HTML
gpl-2.0
1,998
-- Pelit joita on lainattu vähintään viisi kertaa -- Kaikki pelit, joita on lainattu vähintään viisi kertaa. select * from pelitTop where lkm>=5 order by lkm desc;
daFool/slskirjasto
web/vendor/php-reports/public_reports/pgsql/pelit.sql
SQL
gpl-2.0
171
/* * SocialLedge.com - Copyright (C) 2013 * * This file is part of free software framework for embedded processors. * You can use it and/or distribute it as long as this copyright header * remains unmodified. The code is free for personal use and requires * permission to use in a commercial product. * * THIS SOFTWARE IS PROVIDED "AS IS". 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. * I SHALL NOT, IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR * CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER. * * You can reach the author of this software at : * p r e e t . w i k i @ g m a i l . c o m */ #include <stdio.h> #include "lpc_sys.h" #include "wireless.h" #include "lpc_timers.h" #include "io.hpp" #include "FreeRTOS.h" #include "task.h" /// These bitmasks should match up with the timer MCR register to trigger interrupt upon match enum { mr0_mcr_for_overflow = (UINT32_C(1) << 0), mr1_mcr_for_mesh_bckgnd_task = (UINT32_C(1) << 3), mr2_mcr_for_ir_sensor_timeout = (UINT32_C(1) << 6), mr3_mcr_for_watchdog_reset = (UINT32_C(1) << 9), }; /// Periodic interrupt for mesh networking. This timer match interrupt is disabled if FreeRTOS starts to run. #define LPC_SYS_TIME_FOR_BCKGND_TASK_US (1 * 1000) /// Time in microseconds that will feed the watchdog, which should be roughly half of the actual watchdog reset #define LPC_SYS_WATCHDOG_RESET_TIME_US ((SYS_CFG_WATCHDOG_TIMEOUT_MS / 2) * 1000) /// Timer overflow interrupt will increment this upon the last UINT32 value, 16-bit is enough for many years! static volatile uint16_t g_timer_rollover_count = 0; /// Pointer to the timer struct based on SYS_CFG_SYS_TIMER LPC_TIM_TypeDef *gp_timer_ptr = NULL; extern "C" void lpc_sys_setup_system_timer(void) { // Note: Timer1 is required for IR sensor's decoding logic since its pin is tied to Timer1 Capture Pin const lpc_timer_t sys_timer_source = (lpc_timer_t) SYS_CFG_SYS_TIMER; // Get the IRQ number of the timer to enable the interrupt const IRQn_Type timer_irq = lpc_timer_get_irq_num(sys_timer_source); // Initialize the timer structure pointer gp_timer_ptr = lpc_timer_get_struct(sys_timer_source); // Setup the timer to tick with a fine-grain resolution const uint32_t one_micro_second = 1; lpc_timer_enable(sys_timer_source, one_micro_second); /** * MR0: Setup the match register to take care of the overflow. * Upon the roll-over, we increment the roll-over count and the timer restarts from zero. */ gp_timer_ptr->MR0 = UINT32_MAX; // MR1: Setup the periodic interrupt to do background processing gp_timer_ptr->MR1 = LPC_SYS_TIME_FOR_BCKGND_TASK_US; #if (1 == SYS_CFG_SYS_TIMER) // MR2: IR code timeout when timer1 is used since IR receiver is tied to timer1 capture pin gp_timer_ptr->MR2 = 0; #else #warning "IR receiver will not work unless SYS_CFG_SYS_TIMER uses TIMER1, so set it to 1 if possible" #endif /* Setup the first match interrupt to reset the watchdog */ gp_timer_ptr->MR3 = LPC_SYS_WATCHDOG_RESET_TIME_US; // Enable the timer match interrupts gp_timer_ptr->MCR = (mr0_mcr_for_overflow | mr1_mcr_for_mesh_bckgnd_task | mr3_mcr_for_watchdog_reset); // Only if we have got TIMER1, we can use IR sensor timeout match interrupt #if (1 == SYS_CFG_SYS_TIMER) gp_timer_ptr->MCR |= (mr2_mcr_for_ir_sensor_timeout); #endif /* Enable the interrupt and use higher priority than other peripherals because we want * to drive the periodic ISR above other interrupts since we reset the watchdog timer. */ NVIC_SetPriority(timer_irq, IP_high); vTraceSetISRProperties(timer_irq, "AUX Timer", IP_high); NVIC_EnableIRQ(timer_irq); } extern "C" uint64_t sys_get_uptime_us(void) { uint32_t before = 0; uint32_t after = 0; uint32_t rollovers = 0; /** * Loop until we can safely read both the rollover value and the timer value. * When the timer rolls over, the TC value will start from zero, and the "after" * value will be less than the before value in which case, we will loop again * and pick up the new rollover count. This avoid critical section and simplifies * the logic of reading higher 16-bit (roll-over) and lower 32-bit (timer value). */ do { before = gp_timer_ptr->TC; rollovers = g_timer_rollover_count; after = gp_timer_ptr->TC; } while (after < before); // each rollover is 2^32 or UINT32_MAX return (((uint64_t)rollovers << 32) | after); } /** * Actual ISR function (@see startup.cpp) */ #if (0 == SYS_CFG_SYS_TIMER) extern "C" void TIMER0_IRQHandler() #elif (1 == SYS_CFG_SYS_TIMER) extern "C" void TIMER1_IRQHandler() #elif (2 == SYS_CFG_SYS_TIMER) extern "C" void TIMER2_IRQHandler() #elif (3 == SYS_CFG_SYS_TIMER) extern "C" void TIMER3_IRQHandler() #else #error "SYS_CFG_SYS_TIMER must be between 0-3 inclusively" void TIMERX_BAD_IRQHandler() #endif { enum { timer_mr0_intr_timer_rollover = (1 << 0), timer_mr1_intr_mesh_servicing = (1 << 1), timer_mr2_intr_ir_sensor_timeout = (1 << 2), timer_mr3_intr_for_watchdog_rst = (1 << 3), timer_capt0_intr_ir_sensor_edge_time_captured = (1 << 4), timer_capt1_intr = (1 << 5), }; const uint32_t intr_reason = gp_timer_ptr->IR; #if (1 == SYS_CFG_SYS_TIMER) /* ISR for captured time of the capture input pin */ if (intr_reason & timer_capt0_intr_ir_sensor_edge_time_captured) { gp_timer_ptr->IR = timer_capt0_intr_ir_sensor_edge_time_captured; // Store the IR capture time and setup timeout of the IR signal (unless we reset it again) IS.storeIrCode(gp_timer_ptr->CR0); gp_timer_ptr->MR2 = 10000 + gp_timer_ptr->TC; } /* MR2: End of IR capture (no IR capture after initial IR signal) */ else if (intr_reason & timer_mr2_intr_ir_sensor_timeout) { gp_timer_ptr->IR = timer_mr2_intr_ir_sensor_timeout; IS.decodeIrCode(); } /* MR0 is used for the timer rollover count */ else #endif if(intr_reason & timer_mr0_intr_timer_rollover) { gp_timer_ptr->IR = timer_mr0_intr_timer_rollover; ++g_timer_rollover_count; } else if(intr_reason & timer_mr1_intr_mesh_servicing) { gp_timer_ptr->IR = timer_mr1_intr_mesh_servicing; /* FreeRTOS task is used to service the wireless_service() function, otherwise if FreeRTOS * is not running, timer ISR will call this function to carry out mesh networking logic. */ if (taskSCHEDULER_RUNNING != xTaskGetSchedulerState()) { wireless_service(); } else { /* Disable this timer interrupt if FreeRTOS starts to run */ gp_timer_ptr->MCR &= ~(mr1_mcr_for_mesh_bckgnd_task); } /* Setup the next periodic interrupt */ gp_timer_ptr->MR1 += gp_timer_ptr->TC + LPC_SYS_TIME_FOR_BCKGND_TASK_US; } else if (intr_reason & timer_mr3_intr_for_watchdog_rst) { gp_timer_ptr->IR = timer_mr3_intr_for_watchdog_rst; /* If no one feeds the watchdog, we will watchdog reset. We are using a periodic ISR * to feed watchdog because if a critical exception hits, it will enter while(1) loop inside * the interrupt, and since watchdog won't reset, it will trigger system reset. */ sys_watchdog_feed(); /* Setup the next watchdog reset timer */ gp_timer_ptr->MR3 = gp_timer_ptr->TC + LPC_SYS_WATCHDOG_RESET_TIME_US; } else { // Unexpected interrupt, so stay here to trigger watchdog interrupt puts("Unexpected ISR call at lpc_sys.c"); while (1) { ; } } } extern "C" void sys_get_mem_info_str(char buffer[280]) { sys_mem_t info = sys_get_mem_info(); sprintf(buffer, "Memory Information:\n" "Global Used : %5d\n" "malloc Used : %5d\n" "malloc Avail. : %5d\n" "System Avail. : %5d\n" "Next Heap ptr : 0x%08X\n" "Last sbrk() ptr : 0x%08X\n" "Last sbrk() size : %u\n" "Num sbrk() calls: %u\n", (int)info.used_global, (int)info.used_heap, (int)info.avail_heap, (int)info.avail_sys, (unsigned int)info.next_malloc_ptr, (unsigned int)info.last_sbrk_ptr, (unsigned int)info.last_sbrk_size, (unsigned int)info.num_sbrk_calls); }
kammce/SJSU-DEV-Linux
firmware/default/lib/L0_LowLevel/source/lpc_sys.cpp
C++
gpl-2.0
8,998
/* * Copyright (C) Dag Henning Liodden Sørbø <daghenning@lioddensorbo.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, see <http://www.gnu.org/licenses/>. */ #ifndef GUIUTILS_H #define GUIUTILS_H #include <QFont> #include <QLayout> #define MAX_FONT_SIZE 1000 class GuiUtils { public: static QColor backgroundColor() {return QColor(Qt::white);} static QColor foregroundColor() {return QColor(Qt::black);} static int calcMaxFontSize(const QFont& originalFont, const QString& text, const QRect& boundingBox) { QFontMetrics originalMetrics(originalFont); bool fontTooLarge = originalMetrics.width(text) >= boundingBox.width() || originalMetrics.height() >= boundingBox.height(); int inc = 2; int size = originalFont.pointSize(); QFont f = originalFont; if (!fontTooLarge) { // try to increase font size for (int i = 1; i <= MAX_FONT_SIZE; i += inc) { f.setPointSize(size + i); QFontMetrics fm(f); if (fm.width(text) >= boundingBox.width() || fm.height() >= boundingBox.height()) { return size + i - inc; } } } if (fontTooLarge) { for (int i = 1; i <= MAX_FONT_SIZE && size - i > 1; i += inc) { // try to decrease font size f.setPointSize(size - i); QFontMetrics fm(f); if (fm.width(text) < boundingBox.width() && fm.height() < boundingBox.height()) { return size - i; } } } return size; // should never get this far } static void clearLayout(QLayout* layout) { QLayoutItem* item; while ((item = layout->takeAt(0)) != 0) { if (item->layout()) { clearLayout(item->layout()); } else if (item->widget()) { delete item->widget(); } else if (item->spacerItem()) { delete item->spacerItem(); } delete item; } } }; #endif // GUIUTILS_H
Soerboe/Urim
gui/guiutils.h
C
gpl-2.0
2,628
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2007, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * 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. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------------------ * KeypointPNGEncoderAdapter.java * ------------------------------ * (C) Copyright 2004, 2007, by Richard Atkinson and Contributors. * * Original Author: Richard Atkinson; * Contributor(s): -; * * $Id: KeypointPNGEncoderAdapter.java,v 1.4.2.3 2007/02/02 14:51:22 mungady Exp $ * * Changes * ------- * 01-Aug-2004 : Initial version (RA); * 02-Feb-2007 : Removed author tags all over JFreeChart sources (DG); * */ package org.jfree.chart.encoders; import com.keypoint.PngEncoder; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.OutputStream; /** * Adapter class for the Keypoint PNG Encoder. The ImageEncoderFactory will * only return a reference to this class by default if the library has been * compiled under a JDK < 1.4 or is being run using a JDK < 1.4. */ public class KeypointPNGEncoderAdapter implements ImageEncoder { private int quality = 9; private boolean encodingAlpha = false; /** * Get the quality of the image encoding. The underlying encoder uses int * values: 0 for no compression, and values 1 through 9 for various levels * of compression (1 is best speed, 9 is best compression). * * @return A float representing the quality. */ public float getQuality() { return this.quality; } /** * Set the quality of the image encoding (supported). The underlying * encoder uses int values: 0 for no compression, and values 1 through 9 * for various levels of compression (1 is best speed, 9 is best * compression). * * @param quality A float representing the quality. */ public void setQuality(float quality) { this.quality = (int) quality; } /** * Get whether the encoder should encode alpha transparency. * * @return Whether the encoder is encoding alpha transparency. */ public boolean isEncodingAlpha() { return this.encodingAlpha; } /** * Set whether the encoder should encode alpha transparency (supported). * * @param encodingAlpha Whether the encoder should encode alpha * transparency. */ public void setEncodingAlpha(boolean encodingAlpha) { this.encodingAlpha = encodingAlpha; } /** * Encodes an image in PNG format. * * @param bufferedImage The image to be encoded. * @return The byte[] that is the encoded image. * @throws IOException */ public byte[] encode(BufferedImage bufferedImage) throws IOException { if (bufferedImage == null) { throw new IllegalArgumentException("Null 'image' argument."); } PngEncoder encoder = new PngEncoder(bufferedImage, this.encodingAlpha, 0, this.quality); return encoder.pngEncode(); } /** * Encodes an image in PNG format and writes it to an * <code>OutputStream</code>. * * @param bufferedImage The image to be encoded. * @param outputStream The OutputStream to write the encoded image to. * @throws IOException */ public void encode(BufferedImage bufferedImage, OutputStream outputStream) throws IOException { if (bufferedImage == null) { throw new IllegalArgumentException("Null 'image' argument."); } if (outputStream == null) { throw new IllegalArgumentException("Null 'outputStream' argument."); } PngEncoder encoder = new PngEncoder(bufferedImage, this.encodingAlpha, 0, this.quality); outputStream.write(encoder.pngEncode()); } }
nologic/nabs
client/trunk/shared/libraries/jfreechart-1.0.5/source/org/jfree/chart/encoders/KeypointPNGEncoderAdapter.java
Java
gpl-2.0
5,031
<!doctype html> <html lang=en > <head> <meta charset=utf-8 > <title>FGx FlightPath to 2D Map Texture R1</title> <meta name=viewport content='width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no,minimal-ui' > <meta name=description content=' Top folder file wrangler: display default file or if location.hash then open, read and apply Markdown to HTML conversion ' > <meta name=keywords content='AJAX,JavaScript,GitHub,FOSS,STEM' > <meta name=date content='2016-04-17' > </head> <body> <script src=http://cdnjs.cloudflare.com/ajax/libs/showdown/1.3.0/showdown.min.js ></script> <script> // original: https://github.com/jaanga/jaanga.github.io/tree/master/cookbook-html/templates/index-markdown-reader defaultFile = './flightpath-to-2d-map-texture-r1.html'; init(); function init() { if ( location.hash ) { var css, fileName, contents, converter; fileName = location.hash.slice( 1 ); document.title = fileName.split( '/' ).pop() + ' ~ ' + document.title; css = document.head.appendChild( document.createElement( 'style' ) ); css.innerHTML = 'body { font: 12pt monospace; left: 0; margin: 0 auto; max-width: 800px; right: 0; }' + 'button, input[type=button] { background-color: #eee; border: 2px #eee solid; color: #888; }' + 'h1 a, h2 a { text-decoration: none; }' + 'a { color: mediumblue; }' + ''; contents = document.body.appendChild( document.createElement( 'div' ) ); contents.id = 'contents'; converter = new showdown.Converter( { strikethrough: true, literalMidWordUnderscores: true, simplifiedAutoLink: true, tables: true }); xhr = new XMLHttpRequest(); xhr.open( 'get', fileName, true ); xhr.onload = function() { contents.innerHTML = converter.makeHtml( xhr.responseText ); }; xhr.send( null ); } else { window.location.href = defaultFile + location.hash; } } </script> </body> </html>
fgx/fgx.github.io
sandbox/flightpath-to-2d-map-texture/index.html
HTML
gpl-2.0
1,917
<?php /** * @package Joomla.API * @subpackage com_redirect * * @copyright Copyright (C) 2005 - 2020 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ namespace Joomla\Component\Redirect\Api\Controller; \defined('_JEXEC') or die; use Joomla\CMS\MVC\Controller\ApiController; /** * The redirect controller * * @since 4.0.0 */ class RedirectController extends ApiController { /** * The content type of the item. * * @var string * @since 4.0.0 */ protected $contentType = 'links'; /** * The default view for the display method. * * @var string * @since 3.0 */ protected $default_view = 'redirect'; }
twister65/joomla-cms
api/components/com_redirect/src/Controller/RedirectController.php
PHP
gpl-2.0
729
/* * drivers/i2c/busses/i2c-tegra.c * * Copyright (C) 2010 Google, Inc. * Author: Colin Cross <ccross@android.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/kernel.h> #include <linux/init.h> #include <linux/platform_device.h> #include <linux/clk.h> #include <linux/err.h> #include <linux/i2c.h> #include <linux/io.h> #include <linux/interrupt.h> #include <linux/delay.h> #include <linux/slab.h> #include <linux/i2c-tegra.h> #include <linux/of_i2c.h> #include <linux/module.h> #include <asm/unaligned.h> #include <mach/clk.h> #define TEGRA_I2C_TIMEOUT (msecs_to_jiffies(1000)) #define BYTES_PER_FIFO_WORD 4 #define I2C_CNFG 0x000 #define I2C_CNFG_DEBOUNCE_CNT_SHIFT 12 #define I2C_CNFG_PACKET_MODE_EN (1<<10) #define I2C_CNFG_NEW_MASTER_FSM (1<<11) #define I2C_STATUS 0x01C #define I2C_SL_CNFG 0x020 #define I2C_SL_CNFG_NACK (1<<1) #define I2C_SL_CNFG_NEWSL (1<<2) #define I2C_SL_ADDR1 0x02c #define I2C_SL_ADDR2 0x030 #define I2C_TX_FIFO 0x050 #define I2C_RX_FIFO 0x054 #define I2C_PACKET_TRANSFER_STATUS 0x058 #define I2C_FIFO_CONTROL 0x05c #define I2C_FIFO_CONTROL_TX_FLUSH (1<<1) #define I2C_FIFO_CONTROL_RX_FLUSH (1<<0) #define I2C_FIFO_CONTROL_TX_TRIG_SHIFT 5 #define I2C_FIFO_CONTROL_RX_TRIG_SHIFT 2 #define I2C_FIFO_STATUS 0x060 #define I2C_FIFO_STATUS_TX_MASK 0xF0 #define I2C_FIFO_STATUS_TX_SHIFT 4 #define I2C_FIFO_STATUS_RX_MASK 0x0F #define I2C_FIFO_STATUS_RX_SHIFT 0 #define I2C_INT_MASK 0x064 #define I2C_INT_STATUS 0x068 #define I2C_INT_PACKET_XFER_COMPLETE (1<<7) #define I2C_INT_ALL_PACKETS_XFER_COMPLETE (1<<6) #define I2C_INT_TX_FIFO_OVERFLOW (1<<5) #define I2C_INT_RX_FIFO_UNDERFLOW (1<<4) #define I2C_INT_NO_ACK (1<<3) #define I2C_INT_ARBITRATION_LOST (1<<2) #define I2C_INT_TX_FIFO_DATA_REQ (1<<1) #define I2C_INT_RX_FIFO_DATA_REQ (1<<0) #define I2C_CLK_DIVISOR 0x06c #define DVC_CTRL_REG1 0x000 #define DVC_CTRL_REG1_INTR_EN (1<<10) #define DVC_CTRL_REG2 0x004 #define DVC_CTRL_REG3 0x008 #define DVC_CTRL_REG3_SW_PROG (1<<26) #define DVC_CTRL_REG3_I2C_DONE_INTR_EN (1<<30) #define DVC_STATUS 0x00c #define DVC_STATUS_I2C_DONE_INTR (1<<30) #define I2C_ERR_NONE 0x00 #define I2C_ERR_NO_ACK 0x01 #define I2C_ERR_ARBITRATION_LOST 0x02 #define I2C_ERR_UNKNOWN_INTERRUPT 0x04 #define PACKET_HEADER0_HEADER_SIZE_SHIFT 28 #define PACKET_HEADER0_PACKET_ID_SHIFT 16 #define PACKET_HEADER0_CONT_ID_SHIFT 12 #define PACKET_HEADER0_PROTOCOL_I2C (1<<4) #define I2C_HEADER_HIGHSPEED_MODE (1<<22) #define I2C_HEADER_CONT_ON_NAK (1<<21) #define I2C_HEADER_SEND_START_BYTE (1<<20) #define I2C_HEADER_READ (1<<19) #define I2C_HEADER_10BIT_ADDR (1<<18) #define I2C_HEADER_IE_ENABLE (1<<17) #define I2C_HEADER_REPEAT_START (1<<16) #define I2C_HEADER_MASTER_ADDR_SHIFT 12 #define I2C_HEADER_SLAVE_ADDR_SHIFT 1 /** * struct tegra_i2c_dev - per device i2c context * @dev: device reference for power management * @adapter: core i2c layer adapter information * @clk: clock reference for i2c controller * @i2c_clk: clock reference for i2c bus * @iomem: memory resource for registers * @base: ioremapped registers cookie * @cont_id: i2c controller id, used for for packet header * @irq: irq number of transfer complete interrupt * @is_dvc: identifies the DVC i2c controller, has a different register layout * @msg_complete: transfer completion notifier * @msg_err: error code for completed message * @msg_buf: pointer to current message data * @msg_buf_remaining: size of unsent data in the message buffer * @msg_read: identifies read transfers * @bus_clk_rate: current i2c bus clock rate * @is_suspended: prevents i2c controller accesses after suspend is called */ struct tegra_i2c_dev { struct device *dev; struct i2c_adapter adapter; struct clk *clk; struct clk *i2c_clk; struct resource *iomem; void __iomem *base; int cont_id; int irq; bool irq_disabled; int is_dvc; struct completion msg_complete; int msg_err; u8 *msg_buf; size_t msg_buf_remaining; int msg_read; unsigned long bus_clk_rate; bool is_suspended; }; static void dvc_writel(struct tegra_i2c_dev *i2c_dev, u32 val, unsigned long reg) { writel(val, i2c_dev->base + reg); } static u32 dvc_readl(struct tegra_i2c_dev *i2c_dev, unsigned long reg) { return readl(i2c_dev->base + reg); } /* * i2c_writel and i2c_readl will offset the register if necessary to talk * to the I2C block inside the DVC block */ static unsigned long tegra_i2c_reg_addr(struct tegra_i2c_dev *i2c_dev, unsigned long reg) { if (i2c_dev->is_dvc) reg += (reg >= I2C_TX_FIFO) ? 0x10 : 0x40; return reg; } static void i2c_writel(struct tegra_i2c_dev *i2c_dev, u32 val, unsigned long reg) { writel(val, i2c_dev->base + tegra_i2c_reg_addr(i2c_dev, reg)); } static u32 i2c_readl(struct tegra_i2c_dev *i2c_dev, unsigned long reg) { return readl(i2c_dev->base + tegra_i2c_reg_addr(i2c_dev, reg)); } static void i2c_writesl(struct tegra_i2c_dev *i2c_dev, void *data, unsigned long reg, int len) { writesl(i2c_dev->base + tegra_i2c_reg_addr(i2c_dev, reg), data, len); } static void i2c_readsl(struct tegra_i2c_dev *i2c_dev, void *data, unsigned long reg, int len) { readsl(i2c_dev->base + tegra_i2c_reg_addr(i2c_dev, reg), data, len); } static void tegra_i2c_mask_irq(struct tegra_i2c_dev *i2c_dev, u32 mask) { u32 int_mask = i2c_readl(i2c_dev, I2C_INT_MASK); int_mask &= ~mask; i2c_writel(i2c_dev, int_mask, I2C_INT_MASK); } static void tegra_i2c_unmask_irq(struct tegra_i2c_dev *i2c_dev, u32 mask) { u32 int_mask = i2c_readl(i2c_dev, I2C_INT_MASK); int_mask |= mask; i2c_writel(i2c_dev, int_mask, I2C_INT_MASK); } static int tegra_i2c_flush_fifos(struct tegra_i2c_dev *i2c_dev) { unsigned long timeout = jiffies + HZ; u32 val = i2c_readl(i2c_dev, I2C_FIFO_CONTROL); val |= I2C_FIFO_CONTROL_TX_FLUSH | I2C_FIFO_CONTROL_RX_FLUSH; i2c_writel(i2c_dev, val, I2C_FIFO_CONTROL); while (i2c_readl(i2c_dev, I2C_FIFO_CONTROL) & (I2C_FIFO_CONTROL_TX_FLUSH | I2C_FIFO_CONTROL_RX_FLUSH)) { if (time_after(jiffies, timeout)) { dev_warn(i2c_dev->dev, "timeout waiting for fifo flush\n"); return -ETIMEDOUT; } msleep(1); } return 0; } static int tegra_i2c_empty_rx_fifo(struct tegra_i2c_dev *i2c_dev) { u32 val; int rx_fifo_avail; u8 *buf = i2c_dev->msg_buf; size_t buf_remaining = i2c_dev->msg_buf_remaining; int words_to_transfer; val = i2c_readl(i2c_dev, I2C_FIFO_STATUS); rx_fifo_avail = (val & I2C_FIFO_STATUS_RX_MASK) >> I2C_FIFO_STATUS_RX_SHIFT; /* Rounds down to not include partial word at the end of buf */ words_to_transfer = buf_remaining / BYTES_PER_FIFO_WORD; if (words_to_transfer > rx_fifo_avail) words_to_transfer = rx_fifo_avail; i2c_readsl(i2c_dev, buf, I2C_RX_FIFO, words_to_transfer); buf += words_to_transfer * BYTES_PER_FIFO_WORD; buf_remaining -= words_to_transfer * BYTES_PER_FIFO_WORD; rx_fifo_avail -= words_to_transfer; /* * If there is a partial word at the end of buf, handle it manually to * prevent overwriting past the end of buf */ if (rx_fifo_avail > 0 && buf_remaining > 0) { BUG_ON(buf_remaining > 3); val = i2c_readl(i2c_dev, I2C_RX_FIFO); memcpy(buf, &val, buf_remaining); buf_remaining = 0; rx_fifo_avail--; } BUG_ON(rx_fifo_avail > 0 && buf_remaining > 0); i2c_dev->msg_buf_remaining = buf_remaining; i2c_dev->msg_buf = buf; return 0; } static int tegra_i2c_fill_tx_fifo(struct tegra_i2c_dev *i2c_dev) { u32 val; int tx_fifo_avail; u8 *buf = i2c_dev->msg_buf; size_t buf_remaining = i2c_dev->msg_buf_remaining; int words_to_transfer; val = i2c_readl(i2c_dev, I2C_FIFO_STATUS); tx_fifo_avail = (val & I2C_FIFO_STATUS_TX_MASK) >> I2C_FIFO_STATUS_TX_SHIFT; /* Rounds down to not include partial word at the end of buf */ words_to_transfer = buf_remaining / BYTES_PER_FIFO_WORD; /* It's very common to have < 4 bytes, so optimize that case. */ if (words_to_transfer) { if (words_to_transfer > tx_fifo_avail) words_to_transfer = tx_fifo_avail; /* * Update state before writing to FIFO. If this casues us * to finish writing all bytes (AKA buf_remaining goes to 0) we * have a potential for an interrupt (PACKET_XFER_COMPLETE is * not maskable). We need to make sure that the isr sees * buf_remaining as 0 and doesn't call us back re-entrantly. */ buf_remaining -= words_to_transfer * BYTES_PER_FIFO_WORD; tx_fifo_avail -= words_to_transfer; i2c_dev->msg_buf_remaining = buf_remaining; i2c_dev->msg_buf = buf + words_to_transfer * BYTES_PER_FIFO_WORD; barrier(); i2c_writesl(i2c_dev, buf, I2C_TX_FIFO, words_to_transfer); buf += words_to_transfer * BYTES_PER_FIFO_WORD; } /* * If there is a partial word at the end of buf, handle it manually to * prevent reading past the end of buf, which could cross a page * boundary and fault. */ if (tx_fifo_avail > 0 && buf_remaining > 0) { BUG_ON(buf_remaining > 3); memcpy(&val, buf, buf_remaining); /* Again update before writing to FIFO to make sure isr sees. */ i2c_dev->msg_buf_remaining = 0; i2c_dev->msg_buf = NULL; barrier(); i2c_writel(i2c_dev, val, I2C_TX_FIFO); } return 0; } /* * One of the Tegra I2C blocks is inside the DVC (Digital Voltage Controller) * block. This block is identical to the rest of the I2C blocks, except that * it only supports master mode, it has registers moved around, and it needs * some extra init to get it into I2C mode. The register moves are handled * by i2c_readl and i2c_writel */ static void tegra_dvc_init(struct tegra_i2c_dev *i2c_dev) { u32 val = 0; val = dvc_readl(i2c_dev, DVC_CTRL_REG3); val |= DVC_CTRL_REG3_SW_PROG; val |= DVC_CTRL_REG3_I2C_DONE_INTR_EN; dvc_writel(i2c_dev, val, DVC_CTRL_REG3); val = dvc_readl(i2c_dev, DVC_CTRL_REG1); val |= DVC_CTRL_REG1_INTR_EN; dvc_writel(i2c_dev, val, DVC_CTRL_REG1); } static int tegra_i2c_init(struct tegra_i2c_dev *i2c_dev) { u32 val; int err = 0; clk_enable(i2c_dev->clk); tegra_periph_reset_assert(i2c_dev->clk); udelay(2); tegra_periph_reset_deassert(i2c_dev->clk); if (i2c_dev->is_dvc) tegra_dvc_init(i2c_dev); val = I2C_CNFG_NEW_MASTER_FSM | I2C_CNFG_PACKET_MODE_EN | (0x2 << I2C_CNFG_DEBOUNCE_CNT_SHIFT); i2c_writel(i2c_dev, val, I2C_CNFG); i2c_writel(i2c_dev, 0, I2C_INT_MASK); clk_set_rate(i2c_dev->clk, i2c_dev->bus_clk_rate * 8); if (!i2c_dev->is_dvc) { u32 sl_cfg = i2c_readl(i2c_dev, I2C_SL_CNFG); sl_cfg |= I2C_SL_CNFG_NACK | I2C_SL_CNFG_NEWSL; i2c_writel(i2c_dev, sl_cfg, I2C_SL_CNFG); i2c_writel(i2c_dev, 0xfc, I2C_SL_ADDR1); i2c_writel(i2c_dev, 0x00, I2C_SL_ADDR2); } val = 7 << I2C_FIFO_CONTROL_TX_TRIG_SHIFT | 0 << I2C_FIFO_CONTROL_RX_TRIG_SHIFT; i2c_writel(i2c_dev, val, I2C_FIFO_CONTROL); if (tegra_i2c_flush_fifos(i2c_dev)) err = -ETIMEDOUT; clk_disable(i2c_dev->clk); if (i2c_dev->irq_disabled) { i2c_dev->irq_disabled = 0; enable_irq(i2c_dev->irq); } return err; } static irqreturn_t tegra_i2c_isr(int irq, void *dev_id) { u32 status; const u32 status_err = I2C_INT_NO_ACK | I2C_INT_ARBITRATION_LOST; struct tegra_i2c_dev *i2c_dev = dev_id; status = i2c_readl(i2c_dev, I2C_INT_STATUS); if (status == 0) { dev_warn(i2c_dev->dev, "irq status 0 %08x %08x %08x\n", i2c_readl(i2c_dev, I2C_PACKET_TRANSFER_STATUS), i2c_readl(i2c_dev, I2C_STATUS), i2c_readl(i2c_dev, I2C_CNFG)); i2c_dev->msg_err |= I2C_ERR_UNKNOWN_INTERRUPT; if (!i2c_dev->irq_disabled) { disable_irq_nosync(i2c_dev->irq); i2c_dev->irq_disabled = 1; } complete(&i2c_dev->msg_complete); goto err; } if (unlikely(status & status_err)) { if (status & I2C_INT_NO_ACK) i2c_dev->msg_err |= I2C_ERR_NO_ACK; if (status & I2C_INT_ARBITRATION_LOST) i2c_dev->msg_err |= I2C_ERR_ARBITRATION_LOST; complete(&i2c_dev->msg_complete); goto err; } if (i2c_dev->msg_read && (status & I2C_INT_RX_FIFO_DATA_REQ)) { if (i2c_dev->msg_buf_remaining) tegra_i2c_empty_rx_fifo(i2c_dev); else BUG(); } if (!i2c_dev->msg_read && (status & I2C_INT_TX_FIFO_DATA_REQ)) { if (i2c_dev->msg_buf_remaining) tegra_i2c_fill_tx_fifo(i2c_dev); else tegra_i2c_mask_irq(i2c_dev, I2C_INT_TX_FIFO_DATA_REQ); } if (status & I2C_INT_PACKET_XFER_COMPLETE) { BUG_ON(i2c_dev->msg_buf_remaining); complete(&i2c_dev->msg_complete); } i2c_writel(i2c_dev, status, I2C_INT_STATUS); if (i2c_dev->is_dvc) dvc_writel(i2c_dev, DVC_STATUS_I2C_DONE_INTR, DVC_STATUS); return IRQ_HANDLED; err: /* An error occurred, mask all interrupts */ tegra_i2c_mask_irq(i2c_dev, I2C_INT_NO_ACK | I2C_INT_ARBITRATION_LOST | I2C_INT_PACKET_XFER_COMPLETE | I2C_INT_TX_FIFO_DATA_REQ | I2C_INT_RX_FIFO_DATA_REQ); i2c_writel(i2c_dev, status, I2C_INT_STATUS); if (i2c_dev->is_dvc) dvc_writel(i2c_dev, DVC_STATUS_I2C_DONE_INTR, DVC_STATUS); return IRQ_HANDLED; } static int tegra_i2c_xfer_msg(struct tegra_i2c_dev *i2c_dev, struct i2c_msg *msg, int stop) { u32 packet_header; u32 int_mask; int ret; tegra_i2c_flush_fifos(i2c_dev); if (msg->len == 0) return -EINVAL; i2c_dev->msg_buf = msg->buf; i2c_dev->msg_buf_remaining = msg->len; i2c_dev->msg_err = I2C_ERR_NONE; i2c_dev->msg_read = (msg->flags & I2C_M_RD); INIT_COMPLETION(i2c_dev->msg_complete); packet_header = (0 << PACKET_HEADER0_HEADER_SIZE_SHIFT) | PACKET_HEADER0_PROTOCOL_I2C | (i2c_dev->cont_id << PACKET_HEADER0_CONT_ID_SHIFT) | (1 << PACKET_HEADER0_PACKET_ID_SHIFT); i2c_writel(i2c_dev, packet_header, I2C_TX_FIFO); packet_header = msg->len - 1; i2c_writel(i2c_dev, packet_header, I2C_TX_FIFO); packet_header = msg->addr << I2C_HEADER_SLAVE_ADDR_SHIFT; packet_header |= I2C_HEADER_IE_ENABLE; if (!stop) packet_header |= I2C_HEADER_REPEAT_START; if (msg->flags & I2C_M_TEN) packet_header |= I2C_HEADER_10BIT_ADDR; if (msg->flags & I2C_M_IGNORE_NAK) packet_header |= I2C_HEADER_CONT_ON_NAK; if (msg->flags & I2C_M_RD) packet_header |= I2C_HEADER_READ; i2c_writel(i2c_dev, packet_header, I2C_TX_FIFO); if (!(msg->flags & I2C_M_RD)) tegra_i2c_fill_tx_fifo(i2c_dev); int_mask = I2C_INT_NO_ACK | I2C_INT_ARBITRATION_LOST; if (msg->flags & I2C_M_RD) int_mask |= I2C_INT_RX_FIFO_DATA_REQ; else if (i2c_dev->msg_buf_remaining) int_mask |= I2C_INT_TX_FIFO_DATA_REQ; tegra_i2c_unmask_irq(i2c_dev, int_mask); dev_dbg(i2c_dev->dev, "unmasked irq: %02x\n", i2c_readl(i2c_dev, I2C_INT_MASK)); ret = wait_for_completion_timeout(&i2c_dev->msg_complete, TEGRA_I2C_TIMEOUT); tegra_i2c_mask_irq(i2c_dev, int_mask); if (WARN_ON(ret == 0)) { dev_err(i2c_dev->dev, "i2c transfer timed out\n"); tegra_i2c_init(i2c_dev); return -ETIMEDOUT; } dev_dbg(i2c_dev->dev, "transfer complete: %d %d %d\n", ret, completion_done(&i2c_dev->msg_complete), i2c_dev->msg_err); if (likely(i2c_dev->msg_err == I2C_ERR_NONE)) return 0; /* * NACK interrupt is generated before the I2C controller generates the * STOP condition on the bus. So wait for 2 clock periods before resetting * the controller so that STOP condition has been delivered properly. */ if (i2c_dev->msg_err == I2C_ERR_NO_ACK) udelay(DIV_ROUND_UP(2 * 1000000, i2c_dev->bus_clk_rate)); tegra_i2c_init(i2c_dev); if (i2c_dev->msg_err == I2C_ERR_NO_ACK) { if (msg->flags & I2C_M_IGNORE_NAK) return 0; return -EREMOTEIO; } return -EIO; } static int tegra_i2c_xfer(struct i2c_adapter *adap, struct i2c_msg msgs[], int num) { struct tegra_i2c_dev *i2c_dev = i2c_get_adapdata(adap); int i; int ret = 0; if (i2c_dev->is_suspended) return -EBUSY; clk_enable(i2c_dev->clk); for (i = 0; i < num; i++) { int stop = (i == (num - 1)) ? 1 : 0; ret = tegra_i2c_xfer_msg(i2c_dev, &msgs[i], stop); if (ret) break; } clk_disable(i2c_dev->clk); return ret ?: i; } static u32 tegra_i2c_func(struct i2c_adapter *adap) { return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL; } static const struct i2c_algorithm tegra_i2c_algo = { .master_xfer = tegra_i2c_xfer, .functionality = tegra_i2c_func, }; static int __devinit tegra_i2c_probe(struct platform_device *pdev) { struct tegra_i2c_dev *i2c_dev; struct tegra_i2c_platform_data *pdata = pdev->dev.platform_data; struct resource *res; struct resource *iomem; struct clk *clk; struct clk *i2c_clk; const unsigned int *prop; void __iomem *base; int irq; int ret = 0; res = platform_get_resource(pdev, IORESOURCE_MEM, 0); if (!res) { dev_err(&pdev->dev, "no mem resource\n"); return -EINVAL; } iomem = request_mem_region(res->start, resource_size(res), pdev->name); if (!iomem) { dev_err(&pdev->dev, "I2C region already claimed\n"); return -EBUSY; } base = ioremap(iomem->start, resource_size(iomem)); if (!base) { dev_err(&pdev->dev, "Cannot ioremap I2C region\n"); return -ENOMEM; } res = platform_get_resource(pdev, IORESOURCE_IRQ, 0); if (!res) { dev_err(&pdev->dev, "no irq resource\n"); ret = -EINVAL; goto err_iounmap; } irq = res->start; clk = clk_get(&pdev->dev, NULL); if (IS_ERR(clk)) { dev_err(&pdev->dev, "missing controller clock"); ret = PTR_ERR(clk); goto err_release_region; } i2c_clk = clk_get(&pdev->dev, "i2c"); if (IS_ERR(i2c_clk)) { dev_err(&pdev->dev, "missing bus clock"); ret = PTR_ERR(i2c_clk); goto err_clk_put; } i2c_dev = kzalloc(sizeof(struct tegra_i2c_dev), GFP_KERNEL); if (!i2c_dev) { ret = -ENOMEM; goto err_i2c_clk_put; } i2c_dev->base = base; i2c_dev->clk = clk; i2c_dev->i2c_clk = i2c_clk; i2c_dev->iomem = iomem; i2c_dev->adapter.algo = &tegra_i2c_algo; i2c_dev->irq = irq; i2c_dev->cont_id = pdev->id; i2c_dev->dev = &pdev->dev; i2c_dev->bus_clk_rate = 100000; /* default clock rate */ if (pdata) { i2c_dev->bus_clk_rate = pdata->bus_clk_rate; } else if (i2c_dev->dev->of_node) { /* if there is a device tree node ... */ prop = of_get_property(i2c_dev->dev->of_node, "clock-frequency", NULL); if (prop) i2c_dev->bus_clk_rate = be32_to_cpup(prop); } if (pdev->dev.of_node) i2c_dev->is_dvc = of_device_is_compatible(pdev->dev.of_node, "nvidia,tegra20-i2c-dvc"); else if (pdev->id == 3) i2c_dev->is_dvc = 1; init_completion(&i2c_dev->msg_complete); platform_set_drvdata(pdev, i2c_dev); ret = tegra_i2c_init(i2c_dev); if (ret) { dev_err(&pdev->dev, "Failed to initialize i2c controller"); goto err_free; } ret = request_irq(i2c_dev->irq, tegra_i2c_isr, 0, pdev->name, i2c_dev); if (ret) { dev_err(&pdev->dev, "Failed to request irq %i\n", i2c_dev->irq); goto err_free; } clk_enable(i2c_dev->i2c_clk); i2c_set_adapdata(&i2c_dev->adapter, i2c_dev); i2c_dev->adapter.owner = THIS_MODULE; i2c_dev->adapter.class = I2C_CLASS_HWMON; strlcpy(i2c_dev->adapter.name, "Tegra I2C adapter", sizeof(i2c_dev->adapter.name)); i2c_dev->adapter.algo = &tegra_i2c_algo; i2c_dev->adapter.dev.parent = &pdev->dev; i2c_dev->adapter.nr = pdev->id; i2c_dev->adapter.dev.of_node = pdev->dev.of_node; ret = i2c_add_numbered_adapter(&i2c_dev->adapter); if (ret) { dev_err(&pdev->dev, "Failed to add I2C adapter\n"); goto err_free_irq; } of_i2c_register_devices(&i2c_dev->adapter); return 0; err_free_irq: free_irq(i2c_dev->irq, i2c_dev); err_free: kfree(i2c_dev); err_i2c_clk_put: clk_put(i2c_clk); err_clk_put: clk_put(clk); err_release_region: release_mem_region(iomem->start, resource_size(iomem)); err_iounmap: iounmap(base); return ret; } static int __devexit tegra_i2c_remove(struct platform_device *pdev) { struct tegra_i2c_dev *i2c_dev = platform_get_drvdata(pdev); i2c_del_adapter(&i2c_dev->adapter); free_irq(i2c_dev->irq, i2c_dev); clk_put(i2c_dev->i2c_clk); clk_put(i2c_dev->clk); release_mem_region(i2c_dev->iomem->start, resource_size(i2c_dev->iomem)); iounmap(i2c_dev->base); kfree(i2c_dev); return 0; } #ifdef CONFIG_PM static int tegra_i2c_suspend(struct platform_device *pdev, pm_message_t state) { struct tegra_i2c_dev *i2c_dev = platform_get_drvdata(pdev); i2c_lock_adapter(&i2c_dev->adapter); i2c_dev->is_suspended = true; i2c_unlock_adapter(&i2c_dev->adapter); return 0; } static int tegra_i2c_resume(struct platform_device *pdev) { struct tegra_i2c_dev *i2c_dev = platform_get_drvdata(pdev); int ret; i2c_lock_adapter(&i2c_dev->adapter); ret = tegra_i2c_init(i2c_dev); if (ret) { i2c_unlock_adapter(&i2c_dev->adapter); return ret; } i2c_dev->is_suspended = false; i2c_unlock_adapter(&i2c_dev->adapter); return 0; } #endif #if defined(CONFIG_OF) /* Match table for of_platform binding */ static const struct of_device_id tegra_i2c_of_match[] __devinitconst = { { .compatible = "nvidia,tegra20-i2c", }, { .compatible = "nvidia,tegra20-i2c-dvc", }, {}, }; MODULE_DEVICE_TABLE(of, tegra_i2c_of_match); #else #define tegra_i2c_of_match NULL #endif static struct platform_driver tegra_i2c_driver = { .probe = tegra_i2c_probe, .remove = __devexit_p(tegra_i2c_remove), #ifdef CONFIG_PM .suspend = tegra_i2c_suspend, .resume = tegra_i2c_resume, #endif .driver = { .name = "tegra-i2c", .owner = THIS_MODULE, .of_match_table = tegra_i2c_of_match, }, }; static int __init tegra_i2c_init_driver(void) { return platform_driver_register(&tegra_i2c_driver); } static void __exit tegra_i2c_exit_driver(void) { platform_driver_unregister(&tegra_i2c_driver); } subsys_initcall(tegra_i2c_init_driver); module_exit(tegra_i2c_exit_driver); MODULE_DESCRIPTION("nVidia Tegra2 I2C Bus Controller driver"); MODULE_AUTHOR("Colin Cross"); MODULE_LICENSE("GPL v2");
Jackeagle/android_kernel_sony_c2305
drivers/i2c/busses/i2c-tegra.c
C
gpl-2.0
22,597
module.exports = { "methods": { "wiki": function(msg, sender, api) { var query = msg.match(/\".+\"/)[0]; query = query.substring(1, query.length-1); var base = "http://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&rawcontinue&redirects&titles="+encodeURIComponent(query); api.request(base, function(err, res, body) { var info = JSON.parse(body); var page; for (f in info.query.pages) { page = info.query.pages[f]; } if (page.missing === undefined) { var text; var testpos = 0; while (true) { var pos = page.extract.indexOf(".", testpos); if (pos === -1) { api.randomMessage("oddresult", {"query": query}); return; } text = page.extract.substr(0, pos+1); var bstart = text.lastIndexOf("<b>"); var bend = text.lastIndexOf("</b>"); if (bstart < bend || (bstart === -1 && bend === -1)) break; testpos = pos + 1; } text = text.replace(/<\/?[^>]+(>|$)/g, ""); if (text.indexOf("\n") > 0) text = text.substr(0, text.indexOf("\n")); else if (text.indexOf("\n") === 0) text = text.substr(1); if (text.length === text.lastIndexOf("may refer to:") + 13) { api.randomMessage("oddresult", {"query": query}); return; } api.say(text); } else { api.randomMessage("nodefs", {"query": query}); } }); } } }
mortie/ladbot-plugins
wikipedia/index.js
JavaScript
gpl-2.0
1,466
package org.misha.domain.algebra.lie.polynomial.monomial; /** * Author: mshevelin * Date: 3/28/14 * Time: 3:21 PM */ abstract class MonomialVisitor { void visit(final Monomial m) { if (m.isLetter()) { doSomethingWith(m); return; } final Monomial left = m.left(); final Monomial right = m.right(); doSomethingWith(left); doSomethingWith(right); visit(left); visit(right); } protected abstract void doSomethingWith(Monomial m); }
shma2001gmailcom/lie-fe
src/main/java/org/misha/domain/algebra/lie/polynomial/monomial/MonomialVisitor.java
Java
gpl-2.0
536
<?php if (!defined('ABSPATH')) die('No direct access allowed'); class WOOF_Widget extends WP_Widget { //Widget Setup public function __construct() { parent::__construct(__CLASS__, __('WOOF - WooCommerce Products Filter', 'woocommerce-products-filter'), array( 'classname' => __CLASS__, 'description' => __('WooCommerce Products Filter by realmag777', 'woocommerce-products-filter') ) ); } //Widget view public function widget($args, $instance) { $args['instance'] = $instance; $args['sidebar_id'] = $args['id']; $args['sidebar_name'] = $args['name']; //+++ global $WOOF; if (isset($WOOF->settings['by_price']['show'])) { //just for compatibility from 2.1.2 to 2.1.3 $price_filter = (int) $WOOF->settings['by_price']['show']; } else { $price_filter = (int) get_option('woof_show_price_search', 0); } if (isset($args['before_widget'])) { echo $args['before_widget']; } ?> <div class="widget widget-woof"> <?php if (!empty($instance['title'])) { if (isset($args['before_title'])) { echo $args['before_title']; echo $instance['title']; echo $args['after_title']; } else { ?> <h3 class="widget-title"><?php echo $instance['title'] ?></h3> <?php } } ?> <?php if (isset($instance['additional_text_before'])) { echo do_shortcode($instance['additional_text_before']); } $redirect = ''; if (isset($instance['redirect'])) { $redirect = $instance['redirect']; } $ajax_redraw = ''; if (isset($instance['ajax_redraw'])) { $ajax_redraw = $instance['ajax_redraw']; } ?> <?php echo do_shortcode('[woof sid="widget" price_filter=' . $price_filter . ' redirect="' . $redirect . '" ajax_redraw=' . $ajax_redraw . ']'); ?> </div> <?php if (isset($args['after_widget'])) { echo $args['after_widget']; } } //Update widget public function update($new_instance, $old_instance) { $instance = $old_instance; $instance['title'] = $new_instance['title']; $instance['additional_text_before'] = $new_instance['additional_text_before']; $instance['redirect'] = $new_instance['redirect']; $instance['ajax_redraw'] = $new_instance['ajax_redraw']; return $instance; } //Widget form public function form($instance) { //Defaults $defaults = array( 'title' => __('WooCommerce Products Filter', 'woocommerce-products-filter'), 'additional_text_before' => '', 'redirect' => '', 'ajax_redraw' => 0 ); $instance = wp_parse_args((array) $instance, $defaults); $args = array(); $args['instance'] = $instance; $args['widget'] = $this; ?> <p> <label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title', 'woocommerce-products-filter') ?>:</label> <input class="widefat" type="text" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" value="<?php echo $instance['title']; ?>" /> </p> <p> <label for="<?php echo $this->get_field_id('additional_text_before'); ?>"><?php _e('Additional text before', 'woocommerce-products-filter') ?>:</label> <textarea class="widefat" type="text" id="<?php echo $this->get_field_id('additional_text_before'); ?>" name="<?php echo $this->get_field_name('additional_text_before'); ?>"><?php echo $instance['additional_text_before']; ?></textarea> </p> <p> <label for="<?php echo $this->get_field_id('redirect'); ?>"><?php _e('Redirect to', 'woocommerce-products-filter') ?>:</label> <input class="widefat" type="text" id="<?php echo $this->get_field_id('redirect'); ?>" name="<?php echo $this->get_field_name('redirect'); ?>" value="<?php echo $instance['redirect']; ?>" /><br /> <i><?php _e('Redirect to any page - use it by your own logic. Leave it empty for default behavior.', 'woocommerce-products-filter') ?></i> </p> <p> <label for="<?php echo $this->get_field_id('ajax_redraw'); ?>"><?php _e('Form AJAX redrawing', 'woocommerce-products-filter') ?>:</label> <?php $options = array( 0 => __('No', 'woocommerce-products-filter'), 1 => __('Yes', 'woocommerce-products-filter') ); ?> <select class="widefat" id="<?php echo $this->get_field_id('ajax_redraw') ?>" name="<?php echo $this->get_field_name('ajax_redraw') ?>"> <?php foreach ($options as $k => $val) : ?> <option <?php selected($instance['ajax_redraw'], $k) ?> value="<?php echo $k ?>" class="level-0"><?php echo $val ?></option> <?php endforeach; ?> </select> <i><?php _e('Useful when uses hierarchical drop-down for example', 'woocommerce-products-filter') ?></i> </p> <?php } }
Web-Ares/shop-shablon
wp-content/plugins/woocommerce-products-filter/classes/widgets.php
PHP
gpl-2.0
5,598
import werkzeug from openerp import http, SUPERUSER_ID from openerp.http import request class MassMailController(http.Controller): @http.route('/mail/track/<int:mail_id>/blank.gif', type='http', auth='none') def track_mail_open(self, mail_id, **post): """ Email tracking. """ mail_mail_stats = request.registry.get('mail.mail.statistics') mail_mail_stats.set_opened(request.cr, SUPERUSER_ID, mail_mail_ids=[mail_id]) response = werkzeug.wrappers.Response() response.mimetype = 'image/gif' response.data = 'R0lGODlhAQABAIAAANvf7wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=='.decode('base64') return response @http.route(['/mail/mailing/<int:mailing_id>/unsubscribe'], type='http', auth='none') def mailing(self, mailing_id, email=None, res_id=None, **post): cr, uid, context = request.cr, request.uid, request.context MassMailing = request.registry['mail.mass_mailing'] mailing_ids = MassMailing.exists(cr, SUPERUSER_ID, [mailing_id], context=context) if not mailing_ids: return 'KO' mailing = MassMailing.browse(cr, SUPERUSER_ID, mailing_ids[0], context=context) if mailing.mailing_model == 'mail.mass_mailing.contact': list_ids = [l.id for l in mailing.contact_list_ids] record_ids = request.registry[mailing.mailing_model].search(cr, SUPERUSER_ID, [('list_id', 'in', list_ids), ('id', '=', res_id), ('email', 'ilike', email)], context=context) request.registry[mailing.mailing_model].write(cr, SUPERUSER_ID, record_ids, {'opt_out': True}, context=context) else: email_fname = None if 'email_from' in request.registry[mailing.mailing_model]._all_columns: email_fname = 'email_from' elif 'email' in request.registry[mailing.mailing_model]._all_columns: email_fname = 'email' if email_fname: record_ids = request.registry[mailing.mailing_model].search(cr, SUPERUSER_ID, [('id', '=', res_id), (email_fname, 'ilike', email)], context=context) if 'opt_out' in request.registry[mailing.mailing_model]._all_columns: request.registry[mailing.mailing_model].write(cr, SUPERUSER_ID, record_ids, {'opt_out': True}, context=context) return 'OK'
3dfxsoftware/cbss-addons
mass_mailing/controllers/main.py
Python
gpl-2.0
2,342
<?php if ( ! defined( 'PCAFW' ) ) { echo 'This file can only be called via the main index.php file, and not directly'; exit(); } class database { protected $connection; /** * Record of the last query */ protected $last; public function __construct() { } /** * Create a new database connection * @param String database hostname * @param String database username * @param String database password * @param String database we are using * @return int the id of the new connection */ public function newConnection( $host, $user, $password, $database ) { $this->connection = new mysqli( $host, $user, $password, $database ); if( mysqli_connect_errno() ) { trigger_error('Error connecting to host. '.$this->connections[$connection_id]->error, E_USER_ERROR); } $this->connection->set_charset("utf8"); return TRUE; } /** * Close the connection * @return void */ public function closeConnection() { $this->connection->close(); } /** * Delete records from the database * @param String the table to remove rows from * @param String the condition for which rows are to be removed * @param int the number of rows to be removed * @return void */ public function deleteRecords( $table, $condition, $limit ) { $limit = ( $limit == '' ) ? '' : ' LIMIT ' . $limit; $delete = "DELETE FROM {$table} WHERE {$condition} {$limit}"; $this->executeQuery( $delete ); } /** * Update records in the database * @param String the table * @param array of changes field => value * @param String the condition * @return bool */ public function updateRecords( $table, $changes, $condition ) { $update = "UPDATE " . $table . " SET "; foreach( $changes as $field => $value ) { $update .= "`" . $field . "`='{$value}',"; } // remove our trailing , $update = substr($update, 0, -1); if( $condition != '' ) { $update .= "WHERE " . $condition; } $this->executeQuery( $update ); return true; } /** * Insert records into the database * @param String the database table * @param array data to insert field => value * @return bool */ public function insertRecords( $table, $data ) { // setup some variables for fields and values $fields = ""; $values = ""; // populate them foreach ($data as $f => $v) { $fields .= "`$f`,"; $values .= ( is_numeric( $v ) && ( intval( $v ) == $v ) ) ? $v."," : "'$v',"; } // remove our trailing , $fields = substr($fields, 0, -1); // remove our trailing , $values = substr($values, 0, -1); $insert = "INSERT INTO $table ({$fields}) VALUES({$values})"; $this->executeQuery( $insert ); return true; } /** * Execute a query string * @param String the query * @return void */ public function executeQuery( $queryStr ) { if( !$result = $this->connection->query( $queryStr ) ) { trigger_error('Error executing query: '.$this->connection->error, E_USER_ERROR); } else { $this->last = $result; } } /** * Get the rows from the most recently executed query, excluding cached queries * @return array */ public function getRows() { return $this->last->fetch_array(MYSQLI_ASSOC); } /** * Gets the number of affected rows from the previous query * @return int the number of affected rows */ public function affectedRows() { return $this->connection->affected_rows; } /** * Gets the number of selected rows from the previous query * @return int the number of selected rows */ public function numRows() { return $this->last->num_rows; } /** * Sanitize data * @param String the data to be sanitized * @return String the sanitized data */ public function sanitizeData( $data ) { return $this->connection->real_escape_string( $data ); } /** * Get last insert id * @return int id */ public function insertId() { return $this->connection->insert_id; } /** * Deconstruct the object * close all of the database connections */ public function __deconstruct() { $connection->close(); } } ?>
edasubert/tct
testing/framework/objects/database.class.php
PHP
gpl-2.0
4,138
<?php namespace Drupal\Tests\linkit\FunctionalJavascript; use Drupal\Core\Entity\Entity\EntityFormDisplay; use Drupal\editor\Entity\Editor; use Drupal\entity_test\Entity\EntityTestMul; use Drupal\field\Entity\FieldConfig; use Drupal\field\Entity\FieldStorageConfig; use Drupal\filter\Entity\FilterFormat; use Drupal\FunctionalJavascriptTests\JavascriptTestBase; use Drupal\language\Entity\ConfigurableLanguage; use Drupal\linkit\Tests\ProfileCreationTrait; use Drupal\node\Entity\NodeType; /** * Tests the linkit alterations on the drupallink plugin. * * @group linkit */ class LinkitDialogTest extends JavascriptTestBase { use ProfileCreationTrait; /** * Modules to enable. * * @var array */ public static $modules = [ 'node', 'ckeditor', 'filter', 'linkit', 'entity_test', 'language', ]; /** * An instance of the "CKEditor" text editor plugin. * * @var \Drupal\ckeditor\Plugin\Editor\CKEditor */ protected $ckeditor; /** * A linkit profile. * * @var \Drupal\linkit\ProfileInterface */ protected $linkitProfile; /** * {@inheritdoc} */ protected function setUp() { parent::setUp(); $matcherManager = $this->container->get('plugin.manager.linkit.matcher'); /** @var \Drupal\linkit\MatcherInterface $plugin */ $this->linkitProfile = $this->createProfile(); $plugin = $matcherManager->createInstance('entity:entity_test_mul'); $this->linkitProfile->addMatcher($plugin->getConfiguration()); $this->linkitProfile->save(); // Create text format, associate CKEditor. $llama_format = FilterFormat::create([ 'format' => 'llama', 'name' => 'Llama', 'weight' => 0, 'filters' => [], ]); $llama_format->save(); $editor = Editor::create([ 'format' => 'llama', 'editor' => 'ckeditor', ]); $editor->save(); // Create "CKEditor" text editor plugin instance. $this->ckeditor = $this->container->get('plugin.manager.editor')->createInstance('ckeditor'); // Create a node type for testing. NodeType::create(['type' => 'page', 'name' => 'page'])->save(); // Create a body field instance for the 'page' node type. FieldConfig::create([ 'field_storage' => FieldStorageConfig::loadByName('node', 'body'), 'bundle' => 'page', 'label' => 'Body', 'settings' => ['display_summary' => TRUE], 'required' => TRUE, ])->save(); // Assign widget settings for the 'default' form mode. EntityFormDisplay::create([ 'targetEntityType' => 'node', 'bundle' => 'page', 'mode' => 'default', 'status' => TRUE, ])->setComponent('body', ['type' => 'text_textarea_with_summary'])->save(); // Customize the configuration. $this->container->get('plugin.manager.editor')->clearCachedDefinitions(); $this->ckeditor = $this->container->get('plugin.manager.editor')->createInstance('ckeditor'); $this->container->get('plugin.manager.ckeditor.plugin')->clearCachedDefinitions(); $settings = $editor->getSettings(); $settings['plugins']['drupallink']['linkit_enabled'] = TRUE; $settings['plugins']['drupallink']['linkit_profile'] = $this->linkitProfile->id(); $editor->setSettings($settings); $editor->save(); $account = $this->drupalCreateUser([ 'administer nodes', 'create page content', 'edit own page content', 'use text format llama', 'view test entity', ]); $this->drupalLogin($account); } /** * Test the link dialog. */ public function testLinkDialog() { $session = $this->getSession(); $web_assert = $this->assertSession(); $page = $session->getPage(); // Adds additional languages. $langcodes = ['sv', 'da', 'fi']; foreach ($langcodes as $langcode) { ConfigurableLanguage::createFromLangcode($langcode)->save(); } // Create a test entity. /** @var \Drupal\Core\Entity\EntityInterface $entity */ $entity = EntityTestMul::create(['name' => 'Foo']); $entity->save(); // Go to node creation page. $this->drupalGet('node/add/page'); // Wait until the editor has been loaded. $ckeditor_loaded = $this->getSession()->wait(5000, "jQuery('.cke_contents').length > 0"); $this->assertTrue($ckeditor_loaded, 'The editor has been loaded.'); // Click on the drupallink plugin. $page->find('css', 'a.cke_button__drupallink')->click(); // Wait for the form to load. $web_assert->assertWaitOnAjaxRequest(); // Find the href field. $href_field = $page->findField('attributes[href]'); // Make sure the href field is an autocomplete field. $href_field->hasAttribute('data-autocomplete-path'); $href_field->hasClass('form-linkit-autocomplete'); $href_field->hasClass('ui-autocomplete-input'); // Make sure all fields are empty. $this->assertEmpty($href_field->getValue(), 'Href field is empty.'); $this->assertEmptyWithJs('attributes[data-entity-type]'); $this->assertEmptyWithJs('attributes[data-entity-uuid]'); $this->assertEmptyWithJs('attributes[data-entity-substitution]'); $this->assertEmptyWithJs('href_dirty_check'); // Make sure the autocomplete result container is hidden. $autocomplete_container = $page->find('css', 'ul.linkit-ui-autocomplete'); $this->assertFalse($autocomplete_container->isVisible()); // Trigger a keydown event to active a autocomplete search. $href_field->keyDown('f'); // Wait for the results to load. $this->getSession()->wait(5000, "jQuery('.linkit-result.ui-menu-item').length > 0"); // Make sure the autocomplete result container is visible. $this->assertTrue($autocomplete_container->isVisible()); // Find all the autocomplete results. $results = $page->findAll('css', '.linkit-result.ui-menu-item'); $this->assertEquals(1, count($results), 'Found autocomplete result'); // Find the first result and click it. $page->find('xpath', '(//li[contains(@class, "linkit-result") and contains(@class, "ui-menu-item")])[1]')->click(); // Make sure the linkit field field is populated with the node url. $this->assertEquals($entity->toUrl()->toString(), $href_field->getValue(), 'The href field is populated with the node url.'); // Make sure all other fields are populated. $this->assertEqualsWithJs('attributes[data-entity-type]', $entity->getEntityTypeId()); $this->assertEqualsWithJs('attributes[data-entity-uuid]', $entity->uuid()); $this->assertEqualsWithJs('attributes[data-entity-substitution]', 'canonical'); $this->assertEqualsWithJs('href_dirty_check', $entity->toUrl()->toString()); // Save the dialog input. $page->find('css', '.editor-link-dialog')->find('css', '.button.form-submit span')->click(); // Wait for the dialog to close. $web_assert->assertWaitOnAjaxRequest(); $fields = [ 'data-entity-type' => $entity->getEntityTypeId(), 'data-entity-uuid' => $entity->uuid(), 'data-entity-substitution' => 'canonical', 'href' => $entity->toUrl()->toString(), ]; foreach ($fields as $attribute => $value) { $link_attribute = $this->getLinkAttributeFromEditor($attribute); $this->assertEquals($value, $link_attribute, 'The link contain an attribute by the name of "' . $attribute . '" with a value of "' . $value . '"'); } // Select the link in the editor. $javascript = <<<JS (function(){ var editor = window.CKEDITOR.instances['edit-body-0-value']; console.log(editor); var element = editor.document.findOne( 'a' ); editor.getSelection().selectElement( element ); })() JS; $session->executeScript($javascript); // Click on the drupallink plugin. $page->find('css', 'a.cke_button__drupallink')->click(); // Wait for the form to load. $web_assert->assertWaitOnAjaxRequest(); // Find the href field. $href_field = $page->findField('attributes[href]'); $this->assertEquals($entity->toUrl()->toString(), $href_field->getValue(), 'Href field contains the node url when edit.'); // Make sure all other fields are populated when editing a link. $this->assertEqualsWithJs('attributes[data-entity-type]', $entity->getEntityTypeId()); $this->assertEqualsWithJs('attributes[data-entity-uuid]', $entity->uuid()); $this->assertEqualsWithJs('attributes[data-entity-substitution]', 'canonical'); $this->assertEqualsWithJs('href_dirty_check', $entity->toUrl()->toString()); // Edit the href field and set an external url. $href_field->setValue('http://example.com'); // Save the dialog input. $page->find('css', '.editor-link-dialog')->find('css', '.button.form-submit span')->click(); // Wait for the dialog to close. $web_assert->assertWaitOnAjaxRequest(); $fields = [ 'data-entity-type', 'data-entity-uuid', 'data-entity-substitution', ]; foreach ($fields as $attribute) { $link_attribute = $this->getLinkAttributeFromEditor($attribute); $this->assertNull($link_attribute, 'The link does not contain an attribute by the name of "' . $attribute . '"'); } $href_attribute = $this->getLinkAttributeFromEditor('href'); $this->assertEquals('http://example.com', $href_attribute, 'The link href is correct.'); } /** * Asserts that a variable is empty. * * @param string $field_name * The name of the field. */ private function assertEmptyWithJs($field_name) { $javascript = "(function (){ return jQuery('input[name=\"" . $field_name . "\"]').val(); })()"; $field_value = $this->getSession()->evaluateScript($javascript); $this->assertEmpty($field_value, 'The "' . $field_name . '" field is empty.'); } /** * Asserts that two variables are equal. * * @param string $field_name * The name of the field. * @param string $expected * The expected value. */ private function assertEqualsWithJs($field_name, $expected) { $javascript = "(function (){ return jQuery('input[name=\"" . $field_name . "\"]').val(); })()"; $field_value = $this->getSession()->evaluateScript($javascript); $this->assertEquals($expected, $field_value, 'The "' . $field_name . '" field has a value of "' . $expected . '".'); } /** * Gets an attribute of the first link in the ckeditor editor. * * @param string $attribute * The attribute name. * * @return string|null * The attribute, or null if the attribute is not found on the element. */ private function getLinkAttributeFromEditor($attribute) { // We can't use $session->switchToIFrame() here, because the iframe does not // have a name. $javascript = <<<JS (function(){ var iframes = document.getElementsByClassName('cke_wysiwyg_frame'); if (iframes.length) { var doc = iframes[0].contentDocument || iframes[0].contentWindow.document; var link = doc.getElementsByTagName('a')[0]; return link.getAttribute("$attribute"); } })() JS; return $this->getSession()->evaluateScript($javascript); } }
castillo8811/informe24
modules/linkit/tests/src/FunctionalJavascript/LinkitDialogTest.php
PHP
gpl-2.0
11,170
/* * Copyright 1997-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ #include <windows.h> #include <winsock2.h> #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <malloc.h> #include <sys/types.h> #include "java_net_SocketOutputStream.h" #include "net_util.h" #include "jni_util.h" /************************************************************************ * SocketOutputStream */ static jfieldID IO_fd_fdID; /* * Class: java_net_SocketOutputStream * Method: init * Signature: ()V */ JNIEXPORT void JNICALL Java_java_net_SocketOutputStream_init(JNIEnv *env, jclass cls) { IO_fd_fdID = NET_GetFileDescriptorID(env); } /* * Class: java_net_SocketOutputStream * Method: socketWrite * Signature: (Ljava/io/FileDescriptor;[BII)V */ JNIEXPORT void JNICALL Java_java_net_SocketOutputStream_socketWrite0(JNIEnv *env, jobject this, jobject fdObj, jbyteArray data, jint off, jint len) { char *bufP; char BUF[MAX_BUFFER_LEN]; int buflen; int fd; if (IS_NULL(fdObj)) { JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException", "Socket closed"); return; } else { fd = (*env)->GetIntField(env, fdObj, IO_fd_fdID); } if (IS_NULL(data)) { JNU_ThrowNullPointerException(env, "data argument"); return; } /* * Use stack allocate buffer if possible. For large sizes we allocate * an intermediate buffer from the heap (up to a maximum). If heap is * unavailable just use our stack buffer. */ if (len <= MAX_BUFFER_LEN) { bufP = BUF; buflen = MAX_BUFFER_LEN; } else { buflen = min(MAX_HEAP_BUFFER_LEN, len); bufP = (char *)malloc((size_t)buflen); if (bufP == NULL) { bufP = BUF; buflen = MAX_BUFFER_LEN; } } while(len > 0) { int loff = 0; int chunkLen = min(buflen, len); int llen = chunkLen; int retry = 0; (*env)->GetByteArrayRegion(env, data, off, chunkLen, (jbyte *)bufP); while(llen > 0) { int n = send(fd, bufP + loff, llen, 0); if (n > 0) { llen -= n; loff += n; continue; } /* * Due to a bug in Windows Sockets (observed on NT and Windows * 2000) it may be necessary to retry the send. The issue is that * on blocking sockets send/WSASend is supposed to block if there * is insufficient buffer space available. If there are a large * number of threads blocked on write due to congestion then it's * possile to hit the NT/2000 bug whereby send returns WSAENOBUFS. * The workaround we use is to retry the send. If we have a * large buffer to send (>2k) then we retry with a maximum of * 2k buffer. If we hit the issue with <=2k buffer then we backoff * for 1 second and retry again. We repeat this up to a reasonable * limit before bailing out and throwing an exception. In load * conditions we've observed that the send will succeed after 2-3 * attempts but this depends on network buffers associated with * other sockets draining. */ if (WSAGetLastError() == WSAENOBUFS) { if (llen > MAX_BUFFER_LEN) { buflen = MAX_BUFFER_LEN; chunkLen = MAX_BUFFER_LEN; llen = MAX_BUFFER_LEN; continue; } if (retry >= 30) { JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException", "No buffer space available - exhausted attempts to queue buffer"); if (bufP != BUF) { free(bufP); } return; } Sleep(1000); retry++; continue; } /* * Send failed - can be caused by close or write error. */ if (WSAGetLastError() == WSAENOTSOCK) { JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException", "Socket closed"); } else { NET_ThrowCurrent(env, "socket write error"); } if (bufP != BUF) { free(bufP); } return; } len -= chunkLen; off += chunkLen; } if (bufP != BUF) { free(bufP); } }
TheTypoMaster/Scaper
openjdk/jdk/src/windows/native/java/net/SocketOutputStream.c
C
gpl-2.0
5,793
define("jquery-plugin/cookie/1.3/cookie", ["$"], function (require, exports, module) { var jQuery = require('$'); /*! * jQuery Cookie Plugin v1.3 * https://github.com/carhartl/jquery-cookie * * Copyright 2011, Klaus Hartl * Dual licensed under the MIT or GPL Version 2 licenses. * http://www.opensource.org/licenses/mit-license.php * http://www.opensource.org/licenses/GPL-2.0 */ (function ($, document, undefined) { var pluses = /\+/g; function raw(s) { return s; } function decoded(s) { return decodeURIComponent(s.replace(pluses, ' ')); } var config = $.cookie = function (key, value, options) { // write if (value !== undefined) { options = $.extend({}, config.defaults, options); if (value === null) { options.expires = -1; } if (typeof options.expires === 'number') { var days = options.expires, t = options.expires = new Date(); t.setDate(t.getDate() + days); } value = config.json ? JSON.stringify(value) : String(value); return (document.cookie = [ encodeURIComponent(key), '=', config.raw ? value : encodeURIComponent(value), options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE options.path ? '; path=' + options.path : '', options.domain ? '; domain=' + options.domain : '', options.secure ? '; secure' : '' ].join('')); } // read var decode = config.raw ? raw : decoded; var cookies = document.cookie.split('; '); for (var i = 0, l = cookies.length; i < l; i++) { var parts = cookies[i].split('='); if (decode(parts.shift()) === key) { var cookie = decode(parts.join('=')); return config.json ? JSON.parse(cookie) : cookie; } } return null; }; config.defaults = {}; $.removeCookie = function (key, options) { if ($.cookie(key) !== null) { $.cookie(key, null, options); return true; } return false; }; })(jQuery, document); })
huhao1989/Phenom
sea-modules/jquery-plugin/cookie/1.3/cookie-debug.js
JavaScript
gpl-2.0
2,540
require 'sinatra/content_for' require 'sinatra/json' class AuthenticationController < ApplicationController helpers Sinatra::ContentFor before do if /\/logout/.match(request.path).nil? redirect '/' if authorized? end end get '/login' do erb :login end post '/login' do username, password = params['username'], params['password'] user = User.find_by(username: username) if not user.nil? and user.check_password(password) session['user'] = user json :success => true, :message => t('login.messages.success') else json :success => false, :message => t('login.messages.error') end end get '/logout' do logout! redirect to('/login') end end
veskoy/Invoicer
app/routes/authentication_controller.rb
Ruby
gpl-2.0
724
ionic-app ========= An hybrid app built out of ionicframework
vivekchand/ionic-app
README.md
Markdown
gpl-2.0
63
/* Driver template for the LEMON parser generator. ** The author disclaims copyright to this source code. */ /* First off, code is include which follows the "include" declaration ** in the input file. */ #include <stdio.h> #line 5 "./configparser.y" #include <assert.h> #include <stdio.h> #include <string.h> #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "configfile.h" #include "buffer.h" #include "array.h" static void configparser_push(config_t *ctx, data_config *dc, int isnew) { if (isnew) { dc->context_ndx = ctx->all_configs->used; assert(dc->context_ndx > ctx->current->context_ndx); array_insert_unique(ctx->all_configs, (data_unset *)dc); dc->parent = ctx->current; array_insert_unique(dc->parent->childs, (data_unset *)dc); } array_insert_unique(ctx->configs_stack, (data_unset *)ctx->current); ctx->current = dc; } static data_config *configparser_pop(config_t *ctx) { data_config *old = ctx->current; ctx->current = (data_config *) array_pop(ctx->configs_stack); return old; } /* return a copied variable */ static data_unset *configparser_get_variable(config_t *ctx, const buffer *key) { data_unset *du; data_config *dc; #if 0 fprintf(stderr, "get var %s\n", key->ptr); #endif for (dc = ctx->current; dc; dc = dc->parent) { #if 0 fprintf(stderr, "get var on block: %s\n", dc->key->ptr); array_print(dc->value, 0); #endif if (NULL != (du = array_get_element(dc->value, key->ptr))) { return du->copy(du); } } return NULL; } /* op1 is to be eat/return by this function, op1->key is not cared op2 is left untouch, unreferenced */ data_unset *configparser_merge_data(data_unset *op1, const data_unset *op2) { /* type mismatch */ if (op1->type != op2->type) { if (op1->type == TYPE_STRING && op2->type == TYPE_INTEGER) { data_string *ds = (data_string *)op1; buffer_append_long(ds->value, ((data_integer*)op2)->value); return op1; } else if (op1->type == TYPE_INTEGER && op2->type == TYPE_STRING) { data_string *ds = data_string_init(); buffer_append_long(ds->value, ((data_integer*)op1)->value); buffer_append_string_buffer(ds->value, ((data_string*)op2)->value); op1->free(op1); return (data_unset *)ds; } else { fprintf(stderr, "data type mismatch, cannot be merge\n"); op1->free(op1); return NULL; } } switch (op1->type) { case TYPE_STRING: buffer_append_string_buffer(((data_string *)op1)->value, ((data_string *)op2)->value); break; case TYPE_INTEGER: ((data_integer *)op1)->value += ((data_integer *)op2)->value; break; case TYPE_ARRAY: { array *dst = ((data_array *)op1)->value; array *src = ((data_array *)op2)->value; data_unset *du; size_t i; for (i = 0; i < src->used; i ++) { du = (data_unset *)src->data[i]; if (du) { array_insert_unique(dst, du->copy(du)); } } break; default: assert(0); break; } } return op1; } #line 110 "configparser.c" /* Next is all token values, in a form suitable for use by makeheaders. ** This section will be null unless lemon is run with the -m switch. */ /* ** These constants (all generated automatically by the parser generator) ** specify the various kinds of tokens (terminals) that the parser ** understands. ** ** Each symbol here is a terminal symbol in the grammar. */ /* Make sure the INTERFACE macro is defined. */ #ifndef INTERFACE # define INTERFACE 1 #endif /* The next thing included is series of defines which control ** various aspects of the generated parser. ** YYCODETYPE is the data type used for storing terminal ** and nonterminal numbers. "unsigned char" is ** used if there are fewer than 250 terminals ** and nonterminals. "int" is used otherwise. ** YYNOCODE is a number of type YYCODETYPE which corresponds ** to no legal terminal or nonterminal number. This ** number is used to fill in empty slots of the hash ** table. ** YYFALLBACK If defined, this indicates that one or more tokens ** have fall-back values which should be used if the ** original value of the token will not parse. ** YYACTIONTYPE is the data type used for storing terminal ** and nonterminal numbers. "unsigned char" is ** used if there are fewer than 250 rules and ** states combined. "int" is used otherwise. ** configparserTOKENTYPE is the data type used for minor tokens given ** directly to the parser from the tokenizer. ** YYMINORTYPE is the data type used for all minor tokens. ** This is typically a union of many types, one of ** which is configparserTOKENTYPE. The entry in the union ** for base tokens is called "yy0". ** YYSTACKDEPTH is the maximum depth of the parser's stack. ** configparserARG_SDECL A static variable declaration for the %extra_argument ** configparserARG_PDECL A parameter declaration for the %extra_argument ** configparserARG_STORE Code to store %extra_argument into yypParser ** configparserARG_FETCH Code to extract %extra_argument from yypParser ** YYNSTATE the combined number of states. ** YYNRULE the number of rules in the grammar ** YYERRORSYMBOL is the code number of the error symbol. If not ** defined, then do no error processing. */ /*  */ #define YYCODETYPE unsigned char #define YYNOCODE 48 #define YYACTIONTYPE unsigned char #define configparserTOKENTYPE buffer * typedef union { configparserTOKENTYPE yy0; config_cond_t yy27; array * yy40; data_unset * yy41; buffer * yy43; data_config * yy78; int yy95; } YYMINORTYPE; #define YYSTACKDEPTH 100 #define configparserARG_SDECL config_t *ctx; #define configparserARG_PDECL ,config_t *ctx #define configparserARG_FETCH config_t *ctx = yypParser->ctx #define configparserARG_STORE yypParser->ctx = ctx #define YYNSTATE 63 #define YYNRULE 40 #define YYERRORSYMBOL 26 #define YYERRSYMDT yy95 #define YY_NO_ACTION (YYNSTATE+YYNRULE+2) #define YY_ACCEPT_ACTION (YYNSTATE+YYNRULE+1) #define YY_ERROR_ACTION (YYNSTATE+YYNRULE) /* Next are that tables used to determine what action to take based on the ** current state and lookahead token. These tables are used to implement ** functions that take a state number and lookahead value and return an ** action integer. ** ** Suppose the action integer is N. Then the action is determined as ** follows ** ** 0 <= N < YYNSTATE Shift N. That is, push the lookahead ** token onto the stack and goto state N. ** ** YYNSTATE <= N < YYNSTATE+YYNRULE Reduce by rule N-YYNSTATE. ** ** N == YYNSTATE+YYNRULE A syntax error has occurred. ** ** N == YYNSTATE+YYNRULE+1 The parser accepts its input. ** ** N == YYNSTATE+YYNRULE+2 No such action. Denotes unused ** slots in the yy_action[] table. ** ** The action table is constructed as a single large table named yy_action[]. ** Given state S and lookahead X, the action is computed as ** ** yy_action[ yy_shift_ofst[S] + X ] ** ** If the index value yy_shift_ofst[S]+X is out of range or if the value ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S] ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table ** and that yy_default[S] should be used instead. ** ** The formula above is for computing the action when the lookahead is ** a terminal symbol. If the lookahead is a non-terminal (as occurs after ** a reduce action) then the yy_reduce_ofst[] array is used in place of ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of ** YY_SHIFT_USE_DFLT. ** ** The following are the tables generated in this section: ** ** yy_action[] A single table containing all actions. ** yy_lookahead[] A table containing the lookahead for each entry in ** yy_action. Used to detect hash collisions. ** yy_shift_ofst[] For each state, the offset into yy_action for ** shifting terminals. ** yy_reduce_ofst[] For each state, the offset into yy_action for ** shifting non-terminals after a reduce. ** yy_default[] Default action for each state. */ static YYACTIONTYPE yy_action[] = { /* 0 */ 2, 3, 4, 5, 13, 14, 63, 15, 7, 45, /* 10 */ 20, 88, 16, 46, 28, 49, 41, 10, 40, 25, /* 20 */ 22, 50, 46, 8, 15, 104, 1, 20, 28, 18, /* 30 */ 58, 60, 6, 25, 22, 40, 47, 62, 11, 46, /* 40 */ 20, 9, 23, 24, 26, 29, 89, 58, 60, 10, /* 50 */ 17, 38, 28, 27, 37, 19, 30, 25, 22, 34, /* 60 */ 15, 100, 20, 20, 23, 24, 26, 12, 19, 31, /* 70 */ 32, 40, 19, 44, 43, 46, 95, 35, 90, 89, /* 80 */ 28, 49, 42, 58, 60, 25, 22, 59, 28, 27, /* 90 */ 33, 48, 52, 25, 22, 34, 28, 49, 51, 28, /* 100 */ 36, 25, 22, 61, 25, 22, 89, 28, 39, 89, /* 110 */ 89, 89, 25, 22, 54, 55, 56, 57, 89, 28, /* 120 */ 53, 21, 89, 89, 25, 22, 25, 22, }; static YYCODETYPE yy_lookahead[] = { /* 0 */ 29, 30, 31, 32, 33, 34, 0, 1, 44, 38, /* 10 */ 4, 15, 41, 16, 35, 36, 45, 46, 12, 40, /* 20 */ 41, 42, 16, 15, 1, 27, 28, 4, 35, 36, /* 30 */ 24, 25, 1, 40, 41, 12, 17, 14, 13, 16, /* 40 */ 4, 38, 6, 7, 8, 9, 15, 24, 25, 46, /* 50 */ 2, 3, 35, 36, 37, 5, 39, 40, 41, 42, /* 60 */ 1, 11, 4, 4, 6, 7, 8, 28, 5, 9, /* 70 */ 10, 12, 5, 14, 28, 16, 13, 11, 13, 47, /* 80 */ 35, 36, 13, 24, 25, 40, 41, 42, 35, 36, /* 90 */ 37, 18, 43, 40, 41, 42, 35, 36, 19, 35, /* 100 */ 36, 40, 41, 42, 40, 41, 47, 35, 36, 47, /* 110 */ 47, 47, 40, 41, 20, 21, 22, 23, 47, 35, /* 120 */ 36, 35, 47, 47, 40, 41, 40, 41, }; #define YY_SHIFT_USE_DFLT (-5) static signed char yy_shift_ofst[] = { /* 0 */ -5, 6, -5, -5, -5, 31, -4, 8, -3, -5, /* 10 */ 25, -5, 23, -5, -5, -5, 48, 58, 67, 58, /* 20 */ -5, -5, -5, -5, -5, -5, 36, 50, -5, -5, /* 30 */ 60, -5, 58, -5, 66, 58, 67, -5, 58, 67, /* 40 */ 65, 69, -5, 59, -5, -5, 19, 73, 58, 67, /* 50 */ 79, 94, 58, 63, -5, -5, -5, -5, 58, -5, /* 60 */ 58, -5, -5, }; #define YY_REDUCE_USE_DFLT (-37) static signed char yy_reduce_ofst[] = { /* 0 */ -2, -29, -37, -37, -37, -36, -37, -37, 3, -37, /* 10 */ -37, 39, -29, -37, -37, -37, -37, -7, -37, 86, /* 20 */ -37, -37, -37, -37, -37, -37, 17, -37, -37, -37, /* 30 */ -37, -37, 53, -37, -37, 64, -37, -37, 72, -37, /* 40 */ -37, -37, 46, -29, -37, -37, -37, -37, -21, -37, /* 50 */ -37, 49, 84, -37, -37, -37, -37, -37, 45, -37, /* 60 */ 61, -37, -37, }; static YYACTIONTYPE yy_default[] = { /* 0 */ 65, 103, 64, 66, 67, 103, 68, 103, 103, 92, /* 10 */ 103, 65, 103, 69, 70, 71, 103, 103, 72, 103, /* 20 */ 74, 75, 77, 78, 79, 80, 103, 86, 76, 81, /* 30 */ 103, 82, 84, 83, 103, 103, 87, 85, 103, 73, /* 40 */ 103, 103, 65, 103, 91, 93, 103, 103, 103, 100, /* 50 */ 103, 103, 103, 103, 96, 97, 98, 99, 103, 101, /* 60 */ 103, 102, 94, }; #define YY_SZ_ACTTAB (sizeof(yy_action)/sizeof(yy_action[0])) /* The next table maps tokens into fallback tokens. If a construct ** like the following: ** ** %fallback ID X Y Z. ** ** appears in the grammer, then ID becomes a fallback token for X, Y, ** and Z. Whenever one of the tokens X, Y, or Z is input to the parser ** but it does not parse, the type of the token is changed to ID and ** the parse is retried before an error is thrown. */ #ifdef YYFALLBACK static const YYCODETYPE yyFallback[] = { }; #endif /* YYFALLBACK */ /* The following structure represents a single element of the ** parser's stack. Information stored includes: ** ** + The state number for the parser at this level of the stack. ** ** + The value of the token stored at this level of the stack. ** (In other words, the "major" token.) ** ** + The semantic value stored at this level of the stack. This is ** the information used by the action routines in the grammar. ** It is sometimes called the "minor" token. */ struct yyStackEntry { int stateno; /* The state-number */ int major; /* The major token value. This is the code ** number for the token at this stack level */ YYMINORTYPE minor; /* The user-supplied minor token value. This ** is the value of the token */ }; typedef struct yyStackEntry yyStackEntry; /* The state of the parser is completely contained in an instance of ** the following structure */ struct yyParser { int yyidx; /* Index of top element in stack */ int yyerrcnt; /* Shifts left before out of the error */ configparserARG_SDECL /* A place to hold %extra_argument */ yyStackEntry yystack[YYSTACKDEPTH]; /* The parser's stack */ }; typedef struct yyParser yyParser; #ifndef NDEBUG #include <stdio.h> static FILE *yyTraceFILE = 0; static char *yyTracePrompt = 0; #endif /* NDEBUG */ #ifndef NDEBUG /* ** Turn parser tracing on by giving a stream to which to write the trace ** and a prompt to preface each trace message. Tracing is turned off ** by making either argument NULL ** ** Inputs: ** <ul> ** <li> A FILE* to which trace output should be written. ** If NULL, then tracing is turned off. ** <li> A prefix string written at the beginning of every ** line of trace output. If NULL, then tracing is ** turned off. ** </ul> ** ** Outputs: ** None. */ void configparserTrace(FILE *TraceFILE, char *zTracePrompt){ yyTraceFILE = TraceFILE; yyTracePrompt = zTracePrompt; if( yyTraceFILE==0 ) yyTracePrompt = 0; else if( yyTracePrompt==0 ) yyTraceFILE = 0; } #endif /* NDEBUG */ #ifndef NDEBUG /* For tracing shifts, the names of all terminals and nonterminals ** are required. The following table supplies these names */ static const char *yyTokenName[] = { "$", "EOL", "ASSIGN", "APPEND", "LKEY", "PLUS", "STRING", "INTEGER", "LPARAN", "RPARAN", "COMMA", "ARRAY_ASSIGN", "GLOBAL", "LCURLY", "RCURLY", "ELSE", "DOLLAR", "SRVVARNAME", "LBRACKET", "RBRACKET", "EQ", "MATCH", "NE", "NOMATCH", "INCLUDE", "INCLUDE_SHELL", "error", "input", "metalines", "metaline", "varline", "global", "condlines", "include", "include_shell", "value", "expression", "aelement", "condline", "aelements", "array", "key", "stringop", "cond", "eols", "globalstart", "context", }; #endif /* NDEBUG */ #ifndef NDEBUG /* For tracing reduce actions, the names of all rules are required. */ static const char *yyRuleName[] = { /* 0 */ "input ::= metalines", /* 1 */ "metalines ::= metalines metaline", /* 2 */ "metalines ::=", /* 3 */ "metaline ::= varline", /* 4 */ "metaline ::= global", /* 5 */ "metaline ::= condlines EOL", /* 6 */ "metaline ::= include", /* 7 */ "metaline ::= include_shell", /* 8 */ "metaline ::= EOL", /* 9 */ "varline ::= key ASSIGN expression", /* 10 */ "varline ::= key APPEND expression", /* 11 */ "key ::= LKEY", /* 12 */ "expression ::= expression PLUS value", /* 13 */ "expression ::= value", /* 14 */ "value ::= key", /* 15 */ "value ::= STRING", /* 16 */ "value ::= INTEGER", /* 17 */ "value ::= array", /* 18 */ "array ::= LPARAN RPARAN", /* 19 */ "array ::= LPARAN aelements RPARAN", /* 20 */ "aelements ::= aelements COMMA aelement", /* 21 */ "aelements ::= aelements COMMA", /* 22 */ "aelements ::= aelement", /* 23 */ "aelement ::= expression", /* 24 */ "aelement ::= stringop ARRAY_ASSIGN expression", /* 25 */ "eols ::= EOL", /* 26 */ "eols ::=", /* 27 */ "globalstart ::= GLOBAL", /* 28 */ "global ::= globalstart LCURLY metalines RCURLY", /* 29 */ "condlines ::= condlines eols ELSE condline", /* 30 */ "condlines ::= condline", /* 31 */ "condline ::= context LCURLY metalines RCURLY", /* 32 */ "context ::= DOLLAR SRVVARNAME LBRACKET stringop RBRACKET cond expression", /* 33 */ "cond ::= EQ", /* 34 */ "cond ::= MATCH", /* 35 */ "cond ::= NE", /* 36 */ "cond ::= NOMATCH", /* 37 */ "stringop ::= expression", /* 38 */ "include ::= INCLUDE stringop", /* 39 */ "include_shell ::= INCLUDE_SHELL stringop", }; #endif /* NDEBUG */ /* ** This function returns the symbolic name associated with a token ** value. */ const char *configparserTokenName(int tokenType){ #ifndef NDEBUG if( tokenType>0 && tokenType<(sizeof(yyTokenName)/sizeof(yyTokenName[0])) ){ return yyTokenName[tokenType]; }else{ return "Unknown"; } #else return ""; #endif } /* ** This function allocates a new parser. ** The only argument is a pointer to a function which works like ** malloc. ** ** Inputs: ** A pointer to the function used to allocate memory. ** ** Outputs: ** A pointer to a parser. This pointer is used in subsequent calls ** to configparser and configparserFree. */ void *configparserAlloc(void *(*mallocProc)(size_t)){ yyParser *pParser; pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) ); if( pParser ){ pParser->yyidx = -1; } return pParser; } /* The following function deletes the value associated with a ** symbol. The symbol can be either a terminal or nonterminal. ** "yymajor" is the symbol code, and "yypminor" is a pointer to ** the value. */ static void yy_destructor(YYCODETYPE yymajor, YYMINORTYPE *yypminor){ switch( yymajor ){ /* Here is inserted the actions which take place when a ** terminal or non-terminal is destroyed. This can happen ** when the symbol is popped from the stack during a ** reduce or during error processing or when a parser is ** being destroyed before it is finished parsing. ** ** Note: during a reduce, the only symbols destroyed are those ** which appear on the RHS of the rule, but which are not used ** inside the C code. */ case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: case 9: case 10: case 11: case 12: case 13: case 14: case 15: case 16: case 17: case 18: case 19: case 20: case 21: case 22: case 23: case 24: case 25: #line 142 "./configparser.y" { buffer_free((yypminor->yy0)); } #line 518 "configparser.c" break; case 35: #line 133 "./configparser.y" { (yypminor->yy41)->free((yypminor->yy41)); } #line 523 "configparser.c" break; case 36: #line 134 "./configparser.y" { (yypminor->yy41)->free((yypminor->yy41)); } #line 528 "configparser.c" break; case 37: #line 135 "./configparser.y" { (yypminor->yy41)->free((yypminor->yy41)); } #line 533 "configparser.c" break; case 39: #line 136 "./configparser.y" { array_free((yypminor->yy40)); } #line 538 "configparser.c" break; case 40: #line 137 "./configparser.y" { array_free((yypminor->yy40)); } #line 543 "configparser.c" break; case 41: #line 138 "./configparser.y" { buffer_free((yypminor->yy43)); } #line 548 "configparser.c" break; case 42: #line 139 "./configparser.y" { buffer_free((yypminor->yy43)); } #line 553 "configparser.c" break; default: break; /* If no destructor action specified: do nothing */ } } /* ** Pop the parser's stack once. ** ** If there is a destructor routine associated with the token which ** is popped from the stack, then call it. ** ** Return the major token number for the symbol popped. */ static int yy_pop_parser_stack(yyParser *pParser){ YYCODETYPE yymajor; yyStackEntry *yytos = &pParser->yystack[pParser->yyidx]; if( pParser->yyidx<0 ) return 0; #ifndef NDEBUG if( yyTraceFILE && pParser->yyidx>=0 ){ fprintf(yyTraceFILE,"%sPopping %s\n", yyTracePrompt, yyTokenName[yytos->major]); } #endif yymajor = yytos->major; yy_destructor( yymajor, &yytos->minor); pParser->yyidx--; return yymajor; } /* ** Deallocate and destroy a parser. Destructors are all called for ** all stack elements before shutting the parser down. ** ** Inputs: ** <ul> ** <li> A pointer to the parser. This should be a pointer ** obtained from configparserAlloc. ** <li> A pointer to a function used to reclaim memory obtained ** from malloc. ** </ul> */ void configparserFree( void *p, /* The parser to be deleted */ void (*freeProc)(void*) /* Function used to reclaim memory */ ){ yyParser *pParser = (yyParser*)p; if( pParser==0 ) return; while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser); (*freeProc)((void*)pParser); } /* ** Find the appropriate action for a parser given the terminal ** look-ahead token iLookAhead. ** ** If the look-ahead token is YYNOCODE, then check to see if the action is ** independent of the look-ahead. If it is, return the action, otherwise ** return YY_NO_ACTION. */ static int yy_find_shift_action( yyParser *pParser, /* The parser */ int iLookAhead /* The look-ahead token */ ){ int i; int stateno = pParser->yystack[pParser->yyidx].stateno; /* if( pParser->yyidx<0 ) return YY_NO_ACTION; */ i = yy_shift_ofst[stateno]; if( i==YY_SHIFT_USE_DFLT ){ return yy_default[stateno]; } if( iLookAhead==YYNOCODE ){ return YY_NO_ACTION; } i += iLookAhead; if( i<0 || i>=YY_SZ_ACTTAB || yy_lookahead[i]!=iLookAhead ){ #ifdef YYFALLBACK int iFallback; /* Fallback token */ if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0]) && (iFallback = yyFallback[iLookAhead])!=0 ){ #ifndef NDEBUG if( yyTraceFILE ){ fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n", yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]); } #endif return yy_find_shift_action(pParser, iFallback); } #endif return yy_default[stateno]; }else{ return yy_action[i]; } } /* ** Find the appropriate action for a parser given the non-terminal ** look-ahead token iLookAhead. ** ** If the look-ahead token is YYNOCODE, then check to see if the action is ** independent of the look-ahead. If it is, return the action, otherwise ** return YY_NO_ACTION. */ static int yy_find_reduce_action( yyParser *pParser, /* The parser */ int iLookAhead /* The look-ahead token */ ){ int i; int stateno = pParser->yystack[pParser->yyidx].stateno; i = yy_reduce_ofst[stateno]; if( i==YY_REDUCE_USE_DFLT ){ return yy_default[stateno]; } if( iLookAhead==YYNOCODE ){ return YY_NO_ACTION; } i += iLookAhead; if( i<0 || i>=YY_SZ_ACTTAB || yy_lookahead[i]!=iLookAhead ){ return yy_default[stateno]; }else{ return yy_action[i]; } } /* ** Perform a shift action. */ static void yy_shift( yyParser *yypParser, /* The parser to be shifted */ int yyNewState, /* The new state to shift in */ int yyMajor, /* The major token to shift in */ YYMINORTYPE *yypMinor /* Pointer ot the minor token to shift in */ ){ yyStackEntry *yytos; yypParser->yyidx++; if( yypParser->yyidx>=YYSTACKDEPTH ){ configparserARG_FETCH; yypParser->yyidx--; #ifndef NDEBUG if( yyTraceFILE ){ fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt); } #endif while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser); /* Here code is inserted which will execute if the parser ** stack every overflows */ configparserARG_STORE; /* Suppress warning about unused %extra_argument var */ return; } yytos = &yypParser->yystack[yypParser->yyidx]; yytos->stateno = yyNewState; yytos->major = yyMajor; yytos->minor = *yypMinor; #ifndef NDEBUG if( yyTraceFILE && yypParser->yyidx>0 ){ int i; fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState); fprintf(yyTraceFILE,"%sStack:",yyTracePrompt); for(i=1; i<=yypParser->yyidx; i++) fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]); fprintf(yyTraceFILE,"\n"); } #endif } /* The following table contains information about every rule that ** is used during the reduce. */ static struct { YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */ unsigned char nrhs; /* Number of right-hand side symbols in the rule */ } yyRuleInfo[] = { { 27, 1 }, { 28, 2 }, { 28, 0 }, { 29, 1 }, { 29, 1 }, { 29, 2 }, { 29, 1 }, { 29, 1 }, { 29, 1 }, { 30, 3 }, { 30, 3 }, { 41, 1 }, { 36, 3 }, { 36, 1 }, { 35, 1 }, { 35, 1 }, { 35, 1 }, { 35, 1 }, { 40, 2 }, { 40, 3 }, { 39, 3 }, { 39, 2 }, { 39, 1 }, { 37, 1 }, { 37, 3 }, { 44, 1 }, { 44, 0 }, { 45, 1 }, { 31, 4 }, { 32, 4 }, { 32, 1 }, { 38, 4 }, { 46, 7 }, { 43, 1 }, { 43, 1 }, { 43, 1 }, { 43, 1 }, { 42, 1 }, { 33, 2 }, { 34, 2 }, }; static void yy_accept(yyParser*); /* Forward Declaration */ /* ** Perform a reduce action and the shift that must immediately ** follow the reduce. */ static void yy_reduce( yyParser *yypParser, /* The parser */ int yyruleno /* Number of the rule by which to reduce */ ){ int yygoto; /* The next state */ int yyact; /* The next action */ YYMINORTYPE yygotominor; /* The LHS of the rule reduced */ yyStackEntry *yymsp; /* The top of the parser's stack */ int yysize; /* Amount to pop the stack */ configparserARG_FETCH; yymsp = &yypParser->yystack[yypParser->yyidx]; #ifndef NDEBUG if( yyTraceFILE && yyruleno>=0 && yyruleno<sizeof(yyRuleName)/sizeof(yyRuleName[0]) ){ fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt, yyRuleName[yyruleno]); } #endif /* NDEBUG */ switch( yyruleno ){ /* Beginning here are the reduction cases. A typical example ** follows: ** case 0: ** #line <lineno> <grammarfile> ** { ... } // User supplied code ** #line <lineno> <thisfile> ** break; */ case 0: /* No destructor defined for metalines */ break; case 1: /* No destructor defined for metalines */ /* No destructor defined for metaline */ break; case 2: break; case 3: /* No destructor defined for varline */ break; case 4: /* No destructor defined for global */ break; case 5: #line 116 "./configparser.y" { yymsp[-1].minor.yy78 = NULL; } #line 823 "configparser.c" yy_destructor(1,&yymsp[0].minor); break; case 6: /* No destructor defined for include */ break; case 7: /* No destructor defined for include_shell */ break; case 8: yy_destructor(1,&yymsp[0].minor); break; case 9: #line 144 "./configparser.y" { buffer_copy_string_buffer(yymsp[0].minor.yy41->key, yymsp[-2].minor.yy43); if (strncmp(yymsp[-2].minor.yy43->ptr, "env.", sizeof("env.") - 1) == 0) { fprintf(stderr, "Setting env variable is not supported in conditional %d %s: %s\n", ctx->current->context_ndx, ctx->current->key->ptr, yymsp[-2].minor.yy43->ptr); ctx->ok = 0; } else if (NULL == array_get_element(ctx->current->value, yymsp[0].minor.yy41->key->ptr)) { array_insert_unique(ctx->current->value, yymsp[0].minor.yy41); yymsp[0].minor.yy41 = NULL; } else { fprintf(stderr, "Duplicate config variable in conditional %d %s: %s\n", ctx->current->context_ndx, ctx->current->key->ptr, yymsp[0].minor.yy41->key->ptr); ctx->ok = 0; yymsp[0].minor.yy41->free(yymsp[0].minor.yy41); yymsp[0].minor.yy41 = NULL; } buffer_free(yymsp[-2].minor.yy43); yymsp[-2].minor.yy43 = NULL; } #line 858 "configparser.c" yy_destructor(2,&yymsp[-1].minor); break; case 10: #line 166 "./configparser.y" { array *vars = ctx->current->value; data_unset *du; if (strncmp(yymsp[-2].minor.yy43->ptr, "env.", sizeof("env.") - 1) == 0) { fprintf(stderr, "Appending env variable is not supported in conditional %d %s: %s\n", ctx->current->context_ndx, ctx->current->key->ptr, yymsp[-2].minor.yy43->ptr); ctx->ok = 0; } else if (NULL != (du = array_get_element(vars, yymsp[-2].minor.yy43->ptr))) { /* exists in current block */ du = configparser_merge_data(du, yymsp[0].minor.yy41); if (NULL == du) { ctx->ok = 0; } else { buffer_copy_string_buffer(du->key, yymsp[-2].minor.yy43); array_replace(vars, du); } yymsp[0].minor.yy41->free(yymsp[0].minor.yy41); } else if (NULL != (du = configparser_get_variable(ctx, yymsp[-2].minor.yy43))) { du = configparser_merge_data(du, yymsp[0].minor.yy41); if (NULL == du) { ctx->ok = 0; } else { buffer_copy_string_buffer(du->key, yymsp[-2].minor.yy43); array_insert_unique(ctx->current->value, du); } yymsp[0].minor.yy41->free(yymsp[0].minor.yy41); } else { buffer_copy_string_buffer(yymsp[0].minor.yy41->key, yymsp[-2].minor.yy43); array_insert_unique(ctx->current->value, yymsp[0].minor.yy41); } buffer_free(yymsp[-2].minor.yy43); yymsp[-2].minor.yy43 = NULL; yymsp[0].minor.yy41 = NULL; } #line 901 "configparser.c" yy_destructor(3,&yymsp[-1].minor); break; case 11: #line 205 "./configparser.y" { if (strchr(yymsp[0].minor.yy0->ptr, '.') == NULL) { yygotominor.yy43 = buffer_init_string("var."); buffer_append_string_buffer(yygotominor.yy43, yymsp[0].minor.yy0); buffer_free(yymsp[0].minor.yy0); yymsp[0].minor.yy0 = NULL; } else { yygotominor.yy43 = yymsp[0].minor.yy0; yymsp[0].minor.yy0 = NULL; } } #line 917 "configparser.c" break; case 12: #line 217 "./configparser.y" { yygotominor.yy41 = configparser_merge_data(yymsp[-2].minor.yy41, yymsp[0].minor.yy41); if (NULL == yygotominor.yy41) { ctx->ok = 0; } yymsp[-2].minor.yy41 = NULL; yymsp[0].minor.yy41->free(yymsp[0].minor.yy41); yymsp[0].minor.yy41 = NULL; } #line 930 "configparser.c" yy_destructor(5,&yymsp[-1].minor); break; case 13: #line 227 "./configparser.y" { yygotominor.yy41 = yymsp[0].minor.yy41; yymsp[0].minor.yy41 = NULL; } #line 939 "configparser.c" break; case 14: #line 232 "./configparser.y" { if (strncmp(yymsp[0].minor.yy43->ptr, "env.", sizeof("env.") - 1) == 0) { char *env; if (NULL != (env = getenv(yymsp[0].minor.yy43->ptr + 4))) { data_string *ds; ds = data_string_init(); buffer_append_string(ds->value, env); yygotominor.yy41 = (data_unset *)ds; } else { fprintf(stderr, "Undefined env variable: %s\n", yymsp[0].minor.yy43->ptr + 4); ctx->ok = 0; } } else if (NULL == (yygotominor.yy41 = configparser_get_variable(ctx, yymsp[0].minor.yy43))) { fprintf(stderr, "Undefined config variable: %s\n", yymsp[0].minor.yy43->ptr); ctx->ok = 0; } if (!yygotominor.yy41) { /* make a dummy so it won't crash */ yygotominor.yy41 = (data_unset *)data_string_init(); } buffer_free(yymsp[0].minor.yy43); yymsp[0].minor.yy43 = NULL; } #line 968 "configparser.c" break; case 15: #line 258 "./configparser.y" { yygotominor.yy41 = (data_unset *)data_string_init(); buffer_copy_string_buffer(((data_string *)(yygotominor.yy41))->value, yymsp[0].minor.yy0); buffer_free(yymsp[0].minor.yy0); yymsp[0].minor.yy0 = NULL; } #line 978 "configparser.c" break; case 16: #line 265 "./configparser.y" { yygotominor.yy41 = (data_unset *)data_integer_init(); ((data_integer *)(yygotominor.yy41))->value = strtol(yymsp[0].minor.yy0->ptr, NULL, 10); buffer_free(yymsp[0].minor.yy0); yymsp[0].minor.yy0 = NULL; } #line 988 "configparser.c" break; case 17: #line 271 "./configparser.y" { yygotominor.yy41 = (data_unset *)data_array_init(); array_free(((data_array *)(yygotominor.yy41))->value); ((data_array *)(yygotominor.yy41))->value = yymsp[0].minor.yy40; yymsp[0].minor.yy40 = NULL; } #line 998 "configparser.c" break; case 18: #line 277 "./configparser.y" { yygotominor.yy40 = array_init(); } #line 1005 "configparser.c" yy_destructor(8,&yymsp[-1].minor); yy_destructor(9,&yymsp[0].minor); break; case 19: #line 280 "./configparser.y" { yygotominor.yy40 = yymsp[-1].minor.yy40; yymsp[-1].minor.yy40 = NULL; } #line 1015 "configparser.c" yy_destructor(8,&yymsp[-2].minor); yy_destructor(9,&yymsp[0].minor); break; case 20: #line 285 "./configparser.y" { if (buffer_is_empty(yymsp[0].minor.yy41->key) || NULL == array_get_element(yymsp[-2].minor.yy40, yymsp[0].minor.yy41->key->ptr)) { array_insert_unique(yymsp[-2].minor.yy40, yymsp[0].minor.yy41); yymsp[0].minor.yy41 = NULL; } else { fprintf(stderr, "Duplicate array-key: %s\n", yymsp[0].minor.yy41->key->ptr); ctx->ok = 0; yymsp[0].minor.yy41->free(yymsp[0].minor.yy41); yymsp[0].minor.yy41 = NULL; } yygotominor.yy40 = yymsp[-2].minor.yy40; yymsp[-2].minor.yy40 = NULL; } #line 1037 "configparser.c" yy_destructor(10,&yymsp[-1].minor); break; case 21: #line 302 "./configparser.y" { yygotominor.yy40 = yymsp[-1].minor.yy40; yymsp[-1].minor.yy40 = NULL; } #line 1046 "configparser.c" yy_destructor(10,&yymsp[0].minor); break; case 22: #line 307 "./configparser.y" { yygotominor.yy40 = array_init(); array_insert_unique(yygotominor.yy40, yymsp[0].minor.yy41); yymsp[0].minor.yy41 = NULL; } #line 1056 "configparser.c" break; case 23: #line 313 "./configparser.y" { yygotominor.yy41 = yymsp[0].minor.yy41; yymsp[0].minor.yy41 = NULL; } #line 1064 "configparser.c" break; case 24: #line 317 "./configparser.y" { buffer_copy_string_buffer(yymsp[0].minor.yy41->key, yymsp[-2].minor.yy43); buffer_free(yymsp[-2].minor.yy43); yymsp[-2].minor.yy43 = NULL; yygotominor.yy41 = yymsp[0].minor.yy41; yymsp[0].minor.yy41 = NULL; } #line 1076 "configparser.c" yy_destructor(11,&yymsp[-1].minor); break; case 25: yy_destructor(1,&yymsp[0].minor); break; case 26: break; case 27: #line 329 "./configparser.y" { data_config *dc; dc = (data_config *)array_get_element(ctx->srv->config_context, "global"); assert(dc); configparser_push(ctx, dc, 0); } #line 1092 "configparser.c" yy_destructor(12,&yymsp[0].minor); break; case 28: #line 336 "./configparser.y" { data_config *cur; cur = ctx->current; configparser_pop(ctx); assert(cur && ctx->current); yygotominor.yy0 = cur; } #line 1107 "configparser.c" /* No destructor defined for globalstart */ yy_destructor(13,&yymsp[-2].minor); /* No destructor defined for metalines */ yy_destructor(14,&yymsp[0].minor); break; case 29: #line 347 "./configparser.y" { assert(yymsp[-3].minor.yy78->context_ndx < yymsp[0].minor.yy78->context_ndx); yymsp[0].minor.yy78->prev = yymsp[-3].minor.yy78; yymsp[-3].minor.yy78->next = yymsp[0].minor.yy78; yygotominor.yy78 = yymsp[0].minor.yy78; yymsp[-3].minor.yy78 = NULL; yymsp[0].minor.yy78 = NULL; } #line 1123 "configparser.c" /* No destructor defined for eols */ yy_destructor(15,&yymsp[-1].minor); break; case 30: #line 356 "./configparser.y" { yygotominor.yy78 = yymsp[0].minor.yy78; yymsp[0].minor.yy78 = NULL; } #line 1133 "configparser.c" break; case 31: #line 361 "./configparser.y" { data_config *cur; cur = ctx->current; configparser_pop(ctx); assert(cur && ctx->current); yygotominor.yy78 = cur; } #line 1147 "configparser.c" /* No destructor defined for context */ yy_destructor(13,&yymsp[-2].minor); /* No destructor defined for metalines */ yy_destructor(14,&yymsp[0].minor); break; case 32: #line 372 "./configparser.y" { data_config *dc; buffer *b, *rvalue, *op; if (ctx->ok && yymsp[0].minor.yy41->type != TYPE_STRING) { fprintf(stderr, "rvalue must be string"); ctx->ok = 0; } switch(yymsp[-1].minor.yy27) { case CONFIG_COND_NE: op = buffer_init_string("!="); break; case CONFIG_COND_EQ: op = buffer_init_string("=="); break; case CONFIG_COND_NOMATCH: op = buffer_init_string("!~"); break; case CONFIG_COND_MATCH: op = buffer_init_string("=~"); break; default: assert(0); return; } b = buffer_init(); buffer_copy_string_buffer(b, ctx->current->key); buffer_append_string(b, "/"); buffer_append_string_buffer(b, yymsp[-5].minor.yy0); buffer_append_string_buffer(b, yymsp[-3].minor.yy43); buffer_append_string_buffer(b, op); rvalue = ((data_string*)yymsp[0].minor.yy41)->value; buffer_append_string_buffer(b, rvalue); if (NULL != (dc = (data_config *)array_get_element(ctx->all_configs, b->ptr))) { configparser_push(ctx, dc, 0); } else { struct { comp_key_t comp; char *comp_key; size_t len; } comps[] = { { COMP_SERVER_SOCKET, CONST_STR_LEN("SERVER[\"socket\"]" ) }, { COMP_HTTP_URL, CONST_STR_LEN("HTTP[\"url\"]" ) }, { COMP_HTTP_HOST, CONST_STR_LEN("HTTP[\"host\"]" ) }, { COMP_HTTP_REFERER, CONST_STR_LEN("HTTP[\"referer\"]" ) }, { COMP_HTTP_USERAGENT, CONST_STR_LEN("HTTP[\"useragent\"]" ) }, { COMP_HTTP_COOKIE, CONST_STR_LEN("HTTP[\"cookie\"]" ) }, { COMP_HTTP_REMOTEIP, CONST_STR_LEN("HTTP[\"remoteip\"]" ) }, { COMP_HTTP_QUERYSTRING, CONST_STR_LEN("HTTP[\"querystring\"]") }, { COMP_UNSET, NULL, 0 }, }; size_t i; dc = data_config_init(); buffer_copy_string_buffer(dc->key, b); buffer_copy_string_buffer(dc->op, op); buffer_copy_string_buffer(dc->comp_key, yymsp[-5].minor.yy0); buffer_append_string_len(dc->comp_key, CONST_STR_LEN("[\"")); buffer_append_string_buffer(dc->comp_key, yymsp[-3].minor.yy43); buffer_append_string_len(dc->comp_key, CONST_STR_LEN("\"]")); dc->cond = yymsp[-1].minor.yy27; for (i = 0; comps[i].comp_key; i ++) { if (buffer_is_equal_string( dc->comp_key, comps[i].comp_key, comps[i].len)) { dc->comp = comps[i].comp; break; } } if (COMP_UNSET == dc->comp) { fprintf(stderr, "error comp_key %s", dc->comp_key->ptr); ctx->ok = 0; } switch(yymsp[-1].minor.yy27) { case CONFIG_COND_NE: case CONFIG_COND_EQ: dc->string = buffer_init_buffer(rvalue); break; case CONFIG_COND_NOMATCH: case CONFIG_COND_MATCH: { #ifdef HAVE_PCRE_H const char *errptr; int erroff; if (NULL == (dc->regex = pcre_compile(rvalue->ptr, 0, &errptr, &erroff, NULL))) { dc->string = buffer_init_string(errptr); dc->cond = CONFIG_COND_UNSET; fprintf(stderr, "parsing regex failed: %s -> %s at offset %d\n", rvalue->ptr, errptr, erroff); ctx->ok = 0; } else if (NULL == (dc->regex_study = pcre_study(dc->regex, 0, &errptr)) && errptr != NULL) { fprintf(stderr, "studying regex failed: %s -> %s\n", rvalue->ptr, errptr); ctx->ok = 0; } else { dc->string = buffer_init_buffer(rvalue); } #else fprintf(stderr, "can't handle '$%s[%s] =~ ...' as you compiled without pcre support. \n" "(perhaps just a missing pcre-devel package ?) \n", yymsp[-5].minor.yy0->ptr, yymsp[-3].minor.yy43->ptr); ctx->ok = 0; #endif break; } default: fprintf(stderr, "unknown condition for $%s[%s]\n", yymsp[-5].minor.yy0->ptr, yymsp[-3].minor.yy43->ptr); ctx->ok = 0; break; } configparser_push(ctx, dc, 1); } buffer_free(b); buffer_free(op); buffer_free(yymsp[-5].minor.yy0); yymsp[-5].minor.yy0 = NULL; buffer_free(yymsp[-3].minor.yy43); yymsp[-3].minor.yy43 = NULL; yymsp[0].minor.yy41->free(yymsp[0].minor.yy41); yymsp[0].minor.yy41 = NULL; } #line 1290 "configparser.c" yy_destructor(16,&yymsp[-6].minor); yy_destructor(18,&yymsp[-4].minor); yy_destructor(19,&yymsp[-2].minor); break; case 33: #line 507 "./configparser.y" { yygotominor.yy27 = CONFIG_COND_EQ; } #line 1300 "configparser.c" yy_destructor(20,&yymsp[0].minor); break; case 34: #line 510 "./configparser.y" { yygotominor.yy27 = CONFIG_COND_MATCH; } #line 1308 "configparser.c" yy_destructor(21,&yymsp[0].minor); break; case 35: #line 513 "./configparser.y" { yygotominor.yy27 = CONFIG_COND_NE; } #line 1316 "configparser.c" yy_destructor(22,&yymsp[0].minor); break; case 36: #line 516 "./configparser.y" { yygotominor.yy27 = CONFIG_COND_NOMATCH; } #line 1324 "configparser.c" yy_destructor(23,&yymsp[0].minor); break; case 37: #line 520 "./configparser.y" { yygotominor.yy43 = NULL; if (ctx->ok) { if (yymsp[0].minor.yy41->type == TYPE_STRING) { yygotominor.yy43 = buffer_init_buffer(((data_string*)yymsp[0].minor.yy41)->value); } else if (yymsp[0].minor.yy41->type == TYPE_INTEGER) { yygotominor.yy43 = buffer_init(); buffer_copy_long(yygotominor.yy43, ((data_integer *)yymsp[0].minor.yy41)->value); } else { fprintf(stderr, "operand must be string"); ctx->ok = 0; } } yymsp[0].minor.yy41->free(yymsp[0].minor.yy41); yymsp[0].minor.yy41 = NULL; } #line 1345 "configparser.c" break; case 38: #line 537 "./configparser.y" { if (ctx->ok) { if (0 != config_parse_file(ctx->srv, ctx, yymsp[0].minor.yy43->ptr)) { ctx->ok = 0; } buffer_free(yymsp[0].minor.yy43); yymsp[0].minor.yy43 = NULL; } } #line 1358 "configparser.c" yy_destructor(24,&yymsp[-1].minor); break; case 39: #line 547 "./configparser.y" { if (ctx->ok) { if (0 != config_parse_cmd(ctx->srv, ctx, yymsp[0].minor.yy43->ptr)) { ctx->ok = 0; } buffer_free(yymsp[0].minor.yy43); yymsp[0].minor.yy43 = NULL; } } #line 1372 "configparser.c" yy_destructor(25,&yymsp[-1].minor); break; }; yygoto = yyRuleInfo[yyruleno].lhs; yysize = yyRuleInfo[yyruleno].nrhs; yypParser->yyidx -= yysize; yyact = yy_find_reduce_action(yypParser,yygoto); if( yyact < YYNSTATE ){ yy_shift(yypParser,yyact,yygoto,&yygotominor); }else if( yyact == YYNSTATE + YYNRULE + 1 ){ yy_accept(yypParser); } } /* ** The following code executes when the parse fails */ static void yy_parse_failed( yyParser *yypParser /* The parser */ ){ configparserARG_FETCH; #ifndef NDEBUG if( yyTraceFILE ){ fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt); } #endif while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser); /* Here code is inserted which will be executed whenever the ** parser fails */ #line 107 "./configparser.y" ctx->ok = 0; #line 1406 "configparser.c" configparserARG_STORE; /* Suppress warning about unused %extra_argument variable */ } /* ** The following code executes when a syntax error first occurs. */ static void yy_syntax_error( yyParser *yypParser, /* The parser */ int yymajor, /* The major type of the error token */ YYMINORTYPE yyminor /* The minor type of the error token */ ){ configparserARG_FETCH; #define TOKEN (yyminor.yy0) configparserARG_STORE; /* Suppress warning about unused %extra_argument variable */ } /* ** The following is executed when the parser accepts */ static void yy_accept( yyParser *yypParser /* The parser */ ){ configparserARG_FETCH; #ifndef NDEBUG if( yyTraceFILE ){ fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt); } #endif while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser); /* Here code is inserted which will be executed whenever the ** parser accepts */ configparserARG_STORE; /* Suppress warning about unused %extra_argument variable */ } /* The main parser program. ** The first argument is a pointer to a structure obtained from ** "configparserAlloc" which describes the current state of the parser. ** The second argument is the major token number. The third is ** the minor token. The fourth optional argument is whatever the ** user wants (and specified in the grammar) and is available for ** use by the action routines. ** ** Inputs: ** <ul> ** <li> A pointer to the parser (an opaque structure.) ** <li> The major token number. ** <li> The minor token number. ** <li> An option argument of a grammar-specified type. ** </ul> ** ** Outputs: ** None. */ void configparser( void *yyp, /* The parser */ int yymajor, /* The major token code number */ configparserTOKENTYPE yyminor /* The value for the token */ configparserARG_PDECL /* Optional %extra_argument parameter */ ){ YYMINORTYPE yyminorunion; int yyact; /* The parser action. */ int yyendofinput; /* True if we are at the end of input */ int yyerrorhit = 0; /* True if yymajor has invoked an error */ yyParser *yypParser; /* The parser */ /* (re)initialize the parser, if necessary */ yypParser = (yyParser*)yyp; if( yypParser->yyidx<0 ){ if( yymajor==0 ) return; yypParser->yyidx = 0; yypParser->yyerrcnt = -1; yypParser->yystack[0].stateno = 0; yypParser->yystack[0].major = 0; } yyminorunion.yy0 = yyminor; yyendofinput = (yymajor==0); configparserARG_STORE; #ifndef NDEBUG if( yyTraceFILE ){ fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]); } #endif do{ yyact = yy_find_shift_action(yypParser,yymajor); if( yyact<YYNSTATE ){ yy_shift(yypParser,yyact,yymajor,&yyminorunion); yypParser->yyerrcnt--; if( yyendofinput && yypParser->yyidx>=0 ){ yymajor = 0; }else{ yymajor = YYNOCODE; } }else if( yyact < YYNSTATE + YYNRULE ){ yy_reduce(yypParser,yyact-YYNSTATE); }else if( yyact == YY_ERROR_ACTION ){ int yymx; #ifndef NDEBUG if( yyTraceFILE ){ fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt); } #endif #ifdef YYERRORSYMBOL /* A syntax error has occurred. ** The response to an error depends upon whether or not the ** grammar defines an error token "ERROR". ** ** This is what we do if the grammar does define ERROR: ** ** * Call the %syntax_error function. ** ** * Begin popping the stack until we enter a state where ** it is legal to shift the error symbol, then shift ** the error symbol. ** ** * Set the error count to three. ** ** * Begin accepting and shifting new tokens. No new error ** processing will occur until three tokens have been ** shifted successfully. ** */ if( yypParser->yyerrcnt<0 ){ yy_syntax_error(yypParser,yymajor,yyminorunion); } yymx = yypParser->yystack[yypParser->yyidx].major; if( yymx==YYERRORSYMBOL || yyerrorhit ){ #ifndef NDEBUG if( yyTraceFILE ){ fprintf(yyTraceFILE,"%sDiscard input token %s\n", yyTracePrompt,yyTokenName[yymajor]); } #endif yy_destructor(yymajor,&yyminorunion); yymajor = YYNOCODE; }else{ while( yypParser->yyidx >= 0 && yymx != YYERRORSYMBOL && (yyact = yy_find_shift_action(yypParser,YYERRORSYMBOL)) >= YYNSTATE ){ yy_pop_parser_stack(yypParser); } if( yypParser->yyidx < 0 || yymajor==0 ){ yy_destructor(yymajor,&yyminorunion); yy_parse_failed(yypParser); yymajor = YYNOCODE; }else if( yymx!=YYERRORSYMBOL ){ YYMINORTYPE u2; u2.YYERRSYMDT = 0; yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2); } } yypParser->yyerrcnt = 3; yyerrorhit = 1; #else /* YYERRORSYMBOL is not defined */ /* This is what we do if the grammar does not define ERROR: ** ** * Report an error message, and throw away the input token. ** ** * If the input token is $, then fail the parse. ** ** As before, subsequent error messages are suppressed until ** three input tokens have been successfully shifted. */ if( yypParser->yyerrcnt<=0 ){ yy_syntax_error(yypParser,yymajor,yyminorunion); } yypParser->yyerrcnt = 3; yy_destructor(yymajor,&yyminorunion); if( yyendofinput ){ yy_parse_failed(yypParser); } yymajor = YYNOCODE; #endif }else{ yy_accept(yypParser); yymajor = YYNOCODE; } }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 ); return; }
atmark-techno/atmark-dist
user/lighttpd/src/configparser.c
C
gpl-2.0
50,209
/* * drivers/base/power/wakeup.c - System wakeup events framework * * Copyright (c) 2010 Rafael J. Wysocki <rjw@sisk.pl>, Novell Inc. * * This file is released under the GPLv2. */ #include <linux/device.h> #include <linux/slab.h> #include <linux/sched.h> #include <linux/capability.h> #include <linux/export.h> #include <linux/suspend.h> #include <linux/seq_file.h> #include <linux/debugfs.h> #include <trace/events/power.h> #include <linux/moduleparam.h> static bool enable_si_ws = true; module_param(enable_si_ws, bool, 0644); static bool enable_msm_hsic_ws = true; module_param(enable_msm_hsic_ws, bool, 0644); static bool enable_wlan_rx_wake_ws = true; module_param(enable_wlan_rx_wake_ws, bool, 0644); static bool enable_wlan_ctrl_wake_ws = true; module_param(enable_wlan_ctrl_wake_ws, bool, 0644); static bool enable_wlan_wake_ws = true; module_param(enable_wlan_wake_ws, bool, 0644); static bool enable_smb135x_wake_ws = true; module_param(enable_smb135x_wake_ws, bool, 0644); #include "power.h" /* * If set, the suspend/hibernate code will abort transitions to a sleep state * if wakeup events are registered during or immediately before the transition. */ bool events_check_enabled __read_mostly; /* * Combined counters of registered wakeup events and wakeup events in progress. * They need to be modified together atomically, so it's better to use one * atomic variable to hold them both. */ static atomic_t combined_event_count = ATOMIC_INIT(0); #define IN_PROGRESS_BITS (sizeof(int) * 4) #define MAX_IN_PROGRESS ((1 << IN_PROGRESS_BITS) - 1) static void split_counters(unsigned int *cnt, unsigned int *inpr) { unsigned int comb = atomic_read(&combined_event_count); *cnt = (comb >> IN_PROGRESS_BITS); *inpr = comb & MAX_IN_PROGRESS; } /* A preserved old value of the events counter. */ static unsigned int saved_count; static DEFINE_SPINLOCK(events_lock); static void pm_wakeup_timer_fn(unsigned long data); static LIST_HEAD(wakeup_sources); static DECLARE_WAIT_QUEUE_HEAD(wakeup_count_wait_queue); /** * wakeup_source_prepare - Prepare a new wakeup source for initialization. * @ws: Wakeup source to prepare. * @name: Pointer to the name of the new wakeup source. * * Callers must ensure that the @name string won't be freed when @ws is still in * use. */ void wakeup_source_prepare(struct wakeup_source *ws, const char *name) { if (ws) { memset(ws, 0, sizeof(*ws)); ws->name = name; } } EXPORT_SYMBOL_GPL(wakeup_source_prepare); /** * wakeup_source_create - Create a struct wakeup_source object. * @name: Name of the new wakeup source. */ struct wakeup_source *wakeup_source_create(const char *name) { struct wakeup_source *ws; ws = kmalloc(sizeof(*ws), GFP_KERNEL); if (!ws) return NULL; wakeup_source_prepare(ws, name ? kstrdup(name, GFP_KERNEL) : NULL); return ws; } EXPORT_SYMBOL_GPL(wakeup_source_create); /** * wakeup_source_drop - Prepare a struct wakeup_source object for destruction. * @ws: Wakeup source to prepare for destruction. * * Callers must ensure that __pm_stay_awake() or __pm_wakeup_event() will never * be run in parallel with this function for the same wakeup source object. */ void wakeup_source_drop(struct wakeup_source *ws) { if (!ws) return; del_timer_sync(&ws->timer); __pm_relax(ws); } EXPORT_SYMBOL_GPL(wakeup_source_drop); /** * wakeup_source_destroy - Destroy a struct wakeup_source object. * @ws: Wakeup source to destroy. * * Use only for wakeup source objects created with wakeup_source_create(). */ void wakeup_source_destroy(struct wakeup_source *ws) { if (!ws) return; wakeup_source_drop(ws); kfree(ws->name); kfree(ws); } EXPORT_SYMBOL_GPL(wakeup_source_destroy); /** * wakeup_source_destroy_cb * defer processing until all rcu references have expired */ static void wakeup_source_destroy_cb(struct rcu_head *head) { wakeup_source_destroy(container_of(head, struct wakeup_source, rcu)); } /** * wakeup_source_add - Add given object to the list of wakeup sources. * @ws: Wakeup source object to add to the list. */ void wakeup_source_add(struct wakeup_source *ws) { unsigned long flags; if (WARN_ON(!ws)) return; spin_lock_init(&ws->lock); setup_timer(&ws->timer, pm_wakeup_timer_fn, (unsigned long)ws); ws->active = false; ws->last_time = ktime_get(); spin_lock_irqsave(&events_lock, flags); list_add_rcu(&ws->entry, &wakeup_sources); spin_unlock_irqrestore(&events_lock, flags); } EXPORT_SYMBOL_GPL(wakeup_source_add); /** * wakeup_source_remove - Remove given object from the wakeup sources list. * @ws: Wakeup source object to remove from the list. */ void wakeup_source_remove(struct wakeup_source *ws) { unsigned long flags; if (WARN_ON(!ws)) return; spin_lock_irqsave(&events_lock, flags); list_del_rcu(&ws->entry); spin_unlock_irqrestore(&events_lock, flags); synchronize_rcu(); } EXPORT_SYMBOL_GPL(wakeup_source_remove); /** * wakeup_source_remove_async - Remove given object from the wakeup sources * list. * @ws: Wakeup source object to remove from the list. * * Use only for wakeup source objects created with wakeup_source_create(). * Memory for ws must be freed via rcu. */ static void wakeup_source_remove_async(struct wakeup_source *ws) { unsigned long flags; if (WARN_ON(!ws)) return; spin_lock_irqsave(&events_lock, flags); list_del_rcu(&ws->entry); spin_unlock_irqrestore(&events_lock, flags); } /** * wakeup_source_register - Create wakeup source and add it to the list. * @name: Name of the wakeup source to register. */ struct wakeup_source *wakeup_source_register(const char *name) { struct wakeup_source *ws; ws = wakeup_source_create(name); if (ws) wakeup_source_add(ws); return ws; } EXPORT_SYMBOL_GPL(wakeup_source_register); /** * wakeup_source_unregister - Remove wakeup source from the list and remove it. * @ws: Wakeup source object to unregister. */ void wakeup_source_unregister(struct wakeup_source *ws) { if (ws) { wakeup_source_remove_async(ws); call_rcu(&ws->rcu, wakeup_source_destroy_cb); } } EXPORT_SYMBOL_GPL(wakeup_source_unregister); /** * device_wakeup_attach - Attach a wakeup source object to a device object. * @dev: Device to handle. * @ws: Wakeup source object to attach to @dev. * * This causes @dev to be treated as a wakeup device. */ static int device_wakeup_attach(struct device *dev, struct wakeup_source *ws) { spin_lock_irq(&dev->power.lock); if (dev->power.wakeup) { spin_unlock_irq(&dev->power.lock); return -EEXIST; } dev->power.wakeup = ws; spin_unlock_irq(&dev->power.lock); return 0; } /** * device_wakeup_enable - Enable given device to be a wakeup source. * @dev: Device to handle. * * Create a wakeup source object, register it and attach it to @dev. */ int device_wakeup_enable(struct device *dev) { struct wakeup_source *ws; int ret; if (!dev || !dev->power.can_wakeup) return -EINVAL; ws = wakeup_source_register(dev_name(dev)); if (!ws) return -ENOMEM; ret = device_wakeup_attach(dev, ws); if (ret) wakeup_source_unregister(ws); return ret; } EXPORT_SYMBOL_GPL(device_wakeup_enable); /** * device_wakeup_detach - Detach a device's wakeup source object from it. * @dev: Device to detach the wakeup source object from. * * After it returns, @dev will not be treated as a wakeup device any more. */ static struct wakeup_source *device_wakeup_detach(struct device *dev) { struct wakeup_source *ws; spin_lock_irq(&dev->power.lock); ws = dev->power.wakeup; dev->power.wakeup = NULL; spin_unlock_irq(&dev->power.lock); return ws; } /** * device_wakeup_disable - Do not regard a device as a wakeup source any more. * @dev: Device to handle. * * Detach the @dev's wakeup source object from it, unregister this wakeup source * object and destroy it. */ int device_wakeup_disable(struct device *dev) { struct wakeup_source *ws; if (!dev || !dev->power.can_wakeup) return -EINVAL; ws = device_wakeup_detach(dev); if (ws) wakeup_source_unregister(ws); return 0; } EXPORT_SYMBOL_GPL(device_wakeup_disable); /** * device_set_wakeup_capable - Set/reset device wakeup capability flag. * @dev: Device to handle. * @capable: Whether or not @dev is capable of waking up the system from sleep. * * If @capable is set, set the @dev's power.can_wakeup flag and add its * wakeup-related attributes to sysfs. Otherwise, unset the @dev's * power.can_wakeup flag and remove its wakeup-related attributes from sysfs. * * This function may sleep and it can't be called from any context where * sleeping is not allowed. */ void device_set_wakeup_capable(struct device *dev, bool capable) { if (!!dev->power.can_wakeup == !!capable) return; if (device_is_registered(dev) && !list_empty(&dev->power.entry)) { if (capable) { if (wakeup_sysfs_add(dev)) return; } else { wakeup_sysfs_remove(dev); } } dev->power.can_wakeup = capable; } EXPORT_SYMBOL_GPL(device_set_wakeup_capable); /** * device_init_wakeup - Device wakeup initialization. * @dev: Device to handle. * @enable: Whether or not to enable @dev as a wakeup device. * * By default, most devices should leave wakeup disabled. The exceptions are * devices that everyone expects to be wakeup sources: keyboards, power buttons, * possibly network interfaces, etc. Also, devices that don't generate their * own wakeup requests but merely forward requests from one bus to another * (like PCI bridges) should have wakeup enabled by default. */ int device_init_wakeup(struct device *dev, bool enable) { int ret = 0; if (enable) { device_set_wakeup_capable(dev, true); ret = device_wakeup_enable(dev); } else { device_set_wakeup_capable(dev, false); } return ret; } EXPORT_SYMBOL_GPL(device_init_wakeup); /** * device_set_wakeup_enable - Enable or disable a device to wake up the system. * @dev: Device to handle. */ int device_set_wakeup_enable(struct device *dev, bool enable) { if (!dev || !dev->power.can_wakeup) return -EINVAL; return enable ? device_wakeup_enable(dev) : device_wakeup_disable(dev); } EXPORT_SYMBOL_GPL(device_set_wakeup_enable); /* * The functions below use the observation that each wakeup event starts a * period in which the system should not be suspended. The moment this period * will end depends on how the wakeup event is going to be processed after being * detected and all of the possible cases can be divided into two distinct * groups. * * First, a wakeup event may be detected by the same functional unit that will * carry out the entire processing of it and possibly will pass it to user space * for further processing. In that case the functional unit that has detected * the event may later "close" the "no suspend" period associated with it * directly as soon as it has been dealt with. The pair of pm_stay_awake() and * pm_relax(), balanced with each other, is supposed to be used in such * situations. * * Second, a wakeup event may be detected by one functional unit and processed * by another one. In that case the unit that has detected it cannot really * "close" the "no suspend" period associated with it, unless it knows in * advance what's going to happen to the event during processing. This * knowledge, however, may not be available to it, so it can simply specify time * to wait before the system can be suspended and pass it as the second * argument of pm_wakeup_event(). * * It is valid to call pm_relax() after pm_wakeup_event(), in which case the * "no suspend" period will be ended either by the pm_relax(), or by the timer * function executed when the timer expires, whichever comes first. */ /** * wakup_source_activate - Mark given wakeup source as active. * @ws: Wakeup source to handle. * * Update the @ws' statistics and, if @ws has just been activated, notify the PM * core of the event by incrementing the counter of of wakeup events being * processed. */ static void wakeup_source_activate(struct wakeup_source *ws) { unsigned int cec; if (!enable_si_ws && !strcmp(ws->name, "sensor_ind")) return; if (!enable_msm_hsic_ws && !strcmp(ws->name, "msm_hsic_host")) return; if (!enable_wlan_rx_wake_ws && !strcmp(ws->name, "wlan_rx_wake")) return; if (!enable_wlan_ctrl_wake_ws && !strcmp(ws->name, "wlan_ctrl_wake")) return; if (!enable_wlan_wake_ws && !strcmp(ws->name, "wlan_wake")) return; /* * active wakeup source should bring the system * out of PM_SUSPEND_FREEZE state */ freeze_wake(); ws->active = true; ws->active_count++; ws->last_time = ktime_get(); if (ws->autosleep_enabled) ws->start_prevent_time = ws->last_time; /* Increment the counter of events in progress. */ cec = atomic_inc_return(&combined_event_count); trace_wakeup_source_activate(ws->name, cec); } /** * wakeup_source_report_event - Report wakeup event using the given source. * @ws: Wakeup source to report the event for. */ static void wakeup_source_report_event(struct wakeup_source *ws) { ws->event_count++; /* This is racy, but the counter is approximate anyway. */ if (events_check_enabled) ws->wakeup_count++; if (!ws->active) wakeup_source_activate(ws); } /** * __pm_stay_awake - Notify the PM core of a wakeup event. * @ws: Wakeup source object associated with the source of the event. * * It is safe to call this function from interrupt context. */ void __pm_stay_awake(struct wakeup_source *ws) { unsigned long flags; if (!ws) return; spin_lock_irqsave(&ws->lock, flags); wakeup_source_report_event(ws); del_timer(&ws->timer); ws->timer_expires = 0; spin_unlock_irqrestore(&ws->lock, flags); } EXPORT_SYMBOL_GPL(__pm_stay_awake); /** * pm_stay_awake - Notify the PM core that a wakeup event is being processed. * @dev: Device the wakeup event is related to. * * Notify the PM core of a wakeup event (signaled by @dev) by calling * __pm_stay_awake for the @dev's wakeup source object. * * Call this function after detecting of a wakeup event if pm_relax() is going * to be called directly after processing the event (and possibly passing it to * user space for further processing). */ void pm_stay_awake(struct device *dev) { unsigned long flags; if (!dev) return; spin_lock_irqsave(&dev->power.lock, flags); __pm_stay_awake(dev->power.wakeup); spin_unlock_irqrestore(&dev->power.lock, flags); } EXPORT_SYMBOL_GPL(pm_stay_awake); #ifdef CONFIG_PM_AUTOSLEEP static void update_prevent_sleep_time(struct wakeup_source *ws, ktime_t now) { ktime_t delta = ktime_sub(now, ws->start_prevent_time); ws->prevent_sleep_time = ktime_add(ws->prevent_sleep_time, delta); #ifdef CONFIG_HUAWEI_KERNEL ws->screen_off_time = ktime_add(ws->screen_off_time, delta); #endif } #else static inline void update_prevent_sleep_time(struct wakeup_source *ws, ktime_t now) {} #endif /** * wakup_source_deactivate - Mark given wakeup source as inactive. * @ws: Wakeup source to handle. * * Update the @ws' statistics and notify the PM core that the wakeup source has * become inactive by decrementing the counter of wakeup events being processed * and incrementing the counter of registered wakeup events. */ static void wakeup_source_deactivate(struct wakeup_source *ws) { unsigned int cnt, inpr, cec; ktime_t duration; ktime_t now; ws->relax_count++; /* * __pm_relax() may be called directly or from a timer function. * If it is called directly right after the timer function has been * started, but before the timer function calls __pm_relax(), it is * possible that __pm_stay_awake() will be called in the meantime and * will set ws->active. Then, ws->active may be cleared immediately * by the __pm_relax() called from the timer function, but in such a * case ws->relax_count will be different from ws->active_count. */ if (ws->relax_count != ws->active_count) { ws->relax_count--; return; } ws->active = false; now = ktime_get(); duration = ktime_sub(now, ws->last_time); ws->total_time = ktime_add(ws->total_time, duration); if (ktime_to_ns(duration) > ktime_to_ns(ws->max_time)) ws->max_time = duration; ws->last_time = now; del_timer(&ws->timer); ws->timer_expires = 0; if (ws->autosleep_enabled) update_prevent_sleep_time(ws, now); /* * Increment the counter of registered wakeup events and decrement the * couter of wakeup events in progress simultaneously. */ cec = atomic_add_return(MAX_IN_PROGRESS, &combined_event_count); trace_wakeup_source_deactivate(ws->name, cec); split_counters(&cnt, &inpr); if (!inpr && waitqueue_active(&wakeup_count_wait_queue)) wake_up(&wakeup_count_wait_queue); } /** * __pm_relax - Notify the PM core that processing of a wakeup event has ended. * @ws: Wakeup source object associated with the source of the event. * * Call this function for wakeup events whose processing started with calling * __pm_stay_awake(). * * It is safe to call it from interrupt context. */ void __pm_relax(struct wakeup_source *ws) { unsigned long flags; if (!ws) return; spin_lock_irqsave(&ws->lock, flags); if (ws->active) wakeup_source_deactivate(ws); spin_unlock_irqrestore(&ws->lock, flags); } EXPORT_SYMBOL_GPL(__pm_relax); /** * pm_relax - Notify the PM core that processing of a wakeup event has ended. * @dev: Device that signaled the event. * * Execute __pm_relax() for the @dev's wakeup source object. */ void pm_relax(struct device *dev) { unsigned long flags; if (!dev) return; spin_lock_irqsave(&dev->power.lock, flags); __pm_relax(dev->power.wakeup); spin_unlock_irqrestore(&dev->power.lock, flags); } EXPORT_SYMBOL_GPL(pm_relax); /** * pm_wakeup_timer_fn - Delayed finalization of a wakeup event. * @data: Address of the wakeup source object associated with the event source. * * Call wakeup_source_deactivate() for the wakeup source whose address is stored * in @data if it is currently active and its timer has not been canceled and * the expiration time of the timer is not in future. */ static void pm_wakeup_timer_fn(unsigned long data) { struct wakeup_source *ws = (struct wakeup_source *)data; unsigned long flags; spin_lock_irqsave(&ws->lock, flags); if (ws->active && ws->timer_expires && time_after_eq(jiffies, ws->timer_expires)) { wakeup_source_deactivate(ws); ws->expire_count++; } spin_unlock_irqrestore(&ws->lock, flags); } /** * __pm_wakeup_event - Notify the PM core of a wakeup event. * @ws: Wakeup source object associated with the event source. * @msec: Anticipated event processing time (in milliseconds). * * Notify the PM core of a wakeup event whose source is @ws that will take * approximately @msec milliseconds to be processed by the kernel. If @ws is * not active, activate it. If @msec is nonzero, set up the @ws' timer to * execute pm_wakeup_timer_fn() in future. * * It is safe to call this function from interrupt context. */ void __pm_wakeup_event(struct wakeup_source *ws, unsigned int msec) { unsigned long flags; unsigned long expires; if (!ws) return; spin_lock_irqsave(&ws->lock, flags); wakeup_source_report_event(ws); if (!msec) { wakeup_source_deactivate(ws); goto unlock; } expires = jiffies + msecs_to_jiffies(msec); if (!expires) expires = 1; if (!ws->timer_expires || time_after(expires, ws->timer_expires)) { mod_timer(&ws->timer, expires); ws->timer_expires = expires; } unlock: spin_unlock_irqrestore(&ws->lock, flags); } EXPORT_SYMBOL_GPL(__pm_wakeup_event); /** * pm_wakeup_event - Notify the PM core of a wakeup event. * @dev: Device the wakeup event is related to. * @msec: Anticipated event processing time (in milliseconds). * * Call __pm_wakeup_event() for the @dev's wakeup source object. */ void pm_wakeup_event(struct device *dev, unsigned int msec) { unsigned long flags; if (!dev) return; spin_lock_irqsave(&dev->power.lock, flags); __pm_wakeup_event(dev->power.wakeup, msec); spin_unlock_irqrestore(&dev->power.lock, flags); } EXPORT_SYMBOL_GPL(pm_wakeup_event); static void print_active_wakeup_sources(void) { struct wakeup_source *ws; int active = 0; struct wakeup_source *last_activity_ws = NULL; rcu_read_lock(); list_for_each_entry_rcu(ws, &wakeup_sources, entry) { if (ws->active) { pr_info("active wakeup source: %s\n", ws->name); active = 1; } else if (!active && (!last_activity_ws || ktime_to_ns(ws->last_time) > ktime_to_ns(last_activity_ws->last_time))) { last_activity_ws = ws; } } if (!active && last_activity_ws) pr_info("last active wakeup source: %s\n", last_activity_ws->name); rcu_read_unlock(); } /** * pm_wakeup_pending - Check if power transition in progress should be aborted. * * Compare the current number of registered wakeup events with its preserved * value from the past and return true if new wakeup events have been registered * since the old value was stored. Also return true if the current number of * wakeup events being processed is different from zero. */ bool pm_wakeup_pending(void) { unsigned long flags; bool ret = false; spin_lock_irqsave(&events_lock, flags); if (events_check_enabled) { unsigned int cnt, inpr; split_counters(&cnt, &inpr); ret = (cnt != saved_count || inpr > 0); events_check_enabled = !ret; } spin_unlock_irqrestore(&events_lock, flags); if (ret) print_active_wakeup_sources(); return ret; } /** * pm_get_wakeup_count - Read the number of registered wakeup events. * @count: Address to store the value at. * @block: Whether or not to block. * * Store the number of registered wakeup events at the address in @count. If * @block is set, block until the current number of wakeup events being * processed is zero. * * Return 'false' if the current number of wakeup events being processed is * nonzero. Otherwise return 'true'. */ #ifdef CONFIG_HUAWEI_KERNEL extern void print_all_active_wakeup_source(void); #endif bool pm_get_wakeup_count(unsigned int *count, bool block) { unsigned int cnt, inpr; /* remove print_all_active_wakeup_source() temporarily */ if (block) { DEFINE_WAIT(wait); for (;;) { prepare_to_wait(&wakeup_count_wait_queue, &wait, TASK_INTERRUPTIBLE); split_counters(&cnt, &inpr); if (inpr == 0 || signal_pending(current)) break; schedule(); } finish_wait(&wakeup_count_wait_queue, &wait); } split_counters(&cnt, &inpr); *count = cnt; return !inpr; } /** * pm_save_wakeup_count - Save the current number of registered wakeup events. * @count: Value to compare with the current number of registered wakeup events. * * If @count is equal to the current number of registered wakeup events and the * current number of wakeup events being processed is zero, store @count as the * old number of registered wakeup events for pm_check_wakeup_events(), enable * wakeup events detection and return 'true'. Otherwise disable wakeup events * detection and return 'false'. */ bool pm_save_wakeup_count(unsigned int count) { unsigned int cnt, inpr; unsigned long flags; events_check_enabled = false; spin_lock_irqsave(&events_lock, flags); split_counters(&cnt, &inpr); if (cnt == count && inpr == 0) { saved_count = count; events_check_enabled = true; } spin_unlock_irqrestore(&events_lock, flags); return events_check_enabled; } #ifdef CONFIG_PM_AUTOSLEEP /** * pm_wakep_autosleep_enabled - Modify autosleep_enabled for all wakeup sources. * @enabled: Whether to set or to clear the autosleep_enabled flags. */ void pm_wakep_autosleep_enabled(bool set) { struct wakeup_source *ws; ktime_t now = ktime_get(); rcu_read_lock(); list_for_each_entry_rcu(ws, &wakeup_sources, entry) { spin_lock_irq(&ws->lock); if (ws->autosleep_enabled != set) { ws->autosleep_enabled = set; if (ws->active) { if (set) ws->start_prevent_time = now; else update_prevent_sleep_time(ws, now); } #ifdef CONFIG_HUAWEI_KERNEL if (set) { // screen off ws->screen_off_time = ktime_set(0, 0); } #endif } spin_unlock_irq(&ws->lock); } rcu_read_unlock(); } #endif /* CONFIG_PM_AUTOSLEEP */ static struct dentry *wakeup_sources_stats_dentry; /** * print_wakeup_source_stats - Print wakeup source statistics information. * @m: seq_file to print the statistics into. * @ws: Wakeup source object to print the statistics for. */ static int print_wakeup_source_stats(struct seq_file *m, struct wakeup_source *ws) { unsigned long flags; ktime_t total_time; ktime_t max_time; unsigned long active_count; ktime_t active_time; ktime_t prevent_sleep_time; #ifdef CONFIG_HUAWEI_KERNEL ktime_t screen_off_time; #endif int ret; spin_lock_irqsave(&ws->lock, flags); total_time = ws->total_time; max_time = ws->max_time; prevent_sleep_time = ws->prevent_sleep_time; #ifdef CONFIG_HUAWEI_KERNEL screen_off_time = ws->screen_off_time; #endif active_count = ws->active_count; if (ws->active) { ktime_t now = ktime_get(); active_time = ktime_sub(now, ws->last_time); total_time = ktime_add(total_time, active_time); if (active_time.tv64 > max_time.tv64) max_time = active_time; #ifdef CONFIG_HUAWEI_KERNEL if (ws->autosleep_enabled) { prevent_sleep_time = ktime_add(prevent_sleep_time, ktime_sub(now, ws->start_prevent_time)); screen_off_time = ktime_add(screen_off_time, ktime_sub(now, ws->start_prevent_time)); } #else if (ws->autosleep_enabled) prevent_sleep_time = ktime_add(prevent_sleep_time, ktime_sub(now, ws->start_prevent_time)); #endif } else { active_time = ktime_set(0, 0); } #ifdef CONFIG_HUAWEI_KERNEL ret = seq_printf(m, "%-12s\t%lu\t\t%lu\t\t%lu\t\t%lu\t\t" "%lld\t\t%lld\t\t%lld\t\t%lld\t\t%lld\t\t%lld\n", ws->name, active_count, ws->event_count, ws->wakeup_count, ws->expire_count, ktime_to_ms(active_time), ktime_to_ms(total_time), ktime_to_ms(max_time), ktime_to_ms(ws->last_time), ktime_to_ms(prevent_sleep_time), ktime_to_ms(screen_off_time)); #else ret = seq_printf(m, "%-12s\t%lu\t\t%lu\t\t%lu\t\t%lu\t\t" "%lld\t\t%lld\t\t%lld\t\t%lld\t\t%lld\n", ws->name, active_count, ws->event_count, ws->wakeup_count, ws->expire_count, ktime_to_ms(active_time), ktime_to_ms(total_time), ktime_to_ms(max_time), ktime_to_ms(ws->last_time), ktime_to_ms(prevent_sleep_time)); #endif spin_unlock_irqrestore(&ws->lock, flags); return ret; } #ifdef CONFIG_HUAWEI_KERNEL /** * print_wakeup_source_stats - Print wakeup source statistics information. * @m: seq_file to print the statistics into. * @ws: Wakeup source object to print the statistics for. */ static void print_one_active_wakeup_source(struct wakeup_source *ws) { unsigned long flags; ktime_t total_time; ktime_t max_time; unsigned long active_count; ktime_t active_time; ktime_t prevent_sleep_time; spin_lock_irqsave(&ws->lock, flags); total_time = ws->total_time; max_time = ws->max_time; prevent_sleep_time = ws->prevent_sleep_time; active_count = ws->active_count; if (ws->active) { ktime_t now = ktime_get(); active_time = ktime_sub(now, ws->last_time); total_time = ktime_add(total_time, active_time); if (active_time.tv64 > max_time.tv64) max_time = active_time; if (ws->autosleep_enabled) prevent_sleep_time = ktime_add(prevent_sleep_time, ktime_sub(now, ws->start_prevent_time)); } else { active_time = ktime_set(0, 0); } if(ws->active) { printk( "Active resource: %-12s\t%lu\t\t%lu\t\t%lu\t\t%lu\t\t" "%lld\t\t%lld\t\t%lld\t\t%lld\t\t%lld\n", ws->name, active_count, ws->event_count, ws->wakeup_count, ws->expire_count, ktime_to_ms(active_time), ktime_to_ms(total_time), ktime_to_ms(max_time), ktime_to_ms(ws->last_time), ktime_to_ms(prevent_sleep_time)); } spin_unlock_irqrestore(&ws->lock, flags); return; } /** * print_wakeup_source_stats - Print wakeup source statistics information. * @m: seq_file to print the statistics into. * @ws: Wakeup source object to print the statistics for. */ void print_all_active_wakeup_source(void) { struct wakeup_source *ws; printk("name\t\tactive_count\tevent_count\twakeup_count\t" "expire_count\tactive_since\ttotal_time\tmax_time\t" "last_change\tprevent_suspend_time\n"); rcu_read_lock(); list_for_each_entry_rcu(ws, &wakeup_sources, entry) print_one_active_wakeup_source(ws); rcu_read_unlock(); } /** * print_wakeup_source_stats - Print wakeup source statistics information. * @m: seq_file to print the statistics into. * @ws: Wakeup source object to print the statistics for. */ static int print_active_wakeup_source(struct seq_file *m, struct wakeup_source *ws) { unsigned long flags; ktime_t total_time; ktime_t max_time; unsigned long active_count; ktime_t active_time; ktime_t prevent_sleep_time; int ret = 0; spin_lock_irqsave(&ws->lock, flags); total_time = ws->total_time; max_time = ws->max_time; prevent_sleep_time = ws->prevent_sleep_time; active_count = ws->active_count; if (ws->active) { ktime_t now = ktime_get(); active_time = ktime_sub(now, ws->last_time); total_time = ktime_add(total_time, active_time); if (active_time.tv64 > max_time.tv64) max_time = active_time; if (ws->autosleep_enabled) prevent_sleep_time = ktime_add(prevent_sleep_time, ktime_sub(now, ws->start_prevent_time)); } else { active_time = ktime_set(0, 0); } if(ws->active) { ret = seq_printf(m, "Active resource: %-12s\t%lu\t\t%lu\t\t%lu\t\t%lu\t\t" "%lld\t\t%lld\t\t%lld\t\t%lld\t\t%lld\n", ws->name, active_count, ws->event_count, ws->wakeup_count, ws->expire_count, ktime_to_ms(active_time), ktime_to_ms(total_time), ktime_to_ms(max_time), ktime_to_ms(ws->last_time), ktime_to_ms(prevent_sleep_time)); } spin_unlock_irqrestore(&ws->lock, flags); return ret; } #endif /** * wakeup_sources_stats_show - Print wakeup sources statistics information. * @m: seq_file to print the statistics into. */ static int wakeup_sources_stats_show(struct seq_file *m, void *unused) { struct wakeup_source *ws; #ifdef CONFIG_HUAWEI_KERNEL seq_puts(m, "name\t\tactive_count\tevent_count\twakeup_count\t" "expire_count\tactive_since\ttotal_time\tmax_time\t" "last_change\tprevent_suspend_time\tscreen_off_time\n"); #else seq_puts(m, "name\t\tactive_count\tevent_count\twakeup_count\t" "expire_count\tactive_since\ttotal_time\tmax_time\t" "last_change\tprevent_suspend_time\n"); #endif rcu_read_lock(); list_for_each_entry_rcu(ws, &wakeup_sources, entry) print_wakeup_source_stats(m, ws); #ifdef CONFIG_HUAWEI_KERNEL list_for_each_entry_rcu(ws, &wakeup_sources, entry) print_active_wakeup_source(m, ws); #endif rcu_read_unlock(); return 0; } static int wakeup_sources_stats_open(struct inode *inode, struct file *file) { return single_open(file, wakeup_sources_stats_show, NULL); } static const struct file_operations wakeup_sources_stats_fops = { .owner = THIS_MODULE, .open = wakeup_sources_stats_open, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; static int __init wakeup_sources_debugfs_init(void) { wakeup_sources_stats_dentry = debugfs_create_file("wakeup_sources", S_IRUGO, NULL, NULL, &wakeup_sources_stats_fops); return 0; } postcore_initcall(wakeup_sources_debugfs_init);
Hacker432-Y550/android_kernel_huawei_msm8916
drivers/base/power/wakeup.c
C
gpl-2.0
31,179
// Copyright (c) 2006-2013 INRIA Nancy-Grand Est (France). All rights reserved. // // This file is part of CGAL (www.cgal.org); 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. // See the file LICENSE.LGPL distributed with CGAL. // // Licensees holding a valid commercial license may use this file in // accordance with the commercial license agreement provided with the software. // // This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE // WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. // // $URL: https://github.com/CGAL/cgal/blob/releases/CGAL-4.14.1/Algebraic_kernel_d/include/CGAL/RS/ak_1.h $ // $Id: ak_1.h 0698f79 %aI Sébastien Loriot // SPDX-License-Identifier: LGPL-3.0+ // // Author: Luis Peñaranda <luis.penaranda@gmx.com> #ifndef CGAL_RS_AK_1_H #define CGAL_RS_AK_1_H #include <cstddef> // included only to define size_t #include <CGAL/Polynomial_traits_d.h> #include "algebraic_1.h" #include "comparator_1.h" #include "signat_1.h" #include "functors_1.h" namespace CGAL{ namespace RS_AK1{ template <class Polynomial_, class Bound_, class Isolator_, class Refiner_, class Ptraits_=CGAL::Polynomial_traits_d<Polynomial_> > class Algebraic_kernel_1{ public: typedef Polynomial_ Polynomial_1; typedef typename Polynomial_1::NT Coefficient; typedef Bound_ Bound; private: typedef Isolator_ Isolator; typedef Refiner_ Refiner; typedef Ptraits_ Ptraits; typedef CGAL::RS_AK1::Signat_1<Polynomial_1,Bound> Signat; typedef CGAL::RS_AK1::Simple_comparator_1<Polynomial_1, Bound, Refiner, Signat, Ptraits> Comparator; public: typedef CGAL::RS_AK1::Algebraic_1<Polynomial_1, Bound, Refiner, Comparator, Ptraits> Algebraic_real_1; typedef size_t size_type; typedef unsigned Multiplicity_type; // default constructor and destructor public: Algebraic_kernel_1(){}; ~Algebraic_kernel_1(){}; // functors from the CGAL concept public: typedef CGAL::RS_AK1::Construct_algebraic_real_1<Polynomial_1, Algebraic_real_1, Bound, Coefficient, Isolator> Construct_algebraic_real_1; typedef CGAL::RS_AK1::Compute_polynomial_1<Polynomial_1, Algebraic_real_1> Compute_polynomial_1; typedef CGAL::RS_AK1::Isolate_1<Polynomial_1, Bound, Algebraic_real_1, Isolator, Comparator, Signat, Ptraits> Isolate_1; typedef typename Ptraits::Is_square_free Is_square_free_1; typedef typename Ptraits::Make_square_free Make_square_free_1; typedef typename Ptraits::Square_free_factorize Square_free_factorize_1; typedef CGAL::RS_AK1::Is_coprime_1<Polynomial_1,Ptraits> Is_coprime_1; typedef CGAL::RS_AK1::Make_coprime_1<Polynomial_1,Ptraits> Make_coprime_1; typedef CGAL::RS_AK1::Solve_1<Polynomial_1, Bound, Algebraic_real_1, Isolator, Signat, Ptraits> Solve_1; typedef CGAL::RS_AK1::Number_of_solutions_1<Polynomial_1,Isolator> Number_of_solutions_1; typedef CGAL::RS_AK1::Sign_at_1<Polynomial_1, Bound, Algebraic_real_1, Refiner, Signat, Ptraits> Sign_at_1; typedef CGAL::RS_AK1::Is_zero_at_1<Polynomial_1, Bound, Algebraic_real_1, Refiner, Signat, Ptraits> Is_zero_at_1; typedef CGAL::RS_AK1::Compare_1<Algebraic_real_1, Bound, Comparator> Compare_1; typedef CGAL::RS_AK1::Bound_between_1<Algebraic_real_1, Bound, Comparator> Bound_between_1; typedef CGAL::RS_AK1::Approximate_absolute_1<Polynomial_1, Bound, Algebraic_real_1, Refiner> Approximate_absolute_1; typedef CGAL::RS_AK1::Approximate_relative_1<Polynomial_1, Bound, Algebraic_real_1, Refiner> Approximate_relative_1; #define CREATE_FUNCTION_OBJECT(T,N) \ T N##_object()const{return T();} CREATE_FUNCTION_OBJECT(Construct_algebraic_real_1, construct_algebraic_real_1) CREATE_FUNCTION_OBJECT(Compute_polynomial_1, compute_polynomial_1) CREATE_FUNCTION_OBJECT(Isolate_1, isolate_1) CREATE_FUNCTION_OBJECT(Is_square_free_1, is_square_free_1) CREATE_FUNCTION_OBJECT(Make_square_free_1, make_square_free_1) CREATE_FUNCTION_OBJECT(Square_free_factorize_1, square_free_factorize_1) CREATE_FUNCTION_OBJECT(Is_coprime_1, is_coprime_1) CREATE_FUNCTION_OBJECT(Make_coprime_1, make_coprime_1) CREATE_FUNCTION_OBJECT(Solve_1, solve_1) CREATE_FUNCTION_OBJECT(Number_of_solutions_1, number_of_solutions_1) CREATE_FUNCTION_OBJECT(Sign_at_1, sign_at_1) CREATE_FUNCTION_OBJECT(Is_zero_at_1, is_zero_at_1) CREATE_FUNCTION_OBJECT(Compare_1, compare_1) CREATE_FUNCTION_OBJECT(Bound_between_1, bound_between_1) CREATE_FUNCTION_OBJECT(Approximate_absolute_1, approximate_absolute_1) CREATE_FUNCTION_OBJECT(Approximate_relative_1, approximate_relative_1) #undef CREATE_FUNCTION_OBJECT }; // class Algebraic_kernel_1 } // namespace RS_AK1 } // namespace CGAL #endif // CGAL_RS_AK_1_H
wschreyer/PENTrack
cgal/include/CGAL/RS/ak_1.h
C
gpl-2.0
8,851
/**************************************************************************** * Copyright (C) 2015 Cisco and/or its affiliates. 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 as * published by the Free Software Foundation. You may not use, modify or * distribute this program under any other version of the GNU General * Public 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 Street, Fifth Floor, Boston, MA 02110-1301, USA. * ****************************************************************************/ #include <sys/types.h> #include "main/snort_types.h" #include "main/snort_debug.h" #include "imap_paf.h" #include "imap.h" extern IMAPToken imap_resps[]; static inline ImapPafData* get_state(Flow* flow, bool c2s) { if ( !flow ) return nullptr; ImapSplitter* s = (ImapSplitter*)stream.get_splitter(flow, c2s); return s ? &s->state : nullptr; } static inline void reset_data_states(ImapPafData* pfdata) { // reset MIME info file_api->reset_mime_paf_state(&(pfdata->mime_info)); // reset server info pfdata->imap_state = IMAP_PAF_CMD_IDENTIFIER; // reset fetch data information information pfdata->imap_data_info.paren_cnt = 0; pfdata->imap_data_info.next_letter = 0; pfdata->imap_data_info.length = 0; } static inline bool is_untagged(const uint8_t ch) { return (ch == '*' || ch == '+'); } static bool parse_literal_length(const uint8_t ch, uint32_t* len) { uint32_t length = *len; if (isdigit(ch)) { uint64_t tmp_len = (10 * length) + (ch - '0'); if (tmp_len < UINT32_MAX) { *len = (uint32_t)tmp_len; return false; } else { *len = 0; } } else if (ch != '}') *len = 0; // ALERT!! charachter should be a digit or ''}'' return true; } static void parse_fetch_header(const uint8_t ch, ImapPafData* pfdata) { if (pfdata->imap_data_info.esc_nxt_char) { pfdata->imap_data_info.esc_nxt_char = false; } else { switch (ch) { case '{': pfdata->imap_state = IMAP_PAF_DATA_LEN_STATE; break; case '(': pfdata->imap_data_info.paren_cnt++; break; case ')': if (pfdata->imap_data_info.paren_cnt > 0) pfdata->imap_data_info.paren_cnt--; break; case '\n': if (pfdata->imap_data_info.paren_cnt) { pfdata->imap_state = IMAP_PAF_DATA_STATE; } else { reset_data_states(pfdata); } break; case '\\': pfdata->imap_data_info.esc_nxt_char = true; break; default: break; } } } /* * Statefully search for the single line termination sequence LF ("\n"). * * PARAMS: * const uint8_t ch - the next character to analyze. * ImapPafData *pfdata - the struct containing all imap paf information * * RETURNS: * false - if termination sequence not found * true - if termination sequence found */ static bool find_data_end_single_line(const uint8_t ch, ImapPafData* pfdata) { if (ch == '\n') { reset_data_states(pfdata); return true; } return false; } /* Flush based on data length*/ static inline bool literal_complete(ImapPafData* pfdata) { if (pfdata->imap_data_info.length) { pfdata->imap_data_info.length--; if (pfdata->imap_data_info.length) return false; } return true; } static bool check_imap_data_end(ImapDataEnd* data_end_state, uint8_t val) { switch (*data_end_state) { case IMAP_PAF_DATA_END_UNKNOWN: if (val == ')') *data_end_state = IMAP_PAF_DATA_END_PAREN; break; case IMAP_PAF_DATA_END_PAREN: if (val == '\n') { *data_end_state = IMAP_PAF_DATA_END_UNKNOWN; return true; } else if (val != '\r') { *data_end_state = IMAP_PAF_DATA_END_UNKNOWN; } break; default: break; } return false; } /* * Statefully search for the data termination sequence or a MIME boundary. * * PARAMS: * const uint8_t ch - the next character to analyze. * ImapPafData *pfdata - the struct containing all imap paf information * * RETURNS: * false - if termination sequence not found * true - if termination sequence found */ static bool find_data_end_mime_data(const uint8_t ch, ImapPafData* pfdata) { if (literal_complete(pfdata) && check_imap_data_end(&(pfdata->data_end_state), ch)) { DEBUG_WRAP(DebugMessage(DEBUG_IMAP, "IMAP PAF: End of Data!\n"); ); reset_data_states(pfdata); return true; } // check for mime flush point if (file_api->process_mime_paf_data(&(pfdata->mime_info), ch)) { DEBUG_WRAP(DebugMessage(DEBUG_IMAP, "IMAP PAF: Mime Boundary found." " Flushing data!\n"); ); return true; } return false; } /* * Initial command processing function. Determine if this command * may be analyzed irregularly ( which currently means if emails * and email attachments need to be analyzed). * * PARAMS: * const uint8_t ch - the next character to analyze. * ImapPafData *pfdata - the struct containing all imap paf information */ static inline void init_command_search(const uint8_t ch, ImapPafData* pfdata) { switch (ch) { case 'F': case 'f': // may be a FETCH response pfdata->imap_data_info.next_letter = &(imap_resps[RESP_FETCH].name[1]); break; default: // this is not a data command. Search for regular end of line. pfdata->imap_state = IMAP_PAF_REG_STATE; } } /* * Confirms every character in the current sequence is part of the expected * command. After confirmation is complete, IMAP PAF will begin searching * for data. If any character is unexpected, searches for the default * termination sequence. * * PARAMS: * const uint8_t ch - the next character to analyze. * ImapPafData *pfdata - the struct containing all imap paf information */ static inline void parse_command(const uint8_t ch, ImapPafData* pfdata) { char val = *(pfdata->imap_data_info.next_letter); if (val == '\0' && isblank(ch)) pfdata->imap_state = IMAP_PAF_DATA_HEAD_STATE; else if (toupper(ch) == toupper(val)) pfdata->imap_data_info.next_letter++; else pfdata->imap_state = IMAP_PAF_REG_STATE; } /* * Wrapper function for the command parser. Determines whether this is the * first letter being processed and calls the appropriate processing * function. * * PARAMS: * const uint8_t ch - the next character to analyze. * ImapPafData *pfdata - the struct containing all imap paf information */ static inline void process_command(const uint8_t ch, ImapPafData* pfdata) { if (pfdata->imap_data_info.next_letter) parse_command(ch, pfdata); else init_command_search(ch, pfdata); } /* * This function only does something when the character is a blank or a CR/LF. * In those specific cases, this function will set the appropriate next * state information * * PARAMS: * const uint8_t ch - the next character to analyze. * ImapPafData *pfdata - the struct containing all imap paf information * ImapPafData base_state - if a space is not found, revert to this state * ImapPafData next_state - if a space is found, go to this state * RETURNS: * true - if the status has been eaten * false - if a CR or LF has been found */ static inline void eat_character(const uint8_t ch, ImapPafData* pfdata, ImapPafState base_state, ImapPafState next_state) { switch (ch) { case ' ': case '\t': pfdata->imap_state = next_state; break; case '\r': case '\n': pfdata->imap_state = base_state; break; } } /* * defined above in the eat_character function * * Keeping the next two functions to ease any future development * where these cases will no longer be simple or identical */ static inline void eat_second_argument(const uint8_t ch, ImapPafData* pfdata) { eat_character(ch, pfdata, IMAP_PAF_REG_STATE, IMAP_PAF_CMD_SEARCH); } /* explanation in 'eat_second_argument' above */ static inline void eat_response_identifier(const uint8_t ch, ImapPafData* pfdata) { eat_character(ch, pfdata, IMAP_PAF_REG_STATE, IMAP_PAF_CMD_STATUS); } /* * Analyzes the current data for a correct flush point. Flushes when * a command is complete or a MIME boundary is found. * * PARAMS: * ImapPafData *pfdata - ImapPaf state tracking structure * const uint8_t *data - payload data to inspect * uint32_t len - length of payload data * uint32_t * fp- pointer to set flush point * * RETURNS: * StreamSplitter::Status - StreamSplitter::FLUSH if flush point found, * StreamSplitter::SEARCH otherwise */ static StreamSplitter::Status imap_paf_server(ImapPafData* pfdata, const uint8_t* data, uint32_t len, uint32_t* fp) { uint32_t i; uint32_t flush_len = 0; uint32_t boundary_start = 0; pfdata->end_of_data = false; for (i = 0; i < len; i++) { uint8_t ch = data[i]; switch (pfdata->imap_state) { case IMAP_PAF_CMD_IDENTIFIER: // can be '+', '*', or a tag if (is_untagged(ch)) { // continue checking for fetch command pfdata->imap_state = IMAP_PAF_CMD_TAG; } else { // end of a command. flush at end of line. pfdata->imap_state = IMAP_PAF_FLUSH_STATE; } break; case IMAP_PAF_CMD_TAG: eat_response_identifier(ch, pfdata); break; case IMAP_PAF_CMD_STATUS: // can be a command name, msg sequence number, msg count, etc... // since we are only interested in fetch, eat this argument eat_second_argument(ch, pfdata); break; case IMAP_PAF_CMD_SEARCH: process_command(ch, pfdata); find_data_end_single_line(ch, pfdata); break; case IMAP_PAF_REG_STATE: find_data_end_single_line(ch, pfdata); // data reset when end of line hit break; case IMAP_PAF_DATA_HEAD_STATE: parse_fetch_header(ch, pfdata); // function will change state break; case IMAP_PAF_DATA_LEN_STATE: if (parse_literal_length(ch, &(pfdata->imap_data_info.length))) { pfdata->imap_state = IMAP_PAF_DATA_HEAD_STATE; } break; case IMAP_PAF_DATA_STATE: if (find_data_end_mime_data(ch, pfdata)) { // if not a boundary, wait for end of // the server's response before flushing if (pfdata->imap_state == IMAP_PAF_DATA_STATE) { *fp = i + 1; return StreamSplitter::FLUSH; } } if (pfdata->mime_info.boundary_state == MIME_PAF_BOUNDARY_UNKNOWN) boundary_start = i; break; case IMAP_PAF_FLUSH_STATE: if (find_data_end_single_line(ch, pfdata)) { flush_len = i +1; } break; } } if (flush_len) { DEBUG_WRAP(DebugMessage(DEBUG_IMAP, "IMAP PAF: flushing data!\n"); ); // flush at the final termination sequence *fp = flush_len; return StreamSplitter::FLUSH; } if ( scanning_boundary(&pfdata->mime_info, boundary_start, fp) ) return StreamSplitter::LIMIT; return StreamSplitter::SEARCH; } /* * Searches through the current data for a LF. All client * commands end with this termination sequence * * PARAMS: * ImapPafData *pfdata - ImapPaf state tracking structure * const uint8_t *data - payload data to inspect * uint32_t len - length of payload data * uint32_t * fp- pointer to set flush point * * RETURNS: * StreamSplitter::Status - StreamSplitter::FLUSH if flush point found, * StreamSplitter::SEARCH otherwise */ static StreamSplitter::Status imap_paf_client(const uint8_t* data, uint32_t len, uint32_t* fp) { const char* pch; pch = (char *)memchr (data, '\n', len); if (pch != NULL) { DEBUG_WRAP(DebugMessage(DEBUG_IMAP, "IMAP PAF: Flushing client" " data!\n"); ); *fp = (uint32_t)(pch - (const char*)data) + 1; return StreamSplitter::FLUSH; } return StreamSplitter::SEARCH; } //-------------------------------------------------------------------- // callback for stateful scanning of in-order raw payload //-------------------------------------------------------------------- ImapSplitter::ImapSplitter(bool c2s) : StreamSplitter(c2s) { memset(&state, 0, sizeof(state)); reset_data_states(&state); } ImapSplitter::~ImapSplitter() { } /* Function: imap_paf() Purpose: IMAP PAF callback. Inspects imap traffic. Checks client traffic for the current command and sets correct server termination sequence. Client side data will flush after receiving CRLF ("\r\n"). Server data flushes after finding set termination sequence. Arguments: void * - stream5 session pointer void ** - IMAP state tracking structure const uint8_t * - payload data to inspect uint32_t - length of payload data uint32_t - flags to check whether client or server uint32_t * - pointer to set flush point Returns: StreamSplitter::Status - StreamSplitter::FLUSH if flush point found, StreamSplitter::SEARCH otherwise */ StreamSplitter::Status ImapSplitter::scan( Flow* , const uint8_t* data, uint32_t len, uint32_t flags, uint32_t* fp) { ImapPafData* pfdata = &state; if (flags & PKT_FROM_SERVER) { DEBUG_WRAP(DebugMessage(DEBUG_IMAP, "PAF: From server.\n"); ); return imap_paf_server(pfdata, data, len, fp); } else { DEBUG_WRAP(DebugMessage(DEBUG_IMAP, "PAF: From client.\n"); ); return imap_paf_client(data, len, fp); } } bool imap_is_data_end(void* session) { Flow* ssn = (Flow*)session; ImapPafData* s = get_state(ssn, true); return s->end_of_data; }
wkitty42/snort3
src/service_inspectors/imap/imap_paf.cc
C++
gpl-2.0
15,135
/* Copyright (c) 2008-2011, Code Aurora Forum. 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. * * 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/fb.h> #include <linux/file.h> #include <linux/fs.h> #include <linux/debugfs.h> #include <linux/uaccess.h> #include <linux/interrupt.h> #include <linux/workqueue.h> #include <linux/android_pmem.h> #include <linux/vmalloc.h> #include <linux/pm_runtime.h> #include <linux/genlock.h> #include <linux/ashmem.h> #include <linux/major.h> #include "kgsl.h" #include "kgsl_debugfs.h" #include "kgsl_cffdump.h" #include "adreno_ringbuffer.h" #undef MODULE_PARAM_PREFIX #define MODULE_PARAM_PREFIX "kgsl." int kgsl_pagetable_count = KGSL_PAGETABLE_COUNT; module_param_named(ptcount, kgsl_pagetable_count, int, 0); MODULE_PARM_DESC(kgsl_pagetable_count, "Minimum number of pagetables for KGSL to allocate at initialization time"); #ifdef CONFIG_GENLOCK /** * kgsl_add_event - Add a new timstamp event for the KGSL device * @device - KGSL device for the new event * @ts - the timestamp to trigger the event on * @cb - callback function to call when the timestamp expires * @priv - private data for the specific event type * * @returns - 0 on success or error code on failure */ static int kgsl_add_event(struct kgsl_device *device, u32 ts, void (*cb)(struct kgsl_device *, void *, u32), void *priv) { struct kgsl_event *event; struct list_head *n; /* FIXME unsigned int cur = device->ftbl->readtimestamp(device, */ unsigned int cur = device->ftbl.device_readtimestamp(device, KGSL_TIMESTAMP_RETIRED); if (cb == NULL) return -EINVAL; /* Check to see if the requested timestamp has already fired */ if (timestamp_cmp(cur, ts) >= 0) { cb(device, priv, cur); return 0; } event = kzalloc(sizeof(*event), GFP_KERNEL); if (event == NULL) return -ENOMEM; event->timestamp = ts; event->priv = priv; event->func = cb; /* Add the event in order to the list */ for (n = device->events.next ; n != &device->events; n = n->next) { struct kgsl_event *e = list_entry(n, struct kgsl_event, list); if (timestamp_cmp(e->timestamp, ts) > 0) { list_add(&event->list, n->prev); break; } } if (n == &device->events) list_add_tail(&event->list, &device->events); return 0; } #endif static inline struct kgsl_mem_entry * kgsl_mem_entry_create(void) { struct kgsl_mem_entry *entry = kzalloc(sizeof(*entry), GFP_KERNEL); if (!entry) KGSL_CORE_ERR("kzalloc(%d) failed\n", sizeof(*entry)); else kref_init(&entry->refcount); return entry; } void kgsl_mem_entry_destroy(struct kref *kref) { struct kgsl_mem_entry *entry = container_of(kref, struct kgsl_mem_entry, refcount); size_t size = entry->memdesc.size; kgsl_sharedmem_free(&entry->memdesc); if (entry->memtype == KGSL_VMALLOC_MEMORY) entry->priv->stats.vmalloc -= size; else { if (entry->file_ptr) fput(entry->file_ptr); entry->priv->stats.exmem -= size; } kfree(entry); } EXPORT_SYMBOL(kgsl_mem_entry_destroy); static void kgsl_mem_entry_attach_process(struct kgsl_mem_entry *entry, struct kgsl_process_private *process) { spin_lock(&process->mem_lock); list_add(&entry->list, &process->mem_list); spin_unlock(&process->mem_lock); entry->priv = process; } /* Allocate a new context id */ static struct kgsl_context * kgsl_create_context(struct kgsl_device_private *dev_priv) { struct kgsl_context *context; int ret, id; context = kzalloc(sizeof(*context), GFP_KERNEL); if (context == NULL) return NULL; while (1) { if (idr_pre_get(&dev_priv->device->context_idr, GFP_KERNEL) == 0) { kfree(context); return NULL; } ret = idr_get_new(&dev_priv->device->context_idr, context, &id); if (ret != -EAGAIN) break; } if (ret) { kfree(context); return NULL; } context->id = id; context->dev_priv = dev_priv; return context; } static void kgsl_destroy_context(struct kgsl_device_private *dev_priv, struct kgsl_context *context) { int id; if (context == NULL) return; /* Fire a bug if the devctxt hasn't been freed */ BUG_ON(context->devctxt); id = context->id; kfree(context); idr_remove(&dev_priv->device->context_idr, id); } /* to be called when a process is destroyed, this walks the memqueue and * frees any entryies that belong to the dying process */ static void kgsl_memqueue_cleanup(struct kgsl_device *device, struct kgsl_process_private *private) { struct kgsl_mem_entry *entry, *entry_tmp; if (!private) return; BUG_ON(!mutex_is_locked(&device->mutex)); list_for_each_entry_safe(entry, entry_tmp, &device->memqueue, list) { if (entry->priv == private) { list_del(&entry->list); kgsl_mem_entry_put(entry); } } } static void kgsl_memqueue_freememontimestamp(struct kgsl_device *device, struct kgsl_mem_entry *entry, uint32_t timestamp, enum kgsl_timestamp_type type) { BUG_ON(!mutex_is_locked(&device->mutex)); entry->free_timestamp = timestamp; list_add_tail(&entry->list, &device->memqueue); } static void kgsl_memqueue_drain(struct kgsl_device *device) { struct kgsl_mem_entry *entry, *entry_tmp; uint32_t ts_processed; BUG_ON(!mutex_is_locked(&device->mutex)); /* get current EOP timestamp */ ts_processed = device->ftbl.device_readtimestamp( device, KGSL_TIMESTAMP_RETIRED); list_for_each_entry_safe(entry, entry_tmp, &device->memqueue, list) { KGSL_MEM_INFO(device, "ts_processed %d ts_free %d gpuaddr %x)\n", ts_processed, entry->free_timestamp, entry->memdesc.gpuaddr); if (!timestamp_cmp(ts_processed, entry->free_timestamp)) break; list_del(&entry->list); kgsl_mem_entry_put(entry); } } static void kgsl_memqueue_drain_unlocked(struct kgsl_device *device) { mutex_lock(&device->mutex); kgsl_check_suspended(device); kgsl_memqueue_drain(device); mutex_unlock(&device->mutex); } static void kgsl_check_idle_locked(struct kgsl_device *device) { if (device->pwrctrl.nap_allowed == true && device->state == KGSL_STATE_ACTIVE && device->requested_state == KGSL_STATE_NONE) { device->requested_state = KGSL_STATE_NAP; if (kgsl_pwrctrl_sleep(device) != 0) mod_timer(&device->idle_timer, jiffies + device->pwrctrl.interval_timeout); } } static void kgsl_check_idle(struct kgsl_device *device) { mutex_lock(&device->mutex); kgsl_check_idle_locked(device); mutex_unlock(&device->mutex); } struct kgsl_device *kgsl_get_device(int dev_idx) { int i; struct kgsl_device *ret = NULL; mutex_lock(&kgsl_driver.devlock); for (i = 0; i < KGSL_DEVICE_MAX; i++) { if (kgsl_driver.devp[i] && kgsl_driver.devp[i]->id == dev_idx) { ret = kgsl_driver.devp[i]; break; } } mutex_unlock(&kgsl_driver.devlock); return ret; } EXPORT_SYMBOL(kgsl_get_device); static struct kgsl_device *kgsl_get_minor(int minor) { struct kgsl_device *ret = NULL; if (minor < 0 || minor >= KGSL_DEVICE_MAX) return NULL; mutex_lock(&kgsl_driver.devlock); ret = kgsl_driver.devp[minor]; mutex_unlock(&kgsl_driver.devlock); return ret; } int kgsl_register_ts_notifier(struct kgsl_device *device, struct notifier_block *nb) { BUG_ON(device == NULL); return atomic_notifier_chain_register(&device->ts_notifier_list, nb); } EXPORT_SYMBOL(kgsl_register_ts_notifier); int kgsl_unregister_ts_notifier(struct kgsl_device *device, struct notifier_block *nb) { BUG_ON(device == NULL); return atomic_notifier_chain_unregister(&device->ts_notifier_list, nb); } EXPORT_SYMBOL(kgsl_unregister_ts_notifier); int kgsl_check_timestamp(struct kgsl_device *device, unsigned int timestamp) { unsigned int ts_processed; BUG_ON(device->ftbl.device_readtimestamp == NULL); ts_processed = device->ftbl.device_readtimestamp( device, KGSL_TIMESTAMP_RETIRED); return timestamp_cmp(ts_processed, timestamp); } EXPORT_SYMBOL(kgsl_check_timestamp); int kgsl_setstate(struct kgsl_device *device, uint32_t flags) { int status = -ENXIO; if (flags && device->ftbl.device_setstate) { status = device->ftbl.device_setstate(device, flags); } else status = 0; return status; } EXPORT_SYMBOL(kgsl_setstate); int kgsl_idle(struct kgsl_device *device, unsigned int timeout) { int status = -ENXIO; if (device->ftbl.device_idle) status = device->ftbl.device_idle(device, timeout); return status; } EXPORT_SYMBOL(kgsl_idle); static int kgsl_suspend_device(struct kgsl_device *device, pm_message_t state) { int status = -EINVAL; unsigned int nap_allowed_saved; if (!device) return -EINVAL; KGSL_PWR_WARN(device, "suspend start\n"); mutex_lock(&device->mutex); nap_allowed_saved = device->pwrctrl.nap_allowed; device->pwrctrl.nap_allowed = false; device->requested_state = KGSL_STATE_SUSPEND; /* Make sure no user process is waiting for a timestamp * * before supending */ if (device->active_cnt != 0) { mutex_unlock(&device->mutex); wait_for_completion(&device->suspend_gate); mutex_lock(&device->mutex); } /* Don't let the timer wake us during suspended sleep. */ del_timer(&device->idle_timer); switch (device->state) { case KGSL_STATE_INIT: break; case KGSL_STATE_ACTIVE: /* Wait for the device to become idle */ device->ftbl.device_idle(device, KGSL_TIMEOUT_DEFAULT); case KGSL_STATE_NAP: case KGSL_STATE_SLEEP: /* Get the completion ready to be waited upon. */ INIT_COMPLETION(device->hwaccess_gate); device->ftbl.device_suspend_context(device); device->ftbl.device_stop(device); device->state = KGSL_STATE_SUSPEND; KGSL_PWR_WARN(device, "state -> SUSPEND, device %d\n", device->id); break; default: KGSL_PWR_ERR(device, "suspend fail, device %d state(%x)\n", device->id, device->state); goto end; } device->requested_state = KGSL_STATE_NONE; device->pwrctrl.nap_allowed = nap_allowed_saved; status = 0; end: mutex_unlock(&device->mutex); KGSL_PWR_WARN(device, "suspend end\n"); return status; } static int kgsl_resume_device(struct kgsl_device *device) { int status = -EINVAL; if (!device) return -EINVAL; KGSL_PWR_WARN(device, "resume start\n"); mutex_lock(&device->mutex); if (device->state == KGSL_STATE_SUSPEND) { device->requested_state = KGSL_STATE_ACTIVE; status = device->ftbl.device_start(device, 0); if (status == 0) { device->state = KGSL_STATE_ACTIVE; KGSL_PWR_WARN(device, "state -> ACTIVE, device %d\n", device->id); } else { KGSL_PWR_ERR(device, "resume failed, device %d\n", device->id); device->state = KGSL_STATE_INIT; goto end; } status = device->ftbl.device_resume_context(device); complete_all(&device->hwaccess_gate); } device->requested_state = KGSL_STATE_NONE; end: mutex_unlock(&device->mutex); KGSL_PWR_WARN(device, "resume end\n"); return status; } static int kgsl_suspend(struct device *dev) { pm_message_t arg = {0}; struct kgsl_device *device = dev_get_drvdata(dev); return kgsl_suspend_device(device, arg); } static int kgsl_resume(struct device *dev) { struct kgsl_device *device = dev_get_drvdata(dev); return kgsl_resume_device(device); } static int kgsl_runtime_suspend(struct device *dev) { return 0; } static int kgsl_runtime_resume(struct device *dev) { return 0; } const struct dev_pm_ops kgsl_pm_ops = { .suspend = kgsl_suspend, .resume = kgsl_resume, .runtime_suspend = kgsl_runtime_suspend, .runtime_resume = kgsl_runtime_resume, }; EXPORT_SYMBOL(kgsl_pm_ops); int kgsl_suspend_driver(struct platform_device *pdev, pm_message_t state) { struct kgsl_device *device = dev_get_drvdata(&pdev->dev); return kgsl_suspend_device(device, state); } EXPORT_SYMBOL(kgsl_suspend_driver); int kgsl_resume_driver(struct platform_device *pdev) { struct kgsl_device *device = dev_get_drvdata(&pdev->dev); return kgsl_resume_device(device); } EXPORT_SYMBOL(kgsl_resume_driver); /* file operations */ static struct kgsl_process_private * kgsl_get_process_private(struct kgsl_device_private *cur_dev_priv) { struct kgsl_process_private *private; mutex_lock(&kgsl_driver.process_mutex); list_for_each_entry(private, &kgsl_driver.process_list, list) { if (private->pid == task_tgid_nr(current)) { private->refcnt++; goto out; } } /* no existing process private found for this dev_priv, create one */ private = kzalloc(sizeof(struct kgsl_process_private), GFP_KERNEL); if (private == NULL) { KGSL_DRV_ERR(cur_dev_priv->device, "kzalloc(%d) failed\n", sizeof(struct kgsl_process_private)); goto out; } spin_lock_init(&private->mem_lock); private->refcnt = 1; private->pid = task_tgid_nr(current); INIT_LIST_HEAD(&private->mem_list); #ifdef CONFIG_MSM_KGSL_MMU { unsigned long pt_name; #ifdef CONFIG_KGSL_PER_PROCESS_PAGE_TABLE pt_name = task_tgid_nr(current); #else pt_name = KGSL_MMU_GLOBAL_PT; #endif private->pagetable = kgsl_mmu_getpagetable(pt_name); if (private->pagetable == NULL) { kfree(private); private = NULL; goto out; } } #endif list_add(&private->list, &kgsl_driver.process_list); kgsl_process_init_sysfs(private); out: mutex_unlock(&kgsl_driver.process_mutex); return private; } static void kgsl_put_process_private(struct kgsl_device *device, struct kgsl_process_private *private) { struct kgsl_mem_entry *entry = NULL; struct kgsl_mem_entry *entry_tmp = NULL; if (!private) return; mutex_lock(&kgsl_driver.process_mutex); if (--private->refcnt) goto unlock; KGSL_MEM_INFO(device, "Memory usage: vmalloc (%d/%d) exmem (%d/%d)\n", private->stats.vmalloc, private->stats.vmalloc_max, private->stats.exmem, private->stats.exmem_max); kgsl_process_uninit_sysfs(private); list_del(&private->list); list_for_each_entry_safe(entry, entry_tmp, &private->mem_list, list) { list_del(&entry->list); kgsl_mem_entry_put(entry); } kgsl_mmu_putpagetable(private->pagetable); kfree(private); unlock: mutex_unlock(&kgsl_driver.process_mutex); } static int kgsl_release(struct inode *inodep, struct file *filep) { int result = 0; struct kgsl_device_private *dev_priv = NULL; struct kgsl_process_private *private = NULL; struct kgsl_device *device; struct kgsl_context *context; int next = 0; device = kgsl_driver.devp[iminor(inodep)]; BUG_ON(device == NULL); dev_priv = (struct kgsl_device_private *) filep->private_data; BUG_ON(dev_priv == NULL); BUG_ON(device != dev_priv->device); /* private could be null if kgsl_open is not successful */ private = dev_priv->process_priv; filep->private_data = NULL; mutex_lock(&device->mutex); kgsl_check_suspended(device); while (1) { context = idr_get_next(&dev_priv->device->context_idr, &next); if (context == NULL) break; if (context->dev_priv == dev_priv) { device->ftbl.device_drawctxt_destroy(device, context); kgsl_destroy_context(dev_priv, context); } next = next + 1; } device->open_count--; if (device->open_count == 0) { result = device->ftbl.device_stop(device); device->state = KGSL_STATE_INIT; KGSL_PWR_WARN(device, "state -> INIT, device %d\n", device->id); } /* clean up any to-be-freed entries that belong to this * process and this device */ kgsl_memqueue_cleanup(device, private); mutex_unlock(&device->mutex); kfree(dev_priv); kgsl_put_process_private(device, private); pm_runtime_put(&device->pdev->dev); return result; } static int kgsl_open(struct inode *inodep, struct file *filep) { int result; struct kgsl_device_private *dev_priv; struct kgsl_device *device; unsigned int minor = iminor(inodep); struct device *dev; device = kgsl_get_minor(minor); BUG_ON(device == NULL); if (filep->f_flags & O_EXCL) { KGSL_DRV_ERR(device, "O_EXCL not allowed\n"); return -EBUSY; } dev = &device->pdev->dev; result = pm_runtime_get_sync(dev); if (result < 0) { KGSL_DRV_ERR(device, "Runtime PM: Unable to wake up the device, rc = %d\n", result); return result; } result = 0; dev_priv = kzalloc(sizeof(struct kgsl_device_private), GFP_KERNEL); if (dev_priv == NULL) { KGSL_DRV_ERR(device, "kzalloc failed(%d)\n", sizeof(struct kgsl_device_private)); result = -ENOMEM; goto err_pmruntime; } dev_priv->device = device; filep->private_data = dev_priv; /* Get file (per process) private struct */ dev_priv->process_priv = kgsl_get_process_private(dev_priv); if (dev_priv->process_priv == NULL) { result = -ENOMEM; goto err_freedevpriv; } mutex_lock(&device->mutex); kgsl_check_suspended(device); if (device->open_count == 0) { result = device->ftbl.device_start(device, true); if (result) { mutex_unlock(&device->mutex); goto err_putprocess; } device->state = KGSL_STATE_ACTIVE; KGSL_PWR_WARN(device, "state -> ACTIVE, device %d\n", minor); } device->open_count++; mutex_unlock(&device->mutex); KGSL_DRV_INFO(device, "Initialized %s: mmu=%s pagetable_count=%d\n", device->name, kgsl_mmu_enabled() ? "on" : "off", KGSL_PAGETABLE_COUNT); return result; err_putprocess: kgsl_put_process_private(device, dev_priv->process_priv); err_freedevpriv: filep->private_data = NULL; kfree(dev_priv); err_pmruntime: pm_runtime_put(&device->pdev->dev); return result; } /*call with private->mem_lock locked */ static struct kgsl_mem_entry * kgsl_sharedmem_find(struct kgsl_process_private *private, unsigned int gpuaddr) { struct kgsl_mem_entry *entry = NULL, *result = NULL; BUG_ON(private == NULL); gpuaddr &= PAGE_MASK; list_for_each_entry(entry, &private->mem_list, list) { if (entry->memdesc.gpuaddr == gpuaddr) { result = entry; break; } } return result; } /*call with private->mem_lock locked */ struct kgsl_mem_entry * kgsl_sharedmem_find_region(struct kgsl_process_private *private, unsigned int gpuaddr, size_t size) { struct kgsl_mem_entry *entry = NULL, *result = NULL; BUG_ON(private == NULL); list_for_each_entry(entry, &private->mem_list, list) { if (gpuaddr >= entry->memdesc.gpuaddr && ((gpuaddr + size) <= (entry->memdesc.gpuaddr + entry->memdesc.size))) { result = entry; break; } } return result; } EXPORT_SYMBOL(kgsl_gpuaddr_to_vaddr); uint8_t *kgsl_gpuaddr_to_vaddr(const struct kgsl_memdesc *memdesc, unsigned int gpuaddr, unsigned int *size) { BUG_ON(memdesc->hostptr == NULL); if (memdesc->gpuaddr == 0 || (gpuaddr < memdesc->gpuaddr || gpuaddr >= memdesc->gpuaddr + memdesc->size)) return NULL; *size = memdesc->size - (memdesc->gpuaddr - gpuaddr); return memdesc->hostptr + (memdesc->gpuaddr - gpuaddr); } /*call all ioctl sub functions with driver locked*/ static long kgsl_ioctl_device_getproperty(struct kgsl_device_private *dev_priv, unsigned int cmd, void *data) { int result = 0; struct kgsl_device_getproperty *param = data; switch (param->type) { case KGSL_PROP_VERSION: { struct kgsl_version version; if (param->sizebytes != sizeof(version)) { result = -EINVAL; break; } version.drv_major = KGSL_VERSION_MAJOR; version.drv_minor = KGSL_VERSION_MINOR; version.dev_major = dev_priv->device->ver_major; version.dev_minor = dev_priv->device->ver_minor; if (copy_to_user(param->value, &version, sizeof(version))) result = -EFAULT; break; } default: result = dev_priv->device->ftbl.device_getproperty( dev_priv->device, param->type, param->value, param->sizebytes); } return result; } static long kgsl_ioctl_device_waittimestamp(struct kgsl_device_private *dev_priv, unsigned int cmd, void *data) { int result = 0; struct kgsl_device_waittimestamp *param = data; /* Set the active count so that suspend doesn't do the wrong thing */ dev_priv->device->active_cnt++; /* Don't wait forever, set a max value for now */ if (param->timeout == -1) param->timeout = 10 * MSEC_PER_SEC; result = dev_priv->device->ftbl.device_waittimestamp(dev_priv->device, param->timestamp, param->timeout); kgsl_memqueue_drain(dev_priv->device); /* Fire off any pending suspend operations that are in flight */ INIT_COMPLETION(dev_priv->device->suspend_gate); dev_priv->device->active_cnt--; complete(&dev_priv->device->suspend_gate); return result; } static bool check_ibdesc(struct kgsl_device_private *dev_priv, struct kgsl_ibdesc *ibdesc, unsigned int numibs, bool parse) { bool result = true; unsigned int i; for (i = 0; i < numibs; i++) { struct kgsl_mem_entry *entry; spin_lock(&dev_priv->process_priv->mem_lock); entry = kgsl_sharedmem_find_region(dev_priv->process_priv, ibdesc[i].gpuaddr, ibdesc[i].sizedwords * sizeof(uint)); spin_unlock(&dev_priv->process_priv->mem_lock); if (entry == NULL) { KGSL_DRV_ERR(dev_priv->device, "invalid cmd buffer gpuaddr %08x " \ "sizedwords %d\n", ibdesc[i].gpuaddr, ibdesc[i].sizedwords); result = false; break; } if (parse && !kgsl_cffdump_parse_ibs(dev_priv, &entry->memdesc, ibdesc[i].gpuaddr, ibdesc[i].sizedwords, true)) { KGSL_DRV_ERR(dev_priv->device, "invalid cmd buffer gpuaddr %08x " \ "sizedwords %d numibs %d/%d\n", ibdesc[i].gpuaddr, ibdesc[i].sizedwords, i+1, numibs); result = false; break; } } return result; } static long kgsl_ioctl_rb_issueibcmds(struct kgsl_device_private *dev_priv, unsigned int cmd, void *data) { int result = 0; struct kgsl_ringbuffer_issueibcmds *param = data; struct kgsl_ibdesc *ibdesc; struct kgsl_context *context; #ifdef CONFIG_MSM_KGSL_DRM kgsl_gpu_mem_flush(DRM_KGSL_GEM_CACHE_OP_TO_DEV); #endif context = kgsl_find_context(dev_priv, param->drawctxt_id); if (context == NULL) { result = -EINVAL; KGSL_DRV_ERR(dev_priv->device, "invalid drawctxt drawctxt_id %d\n", param->drawctxt_id); goto done; } if (param->flags & KGSL_CONTEXT_SUBMIT_IB_LIST) { KGSL_DRV_INFO(dev_priv->device, "Using IB list mode for ib submission, numibs: %d\n", param->numibs); if (!param->numibs) { KGSL_DRV_ERR(dev_priv->device, "Invalid numibs as parameter: %d\n", param->numibs); result = -EINVAL; goto done; } ibdesc = kzalloc(sizeof(struct kgsl_ibdesc) * param->numibs, GFP_KERNEL); if (!ibdesc) { KGSL_MEM_ERR(dev_priv->device, "kzalloc(%d) failed\n", sizeof(struct kgsl_ibdesc) * param->numibs); result = -ENOMEM; goto done; } if (copy_from_user(ibdesc, (void *)param->ibdesc_addr, sizeof(struct kgsl_ibdesc) * param->numibs)) { result = -EFAULT; KGSL_DRV_ERR(dev_priv->device, "copy_from_user failed\n"); goto free_ibdesc; } } else { KGSL_DRV_INFO(dev_priv->device, "Using single IB submission mode for ib submission\n"); /* If user space driver is still using the old mode of * submitting single ib then we need to support that as well */ ibdesc = kzalloc(sizeof(struct kgsl_ibdesc), GFP_KERNEL); if (!ibdesc) { KGSL_MEM_ERR(dev_priv->device, "kzalloc(%d) failed\n", sizeof(struct kgsl_ibdesc)); result = -ENOMEM; goto done; } ibdesc[0].gpuaddr = param->ibdesc_addr; ibdesc[0].sizedwords = param->numibs; param->numibs = 1; } if (!check_ibdesc(dev_priv, ibdesc, param->numibs, true)) { KGSL_DRV_ERR(dev_priv->device, "bad ibdesc"); result = -EINVAL; goto free_ibdesc; } result = dev_priv->device->ftbl.device_issueibcmds(dev_priv, context, ibdesc, param->numibs, &param->timestamp, param->flags); if (result != 0) goto free_ibdesc; /* this is a check to try to detect if a command buffer was freed * during issueibcmds(). */ if (!check_ibdesc(dev_priv, ibdesc, param->numibs, false)) { KGSL_DRV_ERR(dev_priv->device, "bad ibdesc AFTER issue"); result = -EINVAL; goto free_ibdesc; } free_ibdesc: kfree(ibdesc); done: #ifdef CONFIG_MSM_KGSL_DRM kgsl_gpu_mem_flush(DRM_KGSL_GEM_CACHE_OP_FROM_DEV); #endif return result; } static long kgsl_ioctl_cmdstream_readtimestamp(struct kgsl_device_private *dev_priv, unsigned int cmd, void *data) { struct kgsl_cmdstream_readtimestamp *param = data; param->timestamp = dev_priv->device->ftbl.device_readtimestamp( dev_priv->device, param->type); return 0; } static long kgsl_ioctl_cmdstream_freememontimestamp(struct kgsl_device_private *dev_priv, unsigned int cmd, void *data) { int result = 0; struct kgsl_cmdstream_freememontimestamp *param = data; struct kgsl_mem_entry *entry = NULL; spin_lock(&dev_priv->process_priv->mem_lock); entry = kgsl_sharedmem_find(dev_priv->process_priv, param->gpuaddr); if (entry) list_del(&entry->list); spin_unlock(&dev_priv->process_priv->mem_lock); if (entry) { kgsl_memqueue_freememontimestamp(dev_priv->device, entry, param->timestamp, param->type); kgsl_memqueue_drain(dev_priv->device); } else { KGSL_DRV_ERR(dev_priv->device, "invalid gpuaddr %08x\n", param->gpuaddr); result = -EINVAL; } return result; } static long kgsl_ioctl_drawctxt_create(struct kgsl_device_private *dev_priv, unsigned int cmd, void *data) { int result = 0; struct kgsl_drawctxt_create *param = data; struct kgsl_context *context = NULL; context = kgsl_create_context(dev_priv); if (context == NULL) { result = -ENOMEM; goto done; } if (dev_priv->device->ftbl.device_drawctxt_create != NULL) result = dev_priv->device->ftbl.device_drawctxt_create(dev_priv, param->flags, context); param->drawctxt_id = context->id; done: if (result && context) kgsl_destroy_context(dev_priv, context); return result; } static long kgsl_ioctl_drawctxt_destroy(struct kgsl_device_private *dev_priv, unsigned int cmd, void *data) { int result = 0; struct kgsl_drawctxt_destroy *param = data; struct kgsl_context *context; context = kgsl_find_context(dev_priv, param->drawctxt_id); if (context == NULL) { result = -EINVAL; goto done; } result = dev_priv->device->ftbl.device_drawctxt_destroy( dev_priv->device, context); kgsl_destroy_context(dev_priv, context); done: return result; } static long kgsl_ioctl_sharedmem_free(struct kgsl_device_private *dev_priv, unsigned int cmd, void *data) { int result = 0; struct kgsl_sharedmem_free *param = data; struct kgsl_process_private *private = dev_priv->process_priv; struct kgsl_mem_entry *entry = NULL; spin_lock(&private->mem_lock); entry = kgsl_sharedmem_find(private, param->gpuaddr); if (entry) list_del(&entry->list); spin_unlock(&private->mem_lock); if (entry) { kgsl_mem_entry_put(entry); } else { KGSL_CORE_ERR("invalid gpuaddr %08x\n", param->gpuaddr); result = -EINVAL; } return result; } static struct vm_area_struct *kgsl_get_vma_from_start_addr(unsigned int addr) { struct vm_area_struct *vma; int len; down_read(&current->mm->mmap_sem); vma = find_vma(current->mm, addr); up_read(&current->mm->mmap_sem); if (!vma) { KGSL_CORE_ERR("find_vma(%x) failed\n", addr); return NULL; } len = vma->vm_end - vma->vm_start; if (vma->vm_pgoff || !KGSL_IS_PAGE_ALIGNED(len) || !KGSL_IS_PAGE_ALIGNED(vma->vm_start)) { KGSL_CORE_ERR("address %x is not aligned\n", addr); return NULL; } if (vma->vm_start != addr) { KGSL_CORE_ERR("vma address does not match mmap address\n"); return NULL; } return vma; } static long kgsl_ioctl_sharedmem_from_vmalloc(struct kgsl_device_private *dev_priv, unsigned int cmd, void *data) { int result = 0, len = 0; struct kgsl_process_private *private = dev_priv->process_priv; struct kgsl_sharedmem_from_vmalloc *param = data; struct kgsl_mem_entry *entry = NULL; struct vm_area_struct *vma; if (!kgsl_mmu_enabled()) return -ENODEV; /* Make sure all pending freed memory is collected */ kgsl_memqueue_drain_unlocked(dev_priv->device); if (!param->hostptr) { KGSL_CORE_ERR("invalid hostptr %x\n", param->hostptr); result = -EINVAL; goto error; } vma = kgsl_get_vma_from_start_addr(param->hostptr); if (!vma) { result = -EINVAL; goto error; } len = vma->vm_end - vma->vm_start; if (len == 0) { KGSL_CORE_ERR("Invalid vma region length %d\n", len); result = -EINVAL; goto error; } entry = kgsl_mem_entry_create(); if (entry == NULL) { result = -ENOMEM; goto error; } result = kgsl_sharedmem_vmalloc_user(&entry->memdesc, private->pagetable, len, param->flags); if (result != 0) goto error_free_entry; vma->vm_page_prot = pgprot_writecombine(vma->vm_page_prot); result = remap_vmalloc_range(vma, (void *) entry->memdesc.hostptr, 0); if (result) { KGSL_CORE_ERR("remap_vmalloc_range failed: %d\n", result); goto error_free_vmalloc; } param->gpuaddr = entry->memdesc.gpuaddr; entry->memtype = KGSL_VMALLOC_MEMORY; kgsl_mem_entry_attach_process(entry, private); /* Process specific statistics */ KGSL_STATS_ADD(len, private->stats.vmalloc, private->stats.vmalloc_max); kgsl_check_idle(dev_priv->device); return 0; error_free_vmalloc: kgsl_sharedmem_free(&entry->memdesc); error_free_entry: kfree(entry); error: kgsl_check_idle(dev_priv->device); return result; } static int kgsl_get_phys_file(int fd, unsigned long *start, unsigned long *len, unsigned long *vstart, struct file **filep) { struct file *fbfile; int ret = 0; dev_t rdev; struct fb_info *info; *filep = NULL; if (!get_pmem_file(fd, start, vstart, len, filep)) return 0; fbfile = fget(fd); if (fbfile == NULL) { KGSL_CORE_ERR("fget_light failed\n"); return -1; } rdev = fbfile->f_dentry->d_inode->i_rdev; info = MAJOR(rdev) == FB_MAJOR ? registered_fb[MINOR(rdev)] : NULL; if (info) { *start = info->fix.smem_start; *len = info->fix.smem_len; *vstart = (unsigned long)__va(info->fix.smem_start); ret = 0; } else { KGSL_CORE_ERR("framebuffer minor %d not found\n", MINOR(rdev)); ret = -1; } fput(fbfile); return ret; } static inline int _check_region(unsigned long start, unsigned long size, uint64_t len) { uint64_t end = start + size; return (end > len); } #ifdef CONFIG_ANDROID_PMEM static int kgsl_setup_phys_file(struct kgsl_mem_entry *entry, struct kgsl_pagetable *pagetable, unsigned int fd, unsigned int offset, size_t size) { int ret; unsigned long phys, virt, len; struct file *filep; ret = kgsl_get_phys_file(fd, &phys, &len, &virt, &filep); if (ret) return ret; if (size == 0) size = len; /* Adjust the size of the region to account for the offset */ size += offset & ~PAGE_MASK; size = ALIGN(size, PAGE_SIZE); if (_check_region(offset & PAGE_MASK, size, len)) { KGSL_CORE_ERR("Offset (%ld) + size (%d) is larger" "than pmem region length %ld\n", offset & PAGE_MASK, size, len); put_pmem_file(filep); return -EINVAL; } entry->file_ptr = filep; entry->memdesc.pagetable = pagetable; entry->memdesc.size = size; entry->memdesc.physaddr = phys + (offset & PAGE_MASK); entry->memdesc.hostptr = (void *) (virt + (offset & PAGE_MASK)); entry->memdesc.ops = &kgsl_contig_ops; return 0; } #else static int kgsl_setup_phys_file(struct kgsl_mem_entry *entry, struct kgsl_pagetable *pagetable, unsigned int fd, unsigned int offset, size_t size) { return -EINVAL; } #endif static int kgsl_setup_hostptr(struct kgsl_mem_entry *entry, struct kgsl_pagetable *pagetable, void *hostptr, unsigned int offset, size_t size) { struct vm_area_struct *vma; unsigned int len; down_read(&current->mm->mmap_sem); vma = find_vma(current->mm, (unsigned int) hostptr); up_read(&current->mm->mmap_sem); if (!vma) { KGSL_CORE_ERR("find_vma(%p) failed\n", hostptr); return -EINVAL; } /* We don't necessarily start at vma->vm_start */ len = vma->vm_end - (unsigned long) hostptr; if (!KGSL_IS_PAGE_ALIGNED((unsigned long) hostptr) || !KGSL_IS_PAGE_ALIGNED(len)) { KGSL_CORE_ERR("user address len(%u)" "and start(%p) must be page" "aligned\n", len, hostptr); return -EINVAL; } if (size == 0) size = len; /* Adjust the size of the region to account for the offset */ size += offset & ~PAGE_MASK; size = ALIGN(size, PAGE_SIZE); if (_check_region(offset & PAGE_MASK, size, len)) { KGSL_CORE_ERR("Offset (%ld) + size (%d) is larger" "than region length %d\n", offset & PAGE_MASK, size, len); return -EINVAL; } entry->memdesc.pagetable = pagetable; entry->memdesc.size = size; entry->memdesc.hostptr = hostptr + (offset & PAGE_MASK); entry->memdesc.ops = &kgsl_userptr_ops; return 0; } #ifdef CONFIG_ASHMEM static int kgsl_setup_ashmem(struct kgsl_mem_entry *entry, struct kgsl_pagetable *pagetable, int fd, void *hostptr, size_t size) { int ret; struct vm_area_struct *vma; struct file *filep, *vmfile; unsigned long len; vma = kgsl_get_vma_from_start_addr((unsigned long) hostptr); if (vma == NULL) return -EINVAL; len = vma->vm_end - vma->vm_start; if (size == 0) size = len; if (size != len) { KGSL_CORE_ERR("Invalid size %d for vma region %p\n", size, hostptr); return -EINVAL; } ret = get_ashmem_file(fd, &filep, &vmfile, &len); if (ret) { KGSL_CORE_ERR("get_ashmem_file failed\n"); return ret; } if (vmfile != vma->vm_file) { KGSL_CORE_ERR("ashmem shmem file does not match vma\n"); ret = -EINVAL; goto err; } entry->file_ptr = filep; entry->memdesc.pagetable = pagetable; entry->memdesc.size = ALIGN(size, PAGE_SIZE); entry->memdesc.hostptr = hostptr; entry->memdesc.ops = &kgsl_userptr_ops; return 0; err: put_ashmem_file(filep); return ret; } #else static int kgsl_setup_ashmem(struct kgsl_mem_entry *entry, struct kgsl_pagetable *pagetable, int fd, void *hostptr, size_t size) { return -EINVAL; } #endif static long kgsl_ioctl_map_user_mem(struct kgsl_device_private *dev_priv, unsigned int cmd, void *data) { int result = -EINVAL; struct kgsl_map_user_mem *param = data; struct kgsl_mem_entry *entry = NULL; struct kgsl_process_private *private = dev_priv->process_priv; entry = kgsl_mem_entry_create(); if (entry == NULL) return -ENOMEM; kgsl_memqueue_drain_unlocked(dev_priv->device); switch (param->memtype) { case KGSL_USER_MEM_TYPE_PMEM: if (param->fd == 0 || param->len == 0) break; result = kgsl_setup_phys_file(entry, private->pagetable, param->fd, param->offset, param->len); break; case KGSL_USER_MEM_TYPE_ADDR: if (!kgsl_mmu_enabled()) { KGSL_DRV_ERR(dev_priv->device, "Cannot map paged memory with the " "MMU disabled\n"); break; } if (param->hostptr == 0) break; result = kgsl_setup_hostptr(entry, private->pagetable, (void *) param->hostptr, param->offset, param->len); break; case KGSL_USER_MEM_TYPE_ASHMEM: if (!kgsl_mmu_enabled()) { KGSL_DRV_ERR(dev_priv->device, "Cannot map paged memory with the " "MMU disabled\n"); break; } if (param->hostptr == 0) break; result = kgsl_setup_ashmem(entry, private->pagetable, param->fd, (void *) param->hostptr, param->len); break; default: KGSL_CORE_ERR("Invalid memory type: %x\n", param->memtype); break; } if (result) goto error; result = kgsl_mmu_map(private->pagetable, &entry->memdesc, GSL_PT_PAGE_RV | GSL_PT_PAGE_WV); if (result) goto error_put_file_ptr; /* Adjust the returned value for a non 4k aligned offset */ param->gpuaddr = entry->memdesc.gpuaddr + (param->offset & ~PAGE_MASK); entry->memtype = KGSL_EXTERNAL_MEMORY; /* Statistics */ KGSL_STATS_ADD(param->len, private->stats.exmem, private->stats.exmem_max); kgsl_mem_entry_attach_process(entry, private); kgsl_check_idle(dev_priv->device); return result; error_put_file_ptr: if (entry->file_ptr) fput(entry->file_ptr); error: kfree(entry); kgsl_check_idle(dev_priv->device); return result; } /*This function flushes a graphics memory allocation from CPU cache *when caching is enabled with MMU*/ static long kgsl_ioctl_sharedmem_flush_cache(struct kgsl_device_private *dev_priv, unsigned int cmd, void *data) { int result = 0; struct kgsl_mem_entry *entry; struct kgsl_sharedmem_free *param = data; struct kgsl_process_private *private = dev_priv->process_priv; spin_lock(&private->mem_lock); entry = kgsl_sharedmem_find(private, param->gpuaddr); if (!entry) { KGSL_CORE_ERR("invalid gpuaddr %08x\n", param->gpuaddr); result = -EINVAL; } else { if (!entry->memdesc.hostptr) entry->memdesc.hostptr = kgsl_gpuaddr_to_vaddr(&entry->memdesc, param->gpuaddr, &entry->memdesc.size); if (!entry->memdesc.hostptr) { KGSL_CORE_ERR("invalid hostptr with gpuaddr %08x\n", param->gpuaddr); goto done; } kgsl_cache_range_op(&entry->memdesc, KGSL_CACHE_OP_CLEAN); /* Statistics - keep track of how many flushes each process does */ private->stats.flushes++; } spin_unlock(&private->mem_lock); done: return result; } static long kgsl_ioctl_gpumem_alloc(struct kgsl_device_private *dev_priv, unsigned int cmd, void *data) { struct kgsl_process_private *private = dev_priv->process_priv; struct kgsl_gpumem_alloc *param = data; struct kgsl_mem_entry *entry; int result; entry = kgsl_mem_entry_create(); if (entry == NULL) return -ENOMEM; /* Make sure all pending freed memory is collected */ kgsl_memqueue_drain_unlocked(dev_priv->device); result = kgsl_allocate_user(&entry->memdesc, private->pagetable, param->size, param->flags); if (result == 0) { kgsl_mem_entry_attach_process(entry, private); param->gpuaddr = entry->memdesc.gpuaddr; } else kfree(entry); kgsl_check_idle(dev_priv->device); return result; } static long kgsl_ioctl_cff_syncmem(struct kgsl_device_private *dev_priv, unsigned int cmd, void *data) { int result = 0; struct kgsl_cff_syncmem *param = data; struct kgsl_process_private *private = dev_priv->process_priv; struct kgsl_mem_entry *entry = NULL; spin_lock(&private->mem_lock); entry = kgsl_sharedmem_find_region(private, param->gpuaddr, param->len); if (entry) kgsl_cffdump_syncmem(dev_priv, &entry->memdesc, param->gpuaddr, param->len, true); else result = -EINVAL; spin_unlock(&private->mem_lock); return result; } static long kgsl_ioctl_cff_user_event(struct kgsl_device_private *dev_priv, unsigned int cmd, void *data) { int result = 0; struct kgsl_cff_user_event *param = data; kgsl_cffdump_user_event(param->cff_opcode, param->op1, param->op2, param->op3, param->op4, param->op5); return result; } #ifdef CONFIG_GENLOCK struct kgsl_genlock_event_priv { struct genlock_handle *handle; struct genlock *lock; }; /** * kgsl_genlock_event_cb - Event callback for a genlock timestamp event * @device - The KGSL device that expired the timestamp * @priv - private data for the event * @timestamp - the timestamp that triggered the event * * Release a genlock lock following the expiration of a timestamp */ static void kgsl_genlock_event_cb(struct kgsl_device *device, void *priv, u32 timestamp) { struct kgsl_genlock_event_priv *ev = priv; int ret; ret = genlock_lock(ev->handle, GENLOCK_UNLOCK, 0, 0); if (ret) KGSL_CORE_ERR("Error while unlocking genlock: %d\n", ret); genlock_put_handle(ev->handle); kfree(ev); } /** * kgsl_add_genlock-event - Create a new genlock event * @device - KGSL device to create the event on * @timestamp - Timestamp to trigger the event * @data - User space buffer containing struct kgsl_genlock_event_priv * @len - length of the userspace buffer * @returns 0 on success or error code on error * * Attack to a genlock handle and register an event to release the * genlock lock when the timestamp expires */ static int kgsl_add_genlock_event(struct kgsl_device *device, u32 timestamp, void __user *data, int len) { struct kgsl_genlock_event_priv *event; struct kgsl_timestamp_event_genlock priv; int ret; if (len != sizeof(priv)) return -EINVAL; if (copy_from_user(&priv, data, sizeof(priv))) return -EFAULT; event = kzalloc(sizeof(*event), GFP_KERNEL); if (event == NULL) return -ENOMEM; event->handle = genlock_get_handle_fd(priv.handle); if (IS_ERR(event->handle)) { int ret = PTR_ERR(event->handle); kfree(event); return ret; } ret = kgsl_add_event(device, timestamp, kgsl_genlock_event_cb, event); if (ret) kfree(event); return ret; } #else static long kgsl_add_genlock_event(struct kgsl_device *device, u32 timestamp, void __user *data, int len) { return -EINVAL; } #endif /** * kgsl_ioctl_timestamp_event - Register a new timestamp event from userspace * @dev_priv - pointer to the private device structure * @cmd - the ioctl cmd passed from kgsl_ioctl * @data - the user data buffer from kgsl_ioctl * @returns 0 on success or error code on failure */ static long kgsl_ioctl_timestamp_event(struct kgsl_device_private *dev_priv, unsigned int cmd, void *data) { struct kgsl_timestamp_event *param = data; int ret; switch (param->type) { case KGSL_TIMESTAMP_EVENT_GENLOCK: ret = kgsl_add_genlock_event(dev_priv->device, param->timestamp, param->priv, param->len); break; default: ret = -EINVAL; } return ret; } typedef long (*kgsl_ioctl_func_t)(struct kgsl_device_private *, unsigned int, void *); #define KGSL_IOCTL_FUNC(_cmd, _func, _lock) \ [_IOC_NR(_cmd)] = { .cmd = _cmd, .func = _func, .lock = _lock } static const struct { unsigned int cmd; kgsl_ioctl_func_t func; int lock; } kgsl_ioctl_funcs[] = { KGSL_IOCTL_FUNC(IOCTL_KGSL_DEVICE_GETPROPERTY, kgsl_ioctl_device_getproperty, 1), KGSL_IOCTL_FUNC(IOCTL_KGSL_DEVICE_WAITTIMESTAMP, kgsl_ioctl_device_waittimestamp, 1), KGSL_IOCTL_FUNC(IOCTL_KGSL_RINGBUFFER_ISSUEIBCMDS, kgsl_ioctl_rb_issueibcmds, 1), KGSL_IOCTL_FUNC(IOCTL_KGSL_CMDSTREAM_READTIMESTAMP, kgsl_ioctl_cmdstream_readtimestamp, 1), KGSL_IOCTL_FUNC(IOCTL_KGSL_CMDSTREAM_FREEMEMONTIMESTAMP, kgsl_ioctl_cmdstream_freememontimestamp, 1), KGSL_IOCTL_FUNC(IOCTL_KGSL_DRAWCTXT_CREATE, kgsl_ioctl_drawctxt_create, 1), KGSL_IOCTL_FUNC(IOCTL_KGSL_DRAWCTXT_DESTROY, kgsl_ioctl_drawctxt_destroy, 1), KGSL_IOCTL_FUNC(IOCTL_KGSL_MAP_USER_MEM, kgsl_ioctl_map_user_mem, 0), KGSL_IOCTL_FUNC(IOCTL_KGSL_SHAREDMEM_FROM_PMEM, kgsl_ioctl_map_user_mem, 0), KGSL_IOCTL_FUNC(IOCTL_KGSL_SHAREDMEM_FREE, kgsl_ioctl_sharedmem_free, 0), KGSL_IOCTL_FUNC(IOCTL_KGSL_SHAREDMEM_FROM_VMALLOC, kgsl_ioctl_sharedmem_from_vmalloc, 0), KGSL_IOCTL_FUNC(IOCTL_KGSL_SHAREDMEM_FLUSH_CACHE, kgsl_ioctl_sharedmem_flush_cache, 0), KGSL_IOCTL_FUNC(IOCTL_KGSL_GPUMEM_ALLOC, kgsl_ioctl_gpumem_alloc, 0), KGSL_IOCTL_FUNC(IOCTL_KGSL_CFF_SYNCMEM, kgsl_ioctl_cff_syncmem, 0), KGSL_IOCTL_FUNC(IOCTL_KGSL_CFF_USER_EVENT, kgsl_ioctl_cff_user_event, 0), KGSL_IOCTL_FUNC(IOCTL_KGSL_TIMESTAMP_EVENT, kgsl_ioctl_timestamp_event, 0), }; static long kgsl_ioctl(struct file *filep, unsigned int cmd, unsigned long arg) { struct kgsl_device_private *dev_priv = filep->private_data; unsigned int nr = _IOC_NR(cmd); kgsl_ioctl_func_t func; int lock, ret; char ustack[64]; void *uptr = NULL; BUG_ON(dev_priv == NULL); /* Workaround for an previously incorrectly defined ioctl code. This helps ensure binary compatability */ if (cmd == IOCTL_KGSL_CMDSTREAM_FREEMEMONTIMESTAMP_OLD) cmd = IOCTL_KGSL_CMDSTREAM_FREEMEMONTIMESTAMP; else if (cmd == IOCTL_KGSL_CMDSTREAM_READTIMESTAMP_OLD) cmd = IOCTL_KGSL_CMDSTREAM_READTIMESTAMP; if (cmd & (IOC_IN | IOC_OUT)) { if (_IOC_SIZE(cmd) < sizeof(ustack)) uptr = ustack; else { uptr = kzalloc(_IOC_SIZE(cmd), GFP_KERNEL); if (uptr == NULL) { KGSL_MEM_ERR(dev_priv->device, "kzalloc(%d) failed\n", _IOC_SIZE(cmd)); ret = -ENOMEM; goto done; } } if (cmd & IOC_IN) { if (copy_from_user(uptr, (void __user *) arg, _IOC_SIZE(cmd))) { ret = -EFAULT; goto done; } } else memset(uptr, 0, _IOC_SIZE(cmd)); } if (nr < ARRAY_SIZE(kgsl_ioctl_funcs) && kgsl_ioctl_funcs[nr].func != NULL) { func = kgsl_ioctl_funcs[nr].func; lock = kgsl_ioctl_funcs[nr].lock; } else { func = dev_priv->device->ftbl.device_ioctl; lock = 1; } if (lock) { mutex_lock(&dev_priv->device->mutex); kgsl_check_suspended(dev_priv->device); } ret = func(dev_priv, cmd, uptr); if (lock) { kgsl_check_idle_locked(dev_priv->device); mutex_unlock(&dev_priv->device->mutex); } if (ret == 0 && (cmd & IOC_OUT)) { if (copy_to_user((void __user *) arg, uptr, _IOC_SIZE(cmd))) ret = -EFAULT; } done: if (_IOC_SIZE(cmd) >= sizeof(ustack)) kfree(uptr); return ret; } static int kgsl_mmap_memstore(struct kgsl_device *device, struct vm_area_struct *vma) { struct kgsl_memdesc *memdesc = &device->memstore; int result; unsigned int vma_size = vma->vm_end - vma->vm_start; /* The memstore can only be mapped as read only */ if (vma->vm_flags & VM_WRITE) return -EPERM; if (memdesc->size != vma_size) { KGSL_MEM_ERR(device, "memstore bad size: %d should be %d\n", vma_size, memdesc->size); return -EINVAL; } vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot); result = remap_pfn_range(vma, vma->vm_start, vma->vm_pgoff, vma_size, vma->vm_page_prot); if (result != 0) KGSL_MEM_ERR(device, "remap_pfn_range failed: %d\n", result); return result; } /* * kgsl_gpumem_vm_open is called whenever a vma region is copied or split. * Increase the refcount to make sure that the accounting stays correct */ static void kgsl_gpumem_vm_open(struct vm_area_struct *vma) { struct kgsl_mem_entry *entry = vma->vm_private_data; kgsl_mem_entry_get(entry); } static int kgsl_gpumem_vm_fault(struct vm_area_struct *vma, struct vm_fault *vmf) { struct kgsl_mem_entry *entry = vma->vm_private_data; if (!entry->memdesc.ops->vmfault) return VM_FAULT_SIGBUS; return entry->memdesc.ops->vmfault(&entry->memdesc, vma, vmf); } static void kgsl_gpumem_vm_close(struct vm_area_struct *vma) { struct kgsl_mem_entry *entry = vma->vm_private_data; kgsl_mem_entry_put(entry); } static struct vm_operations_struct kgsl_gpumem_vm_ops = { .open = kgsl_gpumem_vm_open, .fault = kgsl_gpumem_vm_fault, .close = kgsl_gpumem_vm_close, }; static int kgsl_mmap(struct file *file, struct vm_area_struct *vma) { unsigned long vma_offset = vma->vm_pgoff << PAGE_SHIFT; struct inode *inodep = file->f_path.dentry->d_inode; struct kgsl_device_private *dev_priv = file->private_data; struct kgsl_process_private *private = dev_priv->process_priv; struct kgsl_mem_entry *entry; struct kgsl_device *device; device = kgsl_driver.devp[iminor(inodep)]; BUG_ON(device == NULL); /* Handle leagacy behavior for memstore */ if (vma_offset == device->memstore.physaddr) return kgsl_mmap_memstore(device, vma); /* Find a chunk of GPU memory */ spin_lock(&private->mem_lock); list_for_each_entry(entry, &private->mem_list, list) { if (vma_offset == entry->memdesc.gpuaddr) { kgsl_mem_entry_get(entry); break; } } spin_unlock(&private->mem_lock); if (entry == NULL) return -EINVAL; if (!entry->memdesc.ops->vmflags || !entry->memdesc.ops->vmfault) return -EINVAL; vma->vm_flags |= entry->memdesc.ops->vmflags(&entry->memdesc); vma->vm_private_data = entry; vma->vm_page_prot = pgprot_writecombine(vma->vm_page_prot); vma->vm_ops = &kgsl_gpumem_vm_ops; vma->vm_file = file; return 0; } static const struct file_operations kgsl_fops = { .owner = THIS_MODULE, .release = kgsl_release, .open = kgsl_open, .mmap = kgsl_mmap, .unlocked_ioctl = kgsl_ioctl, }; struct kgsl_driver kgsl_driver = { .process_mutex = __MUTEX_INITIALIZER(kgsl_driver.process_mutex), .pt_mutex = __MUTEX_INITIALIZER(kgsl_driver.pt_mutex), .devlock = __MUTEX_INITIALIZER(kgsl_driver.devlock), }; EXPORT_SYMBOL(kgsl_driver); void kgsl_unregister_device(struct kgsl_device *device) { int minor; mutex_lock(&kgsl_driver.devlock); for (minor = 0; minor < KGSL_DEVICE_MAX; minor++) { if (device == kgsl_driver.devp[minor]) break; } mutex_unlock(&kgsl_driver.devlock); if (minor == KGSL_DEVICE_MAX) return; kgsl_pwrctrl_uninit_sysfs(device); device_destroy(kgsl_driver.class, MKDEV(MAJOR(kgsl_driver.major), minor)); mutex_lock(&kgsl_driver.devlock); kgsl_driver.devp[minor] = NULL; mutex_unlock(&kgsl_driver.devlock); } EXPORT_SYMBOL(kgsl_unregister_device); int kgsl_register_device(struct kgsl_device *device) { int minor, ret; dev_t dev; /* Find a minor for the device */ mutex_lock(&kgsl_driver.devlock); for (minor = 0; minor < KGSL_DEVICE_MAX; minor++) { if (kgsl_driver.devp[minor] == NULL) { kgsl_driver.devp[minor] = device; break; } } mutex_unlock(&kgsl_driver.devlock); if (minor == KGSL_DEVICE_MAX) { KGSL_CORE_ERR("minor devices exhausted\n"); return -ENODEV; } /* Create the device */ dev = MKDEV(MAJOR(kgsl_driver.major), minor); device->dev = device_create(kgsl_driver.class, &device->pdev->dev, dev, device, device->name); if (IS_ERR(device->dev)) { ret = PTR_ERR(device->dev); KGSL_CORE_ERR("device_create(%s): %d\n", device->name, ret); goto err_devlist; } dev_set_drvdata(&device->pdev->dev, device); /* Generic device initialization */ /* sysfs and debugfs initalization - failure here is non fatal */ /* Initialize logging */ kgsl_device_debugfs_init(device); /* Initialize common sysfs entries */ kgsl_pwrctrl_init_sysfs(device); return 0; err_devlist: mutex_lock(&kgsl_driver.devlock); kgsl_driver.devp[minor] = NULL; mutex_unlock(&kgsl_driver.devlock); return ret; } EXPORT_SYMBOL(kgsl_register_device); int kgsl_device_platform_probe(struct kgsl_device *device, irqreturn_t (*dev_isr) (int, void*)) { int status = -EINVAL; struct kgsl_memregion *regspace = NULL; struct resource *res; struct platform_device *pdev = device->pdev; pm_runtime_enable(&pdev->dev); status = kgsl_pwrctrl_init(device); if (status) goto error; /* initilization of timestamp wait */ init_waitqueue_head(&device->wait_queue); res = platform_get_resource_byname(pdev, IORESOURCE_MEM, device->iomemname); if (res == NULL) { KGSL_DRV_ERR(device, "platform_get_resource_byname failed\n"); status = -EINVAL; goto error_pwrctrl_close; } if (res->start == 0 || resource_size(res) == 0) { KGSL_DRV_ERR(device, "dev %d invalid regspace\n", device->id); status = -EINVAL; goto error_pwrctrl_close; } regspace = &device->regspace; regspace->mmio_phys_base = res->start; regspace->sizebytes = resource_size(res); if (!request_mem_region(regspace->mmio_phys_base, regspace->sizebytes, device->name)) { KGSL_DRV_ERR(device, "request_mem_region failed\n"); status = -ENODEV; goto error_pwrctrl_close; } regspace->mmio_virt_base = ioremap(regspace->mmio_phys_base, regspace->sizebytes); if (regspace->mmio_virt_base == NULL) { KGSL_DRV_ERR(device, "ioremap failed\n"); status = -ENODEV; goto error_release_mem; } status = request_irq(device->pwrctrl.interrupt_num, dev_isr, IRQF_TRIGGER_HIGH, device->name, device); if (status) { KGSL_DRV_ERR(device, "request_irq(%d) failed: %d\n", device->pwrctrl.interrupt_num, status); goto error_iounmap; } device->pwrctrl.have_irq = 1; disable_irq(device->pwrctrl.interrupt_num); KGSL_DRV_INFO(device, "dev_id %d regs phys 0x%08x size 0x%08x virt %p\n", device->id, regspace->mmio_phys_base, regspace->sizebytes, regspace->mmio_virt_base); kgsl_cffdump_open(device->id); init_completion(&device->hwaccess_gate); init_completion(&device->suspend_gate); ATOMIC_INIT_NOTIFIER_HEAD(&device->ts_notifier_list); setup_timer(&device->idle_timer, kgsl_timer, (unsigned long) device); status = kgsl_create_device_workqueue(device); if (status) goto error_free_irq; INIT_WORK(&device->idle_check_ws, kgsl_idle_check); INIT_LIST_HEAD(&device->memqueue); INIT_LIST_HEAD(&device->events); status = kgsl_mmu_init(device); if (status != 0) goto error_dest_work_q; status = kgsl_allocate_contig(&device->memstore, sizeof(struct kgsl_devmemstore)); if (status != 0) goto error_close_mmu; kgsl_sharedmem_set(&device->memstore, 0, 0, device->memstore.size); status = kgsl_register_device(device); if (status) goto error_close_mmu; wake_lock_init(&device->idle_wakelock, WAKE_LOCK_IDLE, device->name); idr_init(&device->context_idr); return status; error_close_mmu: kgsl_mmu_close(device); error_dest_work_q: destroy_workqueue(device->work_queue); device->work_queue = NULL; error_free_irq: free_irq(device->pwrctrl.interrupt_num, NULL); device->pwrctrl.have_irq = 0; error_iounmap: iounmap(regspace->mmio_virt_base); regspace->mmio_virt_base = NULL; error_release_mem: release_mem_region(regspace->mmio_phys_base, regspace->sizebytes); error_pwrctrl_close: kgsl_pwrctrl_close(device); error: return status; } EXPORT_SYMBOL(kgsl_device_platform_probe); void kgsl_device_platform_remove(struct kgsl_device *device) { struct kgsl_memregion *regspace = &device->regspace; kgsl_unregister_device(device); if (device->memstore.hostptr) kgsl_sharedmem_free(&device->memstore); kgsl_mmu_close(device); if (regspace->mmio_virt_base != NULL) { iounmap(regspace->mmio_virt_base); regspace->mmio_virt_base = NULL; release_mem_region(regspace->mmio_phys_base, regspace->sizebytes); } kgsl_pwrctrl_close(device); kgsl_cffdump_close(device->id); if (device->work_queue) { destroy_workqueue(device->work_queue); device->work_queue = NULL; } pm_runtime_disable(&device->pdev->dev); wake_lock_destroy(&device->idle_wakelock); idr_destroy(&device->context_idr); } EXPORT_SYMBOL(kgsl_device_platform_remove); static int __devinit kgsl_ptdata_init(void) { INIT_LIST_HEAD(&kgsl_driver.pagetable_list); return kgsl_ptpool_init(&kgsl_driver.ptpool, KGSL_PAGETABLE_SIZE, kgsl_pagetable_count); } static void kgsl_core_exit(void) { unregister_chrdev_region(kgsl_driver.major, KGSL_DEVICE_MAX); kgsl_ptpool_destroy(&kgsl_driver.ptpool); device_unregister(&kgsl_driver.virtdev); if (kgsl_driver.class) { class_destroy(kgsl_driver.class); kgsl_driver.class = NULL; } kgsl_drm_exit(); kgsl_cffdump_destroy(); } static int __init kgsl_core_init(void) { int result = 0; /* alloc major and minor device numbers */ result = alloc_chrdev_region(&kgsl_driver.major, 0, KGSL_DEVICE_MAX, KGSL_NAME); if (result < 0) { KGSL_CORE_ERR("alloc_chrdev_region failed err = %d\n", result); goto err; } cdev_init(&kgsl_driver.cdev, &kgsl_fops); kgsl_driver.cdev.owner = THIS_MODULE; kgsl_driver.cdev.ops = &kgsl_fops; result = cdev_add(&kgsl_driver.cdev, MKDEV(MAJOR(kgsl_driver.major), 0), KGSL_DEVICE_MAX); if (result) { KGSL_CORE_ERR("kgsl: cdev_add() failed, dev_num= %d," " result= %d\n", kgsl_driver.major, result); goto err; } kgsl_driver.class = class_create(THIS_MODULE, KGSL_NAME); if (IS_ERR(kgsl_driver.class)) { result = PTR_ERR(kgsl_driver.class); KGSL_CORE_ERR("failed to create class %s", KGSL_NAME); goto err; } /* Make a virtual device for managing core related things in sysfs */ kgsl_driver.virtdev.class = kgsl_driver.class; dev_set_name(&kgsl_driver.virtdev, "kgsl"); result = device_register(&kgsl_driver.virtdev); if (result) { KGSL_CORE_ERR("driver_register failed\n"); goto err; } /* Make kobjects in the virtual device for storing statistics */ kgsl_driver.ptkobj = kobject_create_and_add("pagetables", &kgsl_driver.virtdev.kobj); kgsl_driver.prockobj = kobject_create_and_add("proc", &kgsl_driver.virtdev.kobj); kgsl_core_debugfs_init(); kgsl_sharedmem_init_sysfs(); kgsl_cffdump_init(); /* Generic device initialization */ INIT_LIST_HEAD(&kgsl_driver.process_list); result = kgsl_ptdata_init(); if (result) goto err; result = kgsl_drm_init(NULL); if (result) goto err; return 0; err: kgsl_core_exit(); return result; } device_initcall(kgsl_core_init);
kernelzilla/android-kernel
drivers/gpu/msm/kgsl.c
C
gpl-2.0
56,394
// Generated on 02/23/2017 16:53:48 using System; using System.Collections.Generic; using System.Linq; using DarkSoul.Network.Protocol.Types; using DarkSoul.Network.Protocol.Message; using DarkSoul.Core.Interfaces; using DarkSoul.Core.IO; namespace DarkSoul.Network.Protocol.Messages { public class GuildInformationsMembersMessage : NetworkMessage { public override ushort Id => 5558; public IEnumerable<Types.GuildMember> members; public GuildInformationsMembersMessage() { } public GuildInformationsMembersMessage(IEnumerable<Types.GuildMember> members) { this.members = members; } public override void Serialize(IWriter writer) { writer.WriteShort((short)members.Count()); foreach (var entry in members) { entry.Serialize(writer); } } public override void Deserialize(IReader reader) { var limit = reader.ReadUShort(); members = new Types.GuildMember[limit]; for (int i = 0; i < limit; i++) { (members as Types.GuildMember[])[i] = new Types.GuildMember(); (members as Types.GuildMember[])[i].Deserialize(reader); } } } }
LDOpenSource/DarkSoul
DarkSoul.Network/Protocol/Message/Messages/game/guild/GuildInformationsMembersMessage.cs
C#
gpl-2.0
1,389
[(#AUTORISER{configurer,_cpub}|sinon_interdire_acces)] <h1 class="grostitre"><:cpub:titre_page_configurer_cpub:></h1> <div class="ajax"> #FORMULAIRE_CONFIGURER_CPUB </div>
Arterrien/cpub
prive/squelettes/contenu/configurer_cpub.html
HTML
gpl-2.0
174
<?php //Includes include("../includes/adminIncludes.php"); if(!$_SESSION['name'] || $_SESSION['userrole'] != 1) { header('Location:index.php'); } include("../system/config.php"); include("../system/functions.php"); $_SESSION['page'] = "user"; $page = ($_GET['page']) ? intval($_GET['page']) : 1; $offset = " OFFSET " . intval(($page - 1 ) * 50); //Body Begins ?> <div class="wrapper"> <?php getSegment("topbar"); ?> <div class="col-md-6"> <div class="row"> <h4>Registered Users Search</h4> <div class="row"> <form action="<?php echo $_SERVER['PHP_SELF'];?>" method="GET"> <input type="text" placeholder="Name" name="searchName" /> <select name="searchWarehouse" class="form-control small-select"> <option value="">Warehouse</option> <?php getSegment('warehouse'); ?> </select> <input class="" type="submit" Value="Search" /> </form> </div> <div class="row"> <table cellspacing="5" cellpadding="5 "> <tr><th>Username</th><th>E-mail</th><th>WareHouse</th><th>Role</th><th>Action</th></tr> <?php $whereCondition = ""; if(trim($_GET['searchName']) != "" || trim($_GET['searchWarehouse']) != "") { $whereCondition = " where id > 0 "; } if(trim($_GET['searchName']) != "") { $name = mysql_real_escape_string(urldecode($_GET['searchName'])); $whereCondition .= " and username like '%$name%' "; } if(trim($_GET['searchWarehouse']) != "") { $cid = mysql_real_escape_string(urldecode($_GET['searchWarehouse'])); $whereCondition .= " and centerid = '$cid' "; } $qry = mysql_query("Select * from " . $tableName['admin_login'] . $whereCondition . " order by id LIMIT 50" . $offset); while ($row = mysql_fetch_array($qry)): ?><tr><td><?php echo $row[1];?></td><td><?php echo $row[3];?></td><td> <?php switch($row['userrole']) { case 1: $role = 'Admin';break; case 2: $role = 'WareHouse';break; case 3: $role = 'Super Volunteer';break; default: $role = ''; } $qry2 = mysql_query("Select * from " . $tableName['warehouse'] . " where w_id = " . $row['centerid']); $row2 = mysql_fetch_array($qry2); echo (empty($row2['w_name']) )? 'N/A': $row2['w_name']; ?> </td><td><?php echo $role;?></td><td><a href='<?php echo $config["adminController"]?>/indexController.php?id=<?php echo $row["id"]?>&action=delete'>Delete</a></td></tr> <?php endwhile;?> </table> <?php paginate($total, $page, $tableName['admin_login'], $whereCondition); ?> </div> </div> </div> <div class="col-sm-2"> </div> <div class="col-sm-3"> <div class="row"> <h3 class="ng-binding">Register New User</h3> <div class=""> <p><?php displayMsg();?></p> <form method="POST" action="<?php echo $config['adminController'];?>/indexController.php"> <input placeholder="Username" class="form-control" required="required" type="text" name="username" /> <input placeholder="Password" class="form-control" required="required" type="password" name="password" /> <input placeholder="E-mail" class="form-control" required="required" type="email" name="email" /> <select class="form-control" required="required" name="userrole"> <option value="">User role</option> <?php getSegment('userrole'); ?> </select> <select name="warehouse" class="form-control"> <option value="">Warehouse</option> <?php getSegment('warehouse'); ?> </select> <input type="hidden" value="register" name="type" /> <input class="form-control" type="submit" Value="Register" /> </form> </div> </div> </div> </div> <?php //Includes include("../includes/adminfooter.php"); ?>
mshrestha/himalayandisaster
admin/addEditUser.php
PHP
gpl-2.0
3,824
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the QtWebEngine module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qwebengineurlschemehandler.h" #include "qwebengineurlrequestjob.h" QT_BEGIN_NAMESPACE /*! \class QWebEngineUrlSchemeHandler \brief The QWebEngineUrlSchemeHandler class is a base class for handling custom URL schemes. \since 5.6 To implement a custom URL scheme for QtWebEngine, you first have to create an instance of QWebEngineUrlScheme and register it using QWebEngineUrlScheme::registerScheme(). \note Make sure that you create and register the scheme object \e before the QGuiApplication or QApplication object is instantiated. Then you must create a class derived from QWebEngineUrlSchemeHandler, and reimplement the requestStarted() method. Finally, install the scheme handler object via QWebEngineProfile::installUrlSchemeHandler() or QQuickWebEngineProfile::installUrlSchemeHandler(). \code class MySchemeHandler : public QWebEngineUrlSchemeHandler { public: MySchemeHandler(QObject *parent = nullptr); void requestStarted(QWebEngineUrlRequestJob *request) { // .... } }; int main(int argc, char **argv) { QWebEngineUrlScheme scheme("myscheme"); scheme.setSyntax(QWebEngineUrlScheme::Syntax::HostAndPort); scheme.setDefaultPort(2345); scheme.setFlags(QWebEngineUrlScheme::SecureScheme); QWebEngineUrlScheme::registerScheme(scheme); // ... QApplication app(argc, argv); // ... // installUrlSchemeHandler does not take ownership of the handler. MySchemeHandler *handler = new MySchemeHandler(parent); QWebEngineProfile::defaultProfile()->installUrlSchemeHandler("myscheme", handler); } \endcode \inmodule QtWebEngineCore \sa {QWebEngineUrlScheme}, {WebEngine Widgets WebUI Example} */ /*! Constructs a new URL scheme handler. The handler is created with the parent \a parent. */ QWebEngineUrlSchemeHandler::QWebEngineUrlSchemeHandler(QObject *parent) : QObject(parent) { } /*! Deletes a custom URL scheme handler. */ QWebEngineUrlSchemeHandler::~QWebEngineUrlSchemeHandler() { } /*! \fn void QWebEngineUrlSchemeHandler::requestStarted(QWebEngineUrlRequestJob *request) This method is called whenever a request \a request for the registered scheme is started. This method must be reimplemented by all custom URL scheme handlers. The request is asynchronous and does not need to be handled right away. \sa QWebEngineUrlRequestJob */ QT_END_NAMESPACE
qtproject/qtwebengine
src/core/api/qwebengineurlschemehandler.cpp
C++
gpl-2.0
4,471
/* sha3.c * * Copyright (C) 2006-2016 wolfSSL Inc. * * This file is part of wolfSSL. * * wolfSSL 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. * * wolfSSL 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-1335, USA */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <wolfssl/wolfcrypt/settings.h> #if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_XILINX_CRYPT) #include <wolfssl/wolfcrypt/sha3.h> #include <wolfssl/wolfcrypt/error-crypt.h> /* fips wrapper calls, user can call direct */ #ifdef HAVE_FIPS int wc_InitSha3_224(Sha3* sha, void* heap, int devId) { (void)heap; (void)devId; if (sha == NULL) { return BAD_FUNC_ARG; } return InitSha3_224_fips(sha); } int wc_Sha3_224_Update(Sha3* sha, const byte* data, word32 len) { if (sha == NULL || (data == NULL && len > 0)) { return BAD_FUNC_ARG; } return Sha3_224_Update_fips(sha, data, len); } int wc_Sha3_224_Final(Sha3* sha, byte* out) { if (sha == NULL || out == NULL) { return BAD_FUNC_ARG; } return Sha3_224_Final_fips(sha, out); } void wc_Sha3_224_Free(Sha3* sha) { (void)sha; /* Not supported in FIPS */ } int wc_InitSha3_256(Sha3* sha, void* heap, int devId) { (void)heap; (void)devId; if (sha == NULL) { return BAD_FUNC_ARG; } return InitSha3_256_fips(sha); } int wc_Sha3_256_Update(Sha3* sha, const byte* data, word32 len) { if (sha == NULL || (data == NULL && len > 0)) { return BAD_FUNC_ARG; } return Sha3_256_Update_fips(sha, data, len); } int wc_Sha3_256_Final(Sha3* sha, byte* out) { if (sha == NULL || out == NULL) { return BAD_FUNC_ARG; } return Sha3_256_Final_fips(sha, out); } void wc_Sha3_256_Free(Sha3* sha) { (void)sha; /* Not supported in FIPS */ } int wc_InitSha3_384(Sha3* sha, void* heap, int devId) { (void)heap; (void)devId; if (sha == NULL) { return BAD_FUNC_ARG; } return InitSha3_384_fips(sha); } int wc_Sha3_384_Update(Sha3* sha, const byte* data, word32 len) { if (sha == NULL || (data == NULL && len > 0)) { return BAD_FUNC_ARG; } return Sha3_384_Update_fips(sha, data, len); } int wc_Sha3_384_Final(Sha3* sha, byte* out) { if (sha == NULL || out == NULL) { return BAD_FUNC_ARG; } return Sha3_384_Final_fips(sha, out); } void wc_Sha3_384_Free(Sha3* sha) { (void)sha; /* Not supported in FIPS */ } int wc_InitSha3_512(Sha3* sha, void* heap, int devId) { (void)heap; (void)devId; if (sha == NULL) { return BAD_FUNC_ARG; } return InitSha3_512_fips(sha); } int wc_Sha3_512_Update(Sha3* sha, const byte* data, word32 len) { if (sha == NULL || (data == NULL && len > 0)) { return BAD_FUNC_ARG; } return Sha3_512_Update_fips(sha, data, len); } int wc_Sha3_512_Final(Sha3* sha, byte* out) { if (sha == NULL || out == NULL) { return BAD_FUNC_ARG; } return Sha3_512_Final_fips(sha, out); } void wc_Sha3_512_Free(Sha3* sha) { (void)sha; /* Not supported in FIPS */ } #else /* else build without fips */ #ifdef NO_INLINE #include <wolfssl/wolfcrypt/misc.h> #else #define WOLFSSL_MISC_INCLUDED #include <wolfcrypt/src/misc.c> #endif #ifdef WOLFSSL_SHA3_SMALL /* Rotate a 64-bit value left. * * a Number to rotate left. * r Number od bits to rotate left. * returns the rotated number. */ #define ROTL64(a, n) (((a)<<(n))|((a)>>(64-(n)))) /* An array of values to XOR for block operation. */ static const word64 hash_keccak_r[24] = { 0x0000000000000001UL, 0x0000000000008082UL, 0x800000000000808aUL, 0x8000000080008000UL, 0x000000000000808bUL, 0x0000000080000001UL, 0x8000000080008081UL, 0x8000000000008009UL, 0x000000000000008aUL, 0x0000000000000088UL, 0x0000000080008009UL, 0x000000008000000aUL, 0x000000008000808bUL, 0x800000000000008bUL, 0x8000000000008089UL, 0x8000000000008003UL, 0x8000000000008002UL, 0x8000000000000080UL, 0x000000000000800aUL, 0x800000008000000aUL, 0x8000000080008081UL, 0x8000000000008080UL, 0x0000000080000001UL, 0x8000000080008008UL }; /* Indeces used in swap and rotate operation. */ #define K_I_0 10 #define K_I_1 7 #define K_I_2 11 #define K_I_3 17 #define K_I_4 18 #define K_I_5 3 #define K_I_6 5 #define K_I_7 16 #define K_I_8 8 #define K_I_9 21 #define K_I_10 24 #define K_I_11 4 #define K_I_12 15 #define K_I_13 23 #define K_I_14 19 #define K_I_15 13 #define K_I_16 12 #define K_I_17 2 #define K_I_18 20 #define K_I_19 14 #define K_I_20 22 #define K_I_21 9 #define K_I_22 6 #define K_I_23 1 /* Number of bits to rotate in swap and rotate operation. */ #define K_R_0 1 #define K_R_1 3 #define K_R_2 6 #define K_R_3 10 #define K_R_4 15 #define K_R_5 21 #define K_R_6 28 #define K_R_7 36 #define K_R_8 45 #define K_R_9 55 #define K_R_10 2 #define K_R_11 14 #define K_R_12 27 #define K_R_13 41 #define K_R_14 56 #define K_R_15 8 #define K_R_16 25 #define K_R_17 43 #define K_R_18 62 #define K_R_19 18 #define K_R_20 39 #define K_R_21 61 #define K_R_22 20 #define K_R_23 44 /* Swap and rotate left operation. * * s The state. * t1 Temporary value. * t2 Second temporary value. * i The index of the loop. */ #define SWAP_ROTL(s, t1, t2, i) \ do \ { \ t2 = s[K_I_##i]; s[K_I_##i] = ROTL64(t1, K_R_##i); \ } \ while (0) /* Mix the XOR of the column's values into each number by column. * * s The state. * b Temporary array of XORed column values. * x The index of the column. * t Temporary variable. */ #define COL_MIX(s, b, x, t) \ do \ { \ for (x = 0; x < 5; x++) \ b[x] = s[x + 0] ^ s[x + 5] ^ s[x + 10] ^ s[x + 15] ^ s[x + 20]; \ for (x = 0; x < 5; x++) \ { \ t = b[(x + 4) % 5] ^ ROTL64(b[(x + 1) % 5], 1); \ s[x + 0] ^= t; \ s[x + 5] ^= t; \ s[x + 10] ^= t; \ s[x + 15] ^= t; \ s[x + 20] ^= t; \ } \ } \ while (0) #ifdef SHA3_BY_SPEC /* Mix the row values. * BMI1 has ANDN instruction ((~a) & b) - Haswell and above. * * s The state. * b Temporary array of XORed row values. * y The index of the row to work on. * x The index of the column. * t0 Temporary variable. * t1 Temporary variable. */ #define ROW_MIX(s, b, y, x, t0, t1) \ do \ { \ for (y = 0; y < 5; y++) \ { \ for (x = 0; x < 5; x++) \ b[x] = s[y * 5 + x]; \ for (x = 0; x < 5; x++) \ s[y * 5 + x] = b[x] ^ (~b[(x + 1) % 5] & b[(x + 2) % 5]); \ } \ } \ while (0) #else /* Mix the row values. * a ^ (~b & c) == a ^ (c & (b ^ c)) == (a ^ b) ^ (b | c) * * s The state. * b Temporary array of XORed row values. * y The index of the row to work on. * x The index of the column. * t0 Temporary variable. * t1 Temporary variable. */ #define ROW_MIX(s, b, y, x, t12, t34) \ do \ { \ for (y = 0; y < 5; y++) \ { \ for (x = 0; x < 5; x++) \ b[x] = s[y * 5 + x]; \ t12 = (b[1] ^ b[2]); t34 = (b[3] ^ b[4]); \ s[y * 5 + 0] = b[0] ^ (b[2] & t12); \ s[y * 5 + 1] = t12 ^ (b[2] | b[3]); \ s[y * 5 + 2] = b[2] ^ (b[4] & t34); \ s[y * 5 + 3] = t34 ^ (b[4] | b[0]); \ s[y * 5 + 4] = b[4] ^ (b[1] & (b[0] ^ b[1])); \ } \ } \ while (0) #endif /* The block operation performed on the state. * * s The state. */ static void BlockSha3(word64 *s) { byte i, x, y; word64 t0, t1; word64 b[5]; for (i = 0; i < 24; i++) { COL_MIX(s, b, x, t0); t0 = s[1]; SWAP_ROTL(s, t0, t1, 0); SWAP_ROTL(s, t1, t0, 1); SWAP_ROTL(s, t0, t1, 2); SWAP_ROTL(s, t1, t0, 3); SWAP_ROTL(s, t0, t1, 4); SWAP_ROTL(s, t1, t0, 5); SWAP_ROTL(s, t0, t1, 6); SWAP_ROTL(s, t1, t0, 7); SWAP_ROTL(s, t0, t1, 8); SWAP_ROTL(s, t1, t0, 9); SWAP_ROTL(s, t0, t1, 10); SWAP_ROTL(s, t1, t0, 11); SWAP_ROTL(s, t0, t1, 12); SWAP_ROTL(s, t1, t0, 13); SWAP_ROTL(s, t0, t1, 14); SWAP_ROTL(s, t1, t0, 15); SWAP_ROTL(s, t0, t1, 16); SWAP_ROTL(s, t1, t0, 17); SWAP_ROTL(s, t0, t1, 18); SWAP_ROTL(s, t1, t0, 19); SWAP_ROTL(s, t0, t1, 20); SWAP_ROTL(s, t1, t0, 21); SWAP_ROTL(s, t0, t1, 22); SWAP_ROTL(s, t1, t0, 23); ROW_MIX(s, b, y, x, t0, t1); s[0] ^= hash_keccak_r[i]; } } #else #include "sha3_long.i" #endif /* Convert the array of bytes, in little-endian order, to a 64-bit integer. * * a Array of bytes. * returns a 64-bit integer. */ static word64 Load64BitBigEndian(const byte* a) { #ifdef BIG_ENDIAN_ORDER word64 n = 0; int i; for (i = 0; i < 8; i++) n |= (word64)a[i] << (8 * i); return n; #else return *(word64*)a; #endif } /* Initialize the state for a SHA3-224 hash operation. * * sha3 Sha3 object holding state. * returns 0 on success. */ static int InitSha3(Sha3* sha3) { int i; for (i = 0; i < 25; i++) sha3->s[i] = 0; sha3->i = 0; return 0; } /* Update the SHA-3 hash state with message data. * * sha3 Sha3 object holding state. * data Message data to be hashed. * len Length of the message data. * p Number of 64-bit numbers in a block of data to process. * returns 0 on success. */ static int Sha3Update(Sha3* sha3, const byte* data, word32 len, byte p) { byte i; byte l; byte *t; if (sha3->i > 0) { l = p * 8 - sha3->i; if (l > len) l = len; t = &sha3->t[sha3->i]; for (i = 0; i < l; i++) t[i] = data[i]; data += i; len -= i; sha3->i += i; if (sha3->i == p * 8) { for (i = 0; i < p; i++) sha3->s[i] ^= Load64BitBigEndian(sha3->t + 8 * i); BlockSha3(sha3->s); sha3->i = 0; } } while (len >= p * 8) { for (i = 0; i < p; i++) sha3->s[i] ^= Load64BitBigEndian(data + 8 * i); BlockSha3(sha3->s); len -= p * 8; data += p * 8; } for (i = 0; i < len; i++) sha3->t[i] = data[i]; sha3->i += i; return 0; } /* Calculate the SHA-3 hash based on all the message data seen. * * sha3 Sha3 object holding state. * hash Buffer to hold the hash result. * p Number of 64-bit numbers in a block of data to process. * len Number of bytes in output. * returns 0 on success. */ static int Sha3Final(Sha3* sha3, byte* hash, byte p, byte l) { byte i; byte *s8 = (byte *)sha3->s; sha3->t[p * 8 - 1] = 0x00; sha3->t[ sha3->i] = 0x06; sha3->t[p * 8 - 1] |= 0x80; for (i=sha3->i + 1; i < p * 8 - 1; i++) sha3->t[i] = 0; for (i = 0; i < p; i++) sha3->s[i] ^= Load64BitBigEndian(sha3->t + 8 * i); BlockSha3(sha3->s); #if defined(BIG_ENDIAN_ORDER) ByteReverseWords64(sha3->s, sha3->s, ((l+7)/8)*8); #endif for (i = 0; i < l; i++) hash[i] = s8[i]; return 0; } /* Initialize the state for a SHA-3 hash operation. * * sha3 Sha3 object holding state. * heap Heap reference for dynamic memory allocation. (Used in async ops.) * devId Device identifier for asynchronous operation. * returns 0 on success. */ static int wc_InitSha3(Sha3* sha3, void* heap, int devId) { int ret = 0; if (sha3 == NULL) return BAD_FUNC_ARG; sha3->heap = heap; ret = InitSha3(sha3); if (ret != 0) return ret; #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_SHA3) ret = wolfAsync_DevCtxInit(&sha3->asyncDev, WOLFSSL_ASYNC_MARKER_SHA3, sha3->heap, devId); #else (void)devId; #endif /* WOLFSSL_ASYNC_CRYPT */ return ret; } /* Update the SHA-3 hash state with message data. * * sha3 Sha3 object holding state. * data Message data to be hashed. * len Length of the message data. * p Number of 64-bit numbers in a block of data to process. * returns 0 on success. */ static int wc_Sha3Update(Sha3* sha3, const byte* data, word32 len, byte p) { int ret = 0; if (sha3 == NULL || (data == NULL && len > 0)) { return BAD_FUNC_ARG; } #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_SHA3) if (sha3->asyncDev.marker == WOLFSSL_ASYNC_MARKER_SHA3) { #if defined(HAVE_INTEL_QA) return IntelQaSymSha3(&sha3->asyncDev, NULL, data, len); #endif } #endif /* WOLFSSL_ASYNC_CRYPT */ Sha3Update(sha3, data, len, p); return ret; } /* Calculate the SHA-3 hash based on all the message data seen. * * sha3 Sha3 object holding state. * hash Buffer to hold the hash result. * p Number of 64-bit numbers in a block of data to process. * len Number of bytes in output. * returns 0 on success. */ static int wc_Sha3Final(Sha3* sha3, byte* hash, byte p, byte len) { int ret; if (sha3 == NULL || hash == NULL) { return BAD_FUNC_ARG; } #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_SHA3) if (sha3->asyncDev.marker == WOLFSSL_ASYNC_MARKER_SHA3) { #if defined(HAVE_INTEL_QA) return IntelQaSymSha3(&sha3->asyncDev, hash, NULL, SHA3_DIGEST_SIZE); #endif } #endif /* WOLFSSL_ASYNC_CRYPT */ ret = Sha3Final(sha3, hash, p, len); if (ret != 0) return ret; return InitSha3(sha3); /* reset state */ } /* Dispose of any dynamically allocated data from the SHA3-384 operation. * (Required for async ops.) * * sha3 Sha3 object holding state. * returns 0 on success. */ static void wc_Sha3Free(Sha3* sha3) { (void)sha3; #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_SHA3) if (sha3 == NULL) return; wolfAsync_DevCtxFree(&sha3->asyncDev, WOLFSSL_ASYNC_MARKER_SHA3); #endif /* WOLFSSL_ASYNC_CRYPT */ } #endif /* HAVE_FIPS */ /* Copy the state of the SHA3 operation. * * src Sha3 object holding state top copy. * dst Sha3 object to copy into. * returns 0 on success. */ static int wc_Sha3Copy(Sha3* src, Sha3* dst) { int ret = 0; if (src == NULL || dst == NULL) return BAD_FUNC_ARG; XMEMCPY(dst, src, sizeof(Sha3)); #ifdef WOLFSSL_ASYNC_CRYPT ret = wolfAsync_DevCopy(&src->asyncDev, &dst->asyncDev); #endif return ret; } /* Calculate the SHA3-224 hash based on all the message data so far. * More message data can be added, after this operation, using the current * state. * * sha3 Sha3 object holding state. * hash Buffer to hold the hash result. Must be at least 28 bytes. * p Number of 64-bit numbers in a block of data to process. * len Number of bytes in output. * returns 0 on success. */ static int wc_Sha3GetHash(Sha3* sha3, byte* hash, byte p, byte len) { int ret; Sha3 tmpSha3; if (sha3 == NULL || hash == NULL) return BAD_FUNC_ARG; ret = wc_Sha3Copy(sha3, &tmpSha3); if (ret == 0) { ret = wc_Sha3Final(&tmpSha3, hash, p, len); } return ret; } /* Initialize the state for a SHA3-224 hash operation. * * sha3 Sha3 object holding state. * heap Heap reference for dynamic memory allocation. (Used in async ops.) * devId Device identifier for asynchronous operation. * returns 0 on success. */ WOLFSSL_API int wc_InitSha3_224(Sha3* sha3, void* heap, int devId) { return wc_InitSha3(sha3, heap, devId); } /* Update the SHA3-224 hash state with message data. * * sha3 Sha3 object holding state. * data Message data to be hashed. * len Length of the message data. * returns 0 on success. */ WOLFSSL_API int wc_Sha3_224_Update(Sha3* sha3, const byte* data, word32 len) { return wc_Sha3Update(sha3, data, len, SHA3_224_COUNT); } /* Calculate the SHA3-224 hash based on all the message data seen. * The state is initialized ready for a new message to hash. * * sha3 Sha3 object holding state. * hash Buffer to hold the hash result. Must be at least 28 bytes. * returns 0 on success. */ WOLFSSL_API int wc_Sha3_224_Final(Sha3* sha3, byte* hash) { return wc_Sha3Final(sha3, hash, SHA3_224_COUNT, SHA3_224_DIGEST_SIZE); } /* Dispose of any dynamically allocated data from the SHA3-224 operation. * (Required for async ops.) * * sha3 Sha3 object holding state. * returns 0 on success. */ WOLFSSL_API void wc_Sha3_224_Free(Sha3* sha3) { wc_Sha3Free(sha3); } /* Calculate the SHA3-224 hash based on all the message data so far. * More message data can be added, after this operation, using the current * state. * * sha3 Sha3 object holding state. * hash Buffer to hold the hash result. Must be at least 28 bytes. * returns 0 on success. */ WOLFSSL_API int wc_Sha3_224_GetHash(Sha3* sha3, byte* hash) { return wc_Sha3GetHash(sha3, hash, SHA3_224_COUNT, SHA3_224_DIGEST_SIZE); } /* Copy the state of the SHA3-224 operation. * * src Sha3 object holding state top copy. * dst Sha3 object to copy into. * returns 0 on success. */ WOLFSSL_API int wc_Sha3_224_Copy(Sha3* src, Sha3* dst) { return wc_Sha3Copy(src, dst); } /* Initialize the state for a SHA3-256 hash operation. * * sha3 Sha3 object holding state. * heap Heap reference for dynamic memory allocation. (Used in async ops.) * devId Device identifier for asynchronous operation. * returns 0 on success. */ WOLFSSL_API int wc_InitSha3_256(Sha3* sha3, void* heap, int devId) { return wc_InitSha3(sha3, heap, devId); } /* Update the SHA3-256 hash state with message data. * * sha3 Sha3 object holding state. * data Message data to be hashed. * len Length of the message data. * returns 0 on success. */ WOLFSSL_API int wc_Sha3_256_Update(Sha3* sha3, const byte* data, word32 len) { return wc_Sha3Update(sha3, data, len, SHA3_256_COUNT); } /* Calculate the SHA3-256 hash based on all the message data seen. * The state is initialized ready for a new message to hash. * * sha3 Sha3 object holding state. * hash Buffer to hold the hash result. Must be at least 32 bytes. * returns 0 on success. */ WOLFSSL_API int wc_Sha3_256_Final(Sha3* sha3, byte* hash) { return wc_Sha3Final(sha3, hash, SHA3_256_COUNT, SHA3_256_DIGEST_SIZE); } /* Dispose of any dynamically allocated data from the SHA3-256 operation. * (Required for async ops.) * * sha3 Sha3 object holding state. * returns 0 on success. */ WOLFSSL_API void wc_Sha3_256_Free(Sha3* sha3) { wc_Sha3Free(sha3); } /* Calculate the SHA3-256 hash based on all the message data so far. * More message data can be added, after this operation, using the current * state. * * sha3 Sha3 object holding state. * hash Buffer to hold the hash result. Must be at least 32 bytes. * returns 0 on success. */ WOLFSSL_API int wc_Sha3_256_GetHash(Sha3* sha3, byte* hash) { return wc_Sha3GetHash(sha3, hash, SHA3_256_COUNT, SHA3_256_DIGEST_SIZE); } /* Copy the state of the SHA3-256 operation. * * src Sha3 object holding state top copy. * dst Sha3 object to copy into. * returns 0 on success. */ WOLFSSL_API int wc_Sha3_256_Copy(Sha3* src, Sha3* dst) { return wc_Sha3Copy(src, dst); } /* Initialize the state for a SHA3-384 hash operation. * * sha3 Sha3 object holding state. * heap Heap reference for dynamic memory allocation. (Used in async ops.) * devId Device identifier for asynchronous operation. * returns 0 on success. */ WOLFSSL_API int wc_InitSha3_384(Sha3* sha3, void* heap, int devId) { return wc_InitSha3(sha3, heap, devId); } /* Update the SHA3-384 hash state with message data. * * sha3 Sha3 object holding state. * data Message data to be hashed. * len Length of the message data. * returns 0 on success. */ WOLFSSL_API int wc_Sha3_384_Update(Sha3* sha3, const byte* data, word32 len) { return wc_Sha3Update(sha3, data, len, SHA3_384_COUNT); } /* Calculate the SHA3-384 hash based on all the message data seen. * The state is initialized ready for a new message to hash. * * sha3 Sha3 object holding state. * hash Buffer to hold the hash result. Must be at least 48 bytes. * returns 0 on success. */ WOLFSSL_API int wc_Sha3_384_Final(Sha3* sha3, byte* hash) { return wc_Sha3Final(sha3, hash, SHA3_384_COUNT, SHA3_384_DIGEST_SIZE); } /* Dispose of any dynamically allocated data from the SHA3-384 operation. * (Required for async ops.) * * sha3 Sha3 object holding state. * returns 0 on success. */ WOLFSSL_API void wc_Sha3_384_Free(Sha3* sha3) { wc_Sha3Free(sha3); } /* Calculate the SHA3-384 hash based on all the message data so far. * More message data can be added, after this operation, using the current * state. * * sha3 Sha3 object holding state. * hash Buffer to hold the hash result. Must be at least 48 bytes. * returns 0 on success. */ WOLFSSL_API int wc_Sha3_384_GetHash(Sha3* sha3, byte* hash) { return wc_Sha3GetHash(sha3, hash, SHA3_384_COUNT, SHA3_384_DIGEST_SIZE); } /* Copy the state of the SHA3-384 operation. * * src Sha3 object holding state top copy. * dst Sha3 object to copy into. * returns 0 on success. */ WOLFSSL_API int wc_Sha3_384_Copy(Sha3* src, Sha3* dst) { return wc_Sha3Copy(src, dst); } /* Initialize the state for a SHA3-512 hash operation. * * sha3 Sha3 object holding state. * heap Heap reference for dynamic memory allocation. (Used in async ops.) * devId Device identifier for asynchronous operation. * returns 0 on success. */ WOLFSSL_API int wc_InitSha3_512(Sha3* sha3, void* heap, int devId) { return wc_InitSha3(sha3, heap, devId); } /* Update the SHA3-512 hash state with message data. * * sha3 Sha3 object holding state. * data Message data to be hashed. * len Length of the message data. * returns 0 on success. */ WOLFSSL_API int wc_Sha3_512_Update(Sha3* sha3, const byte* data, word32 len) { return wc_Sha3Update(sha3, data, len, SHA3_512_COUNT); } /* Calculate the SHA3-512 hash based on all the message data seen. * The state is initialized ready for a new message to hash. * * sha3 Sha3 object holding state. * hash Buffer to hold the hash result. Must be at least 64 bytes. * returns 0 on success. */ WOLFSSL_API int wc_Sha3_512_Final(Sha3* sha3, byte* hash) { return wc_Sha3Final(sha3, hash, SHA3_512_COUNT, SHA3_512_DIGEST_SIZE); } /* Dispose of any dynamically allocated data from the SHA3-512 operation. * (Required for async ops.) * * sha3 Sha3 object holding state. * returns 0 on success. */ WOLFSSL_API void wc_Sha3_512_Free(Sha3* sha3) { wc_Sha3Free(sha3); } /* Calculate the SHA3-512 hash based on all the message data so far. * More message data can be added, after this operation, using the current * state. * * sha3 Sha3 object holding state. * hash Buffer to hold the hash result. Must be at least 64 bytes. * returns 0 on success. */ WOLFSSL_API int wc_Sha3_512_GetHash(Sha3* sha3, byte* hash) { return wc_Sha3GetHash(sha3, hash, SHA3_512_COUNT, SHA3_512_DIGEST_SIZE); } /* Copy the state of the SHA3-512 operation. * * src Sha3 object holding state top copy. * dst Sha3 object to copy into. * returns 0 on success. */ WOLFSSL_API int wc_Sha3_512_Copy(Sha3* src, Sha3* dst) { return wc_Sha3Copy(src, dst); } #endif /* WOLFSSL_SHA3 */
NickolasLapp/wolfssl
wolfcrypt/src/sha3.c
C
gpl-2.0
26,465
/* This file is part of the Jactimer Project. Jactimer is a free and feature-rich countdown timer. Visit http://jactimer.org Copyright (C) 2010 Thomas Trapp; mailto: jactimer@thomastrapp.com Jactimer 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. See COPYING for details. */ #include "signalingTimer.h" #include <QDebug> signalingTimer::signalingTimer(uint delay) : timer(this), togo(delay), d(delay) { } signalingTimer::~signalingTimer() { qDebug() << "signalingTimer going down"; } void signalingTimer::setDelay(uint delay) { d = delay; reset(); } uint signalingTimer::getDelay() const { return d; } void signalingTimer::start() { timer.start(interval); emit timerStarted(); } void signalingTimer::stop() { timer.stop(); emit timerStopped(); } void signalingTimer::reset() { togo = d; emit newTimerIndex(d); emit timerReset(); stop(); }
thomastrapp/jactimer
src/signalingTimer.cpp
C++
gpl-2.0
1,540
\overset{¨}{x} \neq \overset{¨}{x} = \overset{¨}{x} = \overset{¨}{x}
jgm/texmath
tests/writers/mover7.tex
TeX
gpl-2.0
73
//***************************************************************************** // Mishira: An audiovisual production tool for broadcasting live video // // Copyright (C) 2014 Lucas Murray <lucas@polyflare.com> // 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 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. //***************************************************************************** #ifndef SYNCLAYER_H #define SYNCLAYER_H #include "layer.h" #include "layerfactory.h" #include <QtGui/QColor> class LayerDialog; //============================================================================= class SyncLayer : public Layer { friend class SyncLayerFactory; private: // Members ----------------------------------------------------------- VidgfxVertBuf * m_vertBufA; // Moving metronome VidgfxVertBuf * m_vertBufB; // Static center VidgfxVertBuf * m_vertBufC; // Static center QColor m_color; bool m_refMetronomeDelayed; bool m_metronomeReffed; private: // Constructor/destructor -------------------------------------------- SyncLayer(LayerGroup *parent); ~SyncLayer(); public: // Methods ------------------------------------------------------------ void setColor(const QColor &color); QColor getColor() const; private: void updateMetronome(VidgfxContext *gfx, uint frameNum); public: // Interface ---------------------------------------------------------- virtual void initializeResources(VidgfxContext *gfx); virtual void updateResources(VidgfxContext *gfx); virtual void destroyResources(VidgfxContext *gfx); virtual void render( VidgfxContext *gfx, Scene *scene, uint frameNum, int numDropped); virtual quint32 getTypeId() const; virtual bool hasSettingsDialog(); virtual LayerDialog * createSettingsDialog(QWidget *parent = NULL); virtual void serialize(QDataStream *stream) const; virtual bool unserialize(QDataStream *stream); protected: virtual void showEvent(); virtual void hideEvent(); virtual void parentShowEvent(); virtual void parentHideEvent(); }; //============================================================================= inline QColor SyncLayer::getColor() const { return m_color; } //============================================================================= class SyncLayerFactory : public LayerFactory { public: // Interface ---------------------------------------------------------- virtual quint32 getTypeId() const; virtual QByteArray getTypeString() const; virtual Layer * createBlankLayer(LayerGroup *parent); virtual Layer * createLayerWithDefaults(LayerGroup *parent); virtual QString getAddLayerString() const; }; //============================================================================= #endif // SYNCLAYER_H
mishira/mishira
MishiraApp/Layers/sync/synclayer.h
C
gpl-2.0
3,151
/* This file is part of the ScriptDev2 Project. See AUTHORS file for Copyright information * 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 */ /* ScriptData SDName: Stratholme SD%Complete: 100 SDComment: Misc mobs for instance. GO-script to apply aura and start event for quest 8945 SDCategory: Stratholme EndScriptData */ /* ContentData go_service_gate go_gauntlet_gate go_stratholme_postbox mob_restless_soul mobs_spectral_ghostly_citizen npc_aurius EndContentData */ #include "precompiled.h" #include "stratholme.h" /*###### ## go_service_gate ######*/ bool GOUse_go_service_gate(Player* /*pPlayer*/, GameObject* pGo) { ScriptedInstance* pInstance = (ScriptedInstance*)pGo->GetInstanceData(); if (!pInstance) return false; if (pInstance->GetData(TYPE_BARTHILAS_RUN) != NOT_STARTED) return false; // if the service gate is used make Barthilas flee pInstance->SetData(TYPE_BARTHILAS_RUN, IN_PROGRESS); return false; } /*###### ## go_gauntlet_gate (this is the _first_ of the gauntlet gates, two exist) ######*/ bool GOUse_go_gauntlet_gate(Player* pPlayer, GameObject* pGo) { ScriptedInstance* pInstance = (ScriptedInstance*)pGo->GetInstanceData(); if (!pInstance) return false; if (pInstance->GetData(TYPE_BARON_RUN) != NOT_STARTED) return false; if (Group* pGroup = pPlayer->GetGroup()) { for (GroupReference* itr = pGroup->GetFirstMember(); itr != nullptr; itr = itr->next()) { Player* pGroupie = itr->getSource(); if (!pGroupie) continue; if (!pGroupie->HasAura(SPELL_BARON_ULTIMATUM)) pGroupie->CastSpell(pGroupie, SPELL_BARON_ULTIMATUM, true); } } else { if (!pPlayer->HasAura(SPELL_BARON_ULTIMATUM)) pPlayer->CastSpell(pPlayer, SPELL_BARON_ULTIMATUM, true); } pInstance->SetData(TYPE_BARON_RUN, IN_PROGRESS); return false; } /*###### ## go_stratholme_postbox ######*/ bool GOUse_go_stratholme_postbox(Player* pPlayer, GameObject* pGo) { ScriptedInstance* pInstance = (ScriptedInstance*)pGo->GetInstanceData(); if (!pInstance) return false; if (pInstance->GetData(TYPE_POSTMASTER) == DONE) return false; // When the data is Special, spawn the postmaster if (pInstance->GetData(TYPE_POSTMASTER) == SPECIAL) { pPlayer->CastSpell(pPlayer, SPELL_SUMMON_POSTMASTER, true); pInstance->SetData(TYPE_POSTMASTER, DONE); } else pInstance->SetData(TYPE_POSTMASTER, IN_PROGRESS); // Summon 3 postmen for each postbox float fX, fY, fZ; for (uint8 i = 0; i < 3; ++i) { pPlayer->GetRandomPoint(pPlayer->GetPositionX(), pPlayer->GetPositionY(), pPlayer->GetPositionZ(), 3.0f, fX, fY, fZ); pPlayer->SummonCreature(NPC_UNDEAD_POSTMAN, fX, fY, fZ, 0.0f, TEMPSUMMON_DEAD_DESPAWN, 0); } return false; } /*###### ## mob_restless_soul ######*/ enum { // Possibly more of these quotes around. SAY_ZAPPED0 = -1329000, SAY_ZAPPED1 = -1329001, SAY_ZAPPED2 = -1329002, SAY_ZAPPED3 = -1329003, QUEST_RESTLESS_SOUL = 5282, SPELL_EGAN_BLASTER = 17368, SPELL_SOUL_FREED = 17370, NPC_RESTLESS_SOUL = 11122, NPC_FREED_SOUL = 11136, }; // TODO - likely entirely not needed workaround struct mob_restless_soulAI : public ScriptedAI { mob_restless_soulAI(Creature* pCreature) : ScriptedAI(pCreature) { Reset(); } ObjectGuid m_taggerGuid; uint32 m_uiDieTimer; bool m_bIsTagged; void Reset() override { m_taggerGuid.Clear(); m_uiDieTimer = 5000; m_bIsTagged = false; } void SpellHit(Unit* pCaster, const SpellEntry* pSpell) override { if (pCaster->GetTypeId() == TYPEID_PLAYER) { if (!m_bIsTagged && pSpell->Id == SPELL_EGAN_BLASTER && ((Player*)pCaster)->GetQuestStatus(QUEST_RESTLESS_SOUL) == QUEST_STATUS_INCOMPLETE) { m_bIsTagged = true; m_taggerGuid = pCaster->GetObjectGuid(); } } } void JustSummoned(Creature* pSummoned) override { if (pSummoned->GetEntry() == NPC_FREED_SOUL) { pSummoned->CastSpell(pSummoned, SPELL_SOUL_FREED, false); switch (urand(0, 3)) { case 0: DoScriptText(SAY_ZAPPED0, pSummoned); break; case 1: DoScriptText(SAY_ZAPPED1, pSummoned); break; case 2: DoScriptText(SAY_ZAPPED2, pSummoned); break; case 3: DoScriptText(SAY_ZAPPED3, pSummoned); break; } } } void JustDied(Unit* /*Killer*/) override { if (m_bIsTagged) m_creature->SummonCreature(NPC_FREED_SOUL, 0.0f, 0.0f, 0.0f, 0.0f, TEMPSUMMON_TIMED_DESPAWN, 300000); } void UpdateAI(const uint32 uiDiff) override { if (m_bIsTagged) { if (m_uiDieTimer < uiDiff) { if (Player* pPlayer = m_creature->GetMap()->GetPlayer(m_taggerGuid)) pPlayer->DealDamage(m_creature, m_creature->GetHealth(), nullptr, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, nullptr, false); } else m_uiDieTimer -= uiDiff; } } }; CreatureAI* GetAI_mob_restless_soul(Creature* pCreature) { return new mob_restless_soulAI(pCreature); } /*###### ## mobs_spectral_ghostly_citizen ######*/ enum { SPELL_HAUNTING_PHANTOM = 16336, SPELL_SLAP = 6754 }; struct mobs_spectral_ghostly_citizenAI : public ScriptedAI { mobs_spectral_ghostly_citizenAI(Creature* pCreature) : ScriptedAI(pCreature) {Reset();} uint32 m_uiDieTimer; bool m_bIsTagged; void Reset() override { m_uiDieTimer = 5000; m_bIsTagged = false; } void SpellHit(Unit* /*pCaster*/, const SpellEntry* pSpell) override { if (!m_bIsTagged && pSpell->Id == SPELL_EGAN_BLASTER) m_bIsTagged = true; } void JustDied(Unit* /*Killer*/) override { if (m_bIsTagged) { for (uint32 i = 0; i < 4; ++i) { float x, y, z; m_creature->GetRandomPoint(m_creature->GetPositionX(), m_creature->GetPositionY(), m_creature->GetPositionZ(), 20.0f, x, y, z); // 100%, 50%, 33%, 25% chance to spawn uint32 j = urand(0, i); if (j == 0) m_creature->SummonCreature(NPC_RESTLESS_SOUL, x, y, z, 0, TEMPSUMMON_DEAD_DESPAWN, 0); } } } void UpdateAI(const uint32 uiDiff) override { if (m_bIsTagged) { if (m_uiDieTimer < uiDiff) { m_creature->DealDamage(m_creature, m_creature->GetHealth(), nullptr, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, nullptr, false); } else m_uiDieTimer -= uiDiff; } if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) return; DoMeleeAttackIfReady(); } void ReceiveEmote(Player* pPlayer, uint32 uiEmote) override { switch (uiEmote) { case TEXTEMOTE_DANCE: EnterEvadeMode(); break; case TEXTEMOTE_RUDE: if (m_creature->IsWithinDistInMap(pPlayer, INTERACTION_DISTANCE)) m_creature->CastSpell(pPlayer, SPELL_SLAP, false); else m_creature->HandleEmote(EMOTE_ONESHOT_RUDE); break; case TEXTEMOTE_WAVE: m_creature->HandleEmote(EMOTE_ONESHOT_WAVE); break; case TEXTEMOTE_BOW: m_creature->HandleEmote(EMOTE_ONESHOT_BOW); break; case TEXTEMOTE_KISS: m_creature->HandleEmote(EMOTE_ONESHOT_FLEX); break; } } }; CreatureAI* GetAI_mobs_spectral_ghostly_citizen(Creature* pCreature) { return new mobs_spectral_ghostly_citizenAI(pCreature); } /*###### ## npc_aurius ######*/ enum { GOSSIP_TEXT_AURIUS_1 = 3755, GOSSIP_TEXT_AURIUS_2 = 3756, GOSSIP_TEXT_AURIUS_3 = 3757, }; bool QuestRewarded_npc_aurius(Player* pPlayer, Creature* pCreature, const Quest* pQuest) { ScriptedInstance* pInstance = (ScriptedInstance*)pCreature->GetInstanceData(); if (!pInstance) return false; if (pInstance->GetData(TYPE_BARON) == DONE || pInstance->GetData(TYPE_AURIUS) != NOT_STARTED) return false; if ((pQuest->GetQuestId() == QUEST_MEDALLION_FAITH)) pInstance->SetData(TYPE_AURIUS, SPECIAL); return true; } bool GossipHello_npc_aurius(Player* pPlayer, Creature* pCreature) { ScriptedInstance* pInstance = (ScriptedInstance*)pCreature->GetInstanceData(); uint32 ui_GossipId; if (pInstance) { if (pCreature->isQuestGiver()) pPlayer->PrepareQuestMenu(pCreature->GetObjectGuid()); switch (pInstance->GetData(TYPE_AURIUS)) { case SPECIAL: ui_GossipId = GOSSIP_TEXT_AURIUS_2; break; case DONE: ui_GossipId = GOSSIP_TEXT_AURIUS_3; break; default: ui_GossipId = GOSSIP_TEXT_AURIUS_1; break; } pPlayer->SEND_GOSSIP_MENU(ui_GossipId, pCreature->GetObjectGuid()); return true; } return false; } void AddSC_stratholme() { Script* pNewScript; pNewScript = new Script; pNewScript->Name = "go_service_gate"; pNewScript->pGOUse = &GOUse_go_service_gate; pNewScript->RegisterSelf(); pNewScript = new Script; pNewScript->Name = "go_gauntlet_gate"; pNewScript->pGOUse = &GOUse_go_gauntlet_gate; pNewScript->RegisterSelf(); pNewScript = new Script; pNewScript->Name = "go_stratholme_postbox"; pNewScript->pGOUse = &GOUse_go_stratholme_postbox; pNewScript->RegisterSelf(); pNewScript = new Script; pNewScript->Name = "mob_restless_soul"; pNewScript->GetAI = &GetAI_mob_restless_soul; pNewScript->RegisterSelf(); pNewScript = new Script; pNewScript->Name = "mobs_spectral_ghostly_citizen"; pNewScript->GetAI = &GetAI_mobs_spectral_ghostly_citizen; pNewScript->RegisterSelf(); pNewScript = new Script; pNewScript->Name = "npc_aurius"; pNewScript->pGossipHello = &GossipHello_npc_aurius; pNewScript->pQuestRewardedNPC = &QuestRewarded_npc_aurius; pNewScript->RegisterSelf(); }
Leadballoon2000/mangos-tbc
src/scriptdev2/scripts/eastern_kingdoms/stratholme/stratholme.cpp
C++
gpl-2.0
11,313
This directory contains files that demonstrate DieHard's effectiveness at preventing memory errors. The file `disaster.cpp` contains lots of memory errors that cause it to crash (Linux) or produce unwanted results (Windows). DieHard avoids all of these. The file `crash-mozilla.htm` does just what you think it might -- it crashes Mozilla (versions 1.0.2 and 1.7.3), usually immediately. DieHard generally prevents these crashes (one is an overflow, which DieHard avoids probabilistically). Similarly, the file `crash-firefox-1.0.4.html` does just what it says -- except when DieHard is running.
emeryberger/DieHard
demo/README.md
Markdown
gpl-2.0
599
meucarronovo ============
LARASOFTWARE/meucarronovo
README.md
Markdown
gpl-2.0
26
#ifndef _LINUX_MM_H #define _LINUX_MM_H #include <linux/errno.h> #ifdef __KERNEL__ #include <linux/gfp.h> #include <linux/bug.h> #include <linux/list.h> #include <linux/mmzone.h> #include <linux/rbtree.h> #include <linux/prio_tree.h> #include <linux/atomic.h> #include <linux/debug_locks.h> #include <linux/mm_types.h> #include <linux/range.h> #include <linux/pfn.h> #include <linux/bit_spinlock.h> #include <linux/shrinker.h> struct mempolicy; struct anon_vma; struct file_ra_state; struct user_struct; struct writeback_control; #ifndef CONFIG_DISCONTIGMEM /* Don't use mapnrs, do it properly */ extern unsigned long max_mapnr; #endif extern unsigned long num_physpages; extern unsigned long totalram_pages; #ifdef CONFIG_FIX_MOVABLE_ZONE extern unsigned long total_unmovable_pages; #endif extern void * high_memory; extern int page_cluster; #ifdef CONFIG_SYSCTL extern int sysctl_legacy_va_layout; #else #define sysctl_legacy_va_layout 0 #endif #include <asm/page.h> #include <asm/pgtable.h> #include <asm/processor.h> #define nth_page(page,n) pfn_to_page(page_to_pfn((page)) + (n)) /* to align the pointer to the (next) page boundary */ #define PAGE_ALIGN(addr) ALIGN(addr, PAGE_SIZE) /* * Linux kernel virtual memory manager primitives. * The idea being to have a "virtual" mm in the same way * we have a virtual fs - giving a cleaner interface to the * mm details, and allowing different kinds of memory mappings * (from shared memory to executable loading to arbitrary * mmap() functions). */ extern struct kmem_cache *vm_area_cachep; #ifndef CONFIG_MMU extern struct rb_root nommu_region_tree; extern struct rw_semaphore nommu_region_sem; extern unsigned int kobjsize(const void *objp); #endif /* * vm_flags in vm_area_struct, see mm_types.h. */ #define VM_READ 0x00000001 /* currently active flags */ #define VM_WRITE 0x00000002 #define VM_EXEC 0x00000004 #define VM_SHARED 0x00000008 /* mprotect() hardcodes VM_MAYREAD >> 4 == VM_READ, and so for r/w/x bits. */ #define VM_MAYREAD 0x00000010 /* limits for mprotect() etc */ #define VM_MAYWRITE 0x00000020 #define VM_MAYEXEC 0x00000040 #define VM_MAYSHARE 0x00000080 #define VM_GROWSDOWN 0x00000100 /* general info on the segment */ #if defined(CONFIG_STACK_GROWSUP) || defined(CONFIG_IA64) #define VM_GROWSUP 0x00000200 #else #define VM_GROWSUP 0x00000000 #define VM_NOHUGEPAGE 0x00000200 /* MADV_NOHUGEPAGE marked this vma */ #endif #define VM_PFNMAP 0x00000400 /* Page-ranges managed without "struct page", just pure PFN */ #define VM_DENYWRITE 0x00000800 /* ETXTBSY on write attempts.. */ #define VM_EXECUTABLE 0x00001000 #define VM_LOCKED 0x00002000 #define VM_IO 0x00004000 /* Memory mapped I/O or similar */ /* Used by sys_madvise() */ #define VM_SEQ_READ 0x00008000 /* App will access data sequentially */ #define VM_RAND_READ 0x00010000 /* App will not benefit from clustered reads */ #define VM_DONTCOPY 0x00020000 /* Do not copy this vma on fork */ #define VM_DONTEXPAND 0x00040000 /* Cannot expand with mremap() */ #define VM_RESERVED 0x00080000 /* Count as reserved_vm like IO */ #define VM_ACCOUNT 0x00100000 /* Is a VM accounted object */ #define VM_NORESERVE 0x00200000 /* should the VM suppress accounting */ #define VM_HUGETLB 0x00400000 /* Huge TLB Page VM */ #define VM_NONLINEAR 0x00800000 /* Is non-linear (remap_file_pages) */ #ifndef CONFIG_TRANSPARENT_HUGEPAGE #define VM_MAPPED_COPY 0x01000000 /* T if mapped copy of data (nommu mmap) */ #else #define VM_HUGEPAGE 0x01000000 /* MADV_HUGEPAGE marked this vma */ #endif #define VM_INSERTPAGE 0x02000000 /* The vma has had "vm_insert_page()" done on it */ #define VM_NODUMP 0x04000000 /* Do not include in the core dump */ #define VM_CAN_NONLINEAR 0x08000000 /* Has ->fault & does nonlinear pages */ #define VM_MIXEDMAP 0x10000000 /* Can contain "struct page" and pure PFN pages */ #define VM_SAO 0x20000000 /* Strong Access Ordering (powerpc) */ #define VM_PFN_AT_MMAP 0x40000000 /* PFNMAP vma that is fully mapped at mmap time */ #define VM_MERGEABLE 0x80000000 /* KSM may merge identical pages */ /* Bits set in the VMA until the stack is in its final location */ #define VM_STACK_INCOMPLETE_SETUP (VM_RAND_READ | VM_SEQ_READ) #ifndef VM_STACK_DEFAULT_FLAGS /* arch can override this */ #define VM_STACK_DEFAULT_FLAGS VM_DATA_DEFAULT_FLAGS #endif #ifdef CONFIG_STACK_GROWSUP #define VM_STACK_FLAGS (VM_GROWSUP | VM_STACK_DEFAULT_FLAGS | VM_ACCOUNT) #else #define VM_STACK_FLAGS (VM_GROWSDOWN | VM_STACK_DEFAULT_FLAGS | VM_ACCOUNT) #endif #define VM_READHINTMASK (VM_SEQ_READ | VM_RAND_READ) #define VM_ClearReadHint(v) (v)->vm_flags &= ~VM_READHINTMASK #define VM_NormalReadHint(v) (!((v)->vm_flags & VM_READHINTMASK)) #define VM_SequentialReadHint(v) ((v)->vm_flags & VM_SEQ_READ) #define VM_RandomReadHint(v) ((v)->vm_flags & VM_RAND_READ) /* * Special vmas that are non-mergable, non-mlock()able. * Note: mm/huge_memory.c VM_NO_THP depends on this definition. */ #define VM_SPECIAL (VM_IO | VM_DONTEXPAND | VM_RESERVED | VM_PFNMAP) /* * mapping from the currently active vm_flags protection bits (the * low four bits) to a page protection mask.. */ extern pgprot_t protection_map[16]; #define FAULT_FLAG_WRITE 0x01 /* Fault was a write access */ #define FAULT_FLAG_NONLINEAR 0x02 /* Fault was via a nonlinear mapping */ #define FAULT_FLAG_MKWRITE 0x04 /* Fault was mkwrite of existing pte */ #define FAULT_FLAG_ALLOW_RETRY 0x08 /* Retry fault if blocking */ #define FAULT_FLAG_RETRY_NOWAIT 0x10 /* Don't drop mmap_sem and wait when retrying */ #define FAULT_FLAG_KILLABLE 0x20 /* The fault task is in SIGKILL killable region */ /* * This interface is used by x86 PAT code to identify a pfn mapping that is * linear over entire vma. This is to optimize PAT code that deals with * marking the physical region with a particular prot. This is not for generic * mm use. Note also that this check will not work if the pfn mapping is * linear for a vma starting at physical address 0. In which case PAT code * falls back to slow path of reserving physical range page by page. */ static inline int is_linear_pfn_mapping(struct vm_area_struct *vma) { return !!(vma->vm_flags & VM_PFN_AT_MMAP); } static inline int is_pfn_mapping(struct vm_area_struct *vma) { return !!(vma->vm_flags & VM_PFNMAP); } /* * vm_fault is filled by the the pagefault handler and passed to the vma's * ->fault function. The vma's ->fault is responsible for returning a bitmask * of VM_FAULT_xxx flags that give details about how the fault was handled. * * pgoff should be used in favour of virtual_address, if possible. If pgoff * is used, one may set VM_CAN_NONLINEAR in the vma->vm_flags to get nonlinear * mapping support. */ struct vm_fault { unsigned int flags; /* FAULT_FLAG_xxx flags */ pgoff_t pgoff; /* Logical page offset based on vma */ void __user *virtual_address; /* Faulting virtual address */ struct page *page; /* ->fault handlers should return a * page here, unless VM_FAULT_NOPAGE * is set (which is also implied by * VM_FAULT_ERROR). */ }; /* * These are the virtual MM functions - opening of an area, closing and * unmapping it (needed to keep files on disk up-to-date etc), pointer * to the functions called when a no-page or a wp-page exception occurs. */ struct vm_operations_struct { void (*open)(struct vm_area_struct * area); void (*close)(struct vm_area_struct * area); int (*fault)(struct vm_area_struct *vma, struct vm_fault *vmf); /* notification that a previously read-only page is about to become * writable, if an error is returned it will cause a SIGBUS */ int (*page_mkwrite)(struct vm_area_struct *vma, struct vm_fault *vmf); /* called by access_process_vm when get_user_pages() fails, typically * for use by special VMAs that can switch between memory and hardware */ int (*access)(struct vm_area_struct *vma, unsigned long addr, void *buf, int len, int write); #ifdef CONFIG_NUMA /* * set_policy() op must add a reference to any non-NULL @new mempolicy * to hold the policy upon return. Caller should pass NULL @new to * remove a policy and fall back to surrounding context--i.e. do not * install a MPOL_DEFAULT policy, nor the task or system default * mempolicy. */ int (*set_policy)(struct vm_area_struct *vma, struct mempolicy *new); /* * get_policy() op must add reference [mpol_get()] to any policy at * (vma,addr) marked as MPOL_SHARED. The shared policy infrastructure * in mm/mempolicy.c will do this automatically. * get_policy() must NOT add a ref if the policy at (vma,addr) is not * marked as MPOL_SHARED. vma policies are protected by the mmap_sem. * If no [shared/vma] mempolicy exists at the addr, get_policy() op * must return NULL--i.e., do not "fallback" to task or system default * policy. */ struct mempolicy *(*get_policy)(struct vm_area_struct *vma, unsigned long addr); int (*migrate)(struct vm_area_struct *vma, const nodemask_t *from, const nodemask_t *to, unsigned long flags); #endif }; struct mmu_gather; struct inode; #define page_private(page) ((page)->private) #define set_page_private(page, v) ((page)->private = (v)) /* * FIXME: take this include out, include page-flags.h in * files which need it (119 of them) */ #include <linux/page-flags.h> #include <linux/huge_mm.h> /* * Methods to modify the page usage count. * * What counts for a page usage: * - cache mapping (page->mapping) * - private data (page->private) * - page mapped in a task's page tables, each mapping * is counted separately * * Also, many kernel routines increase the page count before a critical * routine so they can be sure the page doesn't go away from under them. */ /* * Drop a ref, return true if the refcount fell to zero (the page has no users) */ static inline int put_page_testzero(struct page *page) { VM_BUG_ON(atomic_read(&page->_count) == 0); return atomic_dec_and_test(&page->_count); } /* * Try to grab a ref unless the page has a refcount of zero, return false if * that is the case. */ static inline int get_page_unless_zero(struct page *page) { return atomic_inc_not_zero(&page->_count); } extern int page_is_ram(unsigned long pfn); /* Support for virtually mapped pages */ struct page *vmalloc_to_page(const void *addr); unsigned long vmalloc_to_pfn(const void *addr); /* * Determine if an address is within the vmalloc range * * On nommu, vmalloc/vfree wrap through kmalloc/kfree directly, so there * is no special casing required. */ #ifdef CONFIG_MMU extern int is_vmalloc_addr(const void *x); #else static inline int is_vmalloc_addr(const void *x) { return 0; } #endif #ifdef CONFIG_MMU extern int is_vmalloc_or_module_addr(const void *x); #else static inline int is_vmalloc_or_module_addr(const void *x) { return 0; } #endif static inline void compound_lock(struct page *page) { #ifdef CONFIG_TRANSPARENT_HUGEPAGE bit_spin_lock(PG_compound_lock, &page->flags); #endif } static inline void compound_unlock(struct page *page) { #ifdef CONFIG_TRANSPARENT_HUGEPAGE bit_spin_unlock(PG_compound_lock, &page->flags); #endif } static inline unsigned long compound_lock_irqsave(struct page *page) { unsigned long uninitialized_var(flags); #ifdef CONFIG_TRANSPARENT_HUGEPAGE local_irq_save(flags); compound_lock(page); #endif return flags; } static inline void compound_unlock_irqrestore(struct page *page, unsigned long flags) { #ifdef CONFIG_TRANSPARENT_HUGEPAGE compound_unlock(page); local_irq_restore(flags); #endif } static inline struct page *compound_head(struct page *page) { if (unlikely(PageTail(page))) return page->first_page; return page; } /* * The atomic page->_mapcount, starts from -1: so that transitions * both from it and to it can be tracked, using atomic_inc_and_test * and atomic_add_negative(-1). */ static inline void reset_page_mapcount(struct page *page) { atomic_set(&(page)->_mapcount, -1); } static inline int page_mapcount(struct page *page) { return atomic_read(&(page)->_mapcount) + 1; } static inline int page_count(struct page *page) { return atomic_read(&compound_head(page)->_count); } static inline void get_huge_page_tail(struct page *page) { /* * __split_huge_page_refcount() cannot run * from under us. */ VM_BUG_ON(page_mapcount(page) < 0); VM_BUG_ON(atomic_read(&page->_count) != 0); atomic_inc(&page->_mapcount); } extern bool __get_page_tail(struct page *page); static inline void get_page(struct page *page) { if (unlikely(PageTail(page))) if (likely(__get_page_tail(page))) return; /* * Getting a normal page or the head of a compound page * requires to already have an elevated page->_count. */ VM_BUG_ON(atomic_read(&page->_count) <= 0); atomic_inc(&page->_count); } static inline struct page *virt_to_head_page(const void *x) { struct page *page = virt_to_page(x); return compound_head(page); } /* * Setup the page count before being freed into the page allocator for * the first time (boot or memory hotplug) */ static inline void init_page_count(struct page *page) { atomic_set(&page->_count, 1); } /* * PageBuddy() indicate that the page is free and in the buddy system * (see mm/page_alloc.c). * * PAGE_BUDDY_MAPCOUNT_VALUE must be <= -2 but better not too close to * -2 so that an underflow of the page_mapcount() won't be mistaken * for a genuine PAGE_BUDDY_MAPCOUNT_VALUE. -128 can be created very * efficiently by most CPU architectures. */ #define PAGE_BUDDY_MAPCOUNT_VALUE (-128) static inline int PageBuddy(struct page *page) { return atomic_read(&page->_mapcount) == PAGE_BUDDY_MAPCOUNT_VALUE; } static inline void __SetPageBuddy(struct page *page) { VM_BUG_ON(atomic_read(&page->_mapcount) != -1); atomic_set(&page->_mapcount, PAGE_BUDDY_MAPCOUNT_VALUE); } static inline void __ClearPageBuddy(struct page *page) { VM_BUG_ON(!PageBuddy(page)); atomic_set(&page->_mapcount, -1); } void put_page(struct page *page); void put_pages_list(struct list_head *pages); void split_page(struct page *page, unsigned int order); int split_free_page(struct page *page); /* * Compound pages have a destructor function. Provide a * prototype for that function and accessor functions. * These are _only_ valid on the head of a PG_compound page. */ typedef void compound_page_dtor(struct page *); static inline void set_compound_page_dtor(struct page *page, compound_page_dtor *dtor) { page[1].lru.next = (void *)dtor; } static inline compound_page_dtor *get_compound_page_dtor(struct page *page) { return (compound_page_dtor *)page[1].lru.next; } static inline int compound_order(struct page *page) { if (!PageHead(page)) return 0; return (unsigned long)page[1].lru.prev; } static inline int compound_trans_order(struct page *page) { int order; unsigned long flags; if (!PageHead(page)) return 0; flags = compound_lock_irqsave(page); order = compound_order(page); compound_unlock_irqrestore(page, flags); return order; } static inline void set_compound_order(struct page *page, unsigned long order) { page[1].lru.prev = (void *)order; } #ifdef CONFIG_MMU /* * Do pte_mkwrite, but only if the vma says VM_WRITE. We do this when * servicing faults for write access. In the normal case, do always want * pte_mkwrite. But get_user_pages can cause write faults for mappings * that do not have writing enabled, when used by access_process_vm. */ static inline pte_t maybe_mkwrite(pte_t pte, struct vm_area_struct *vma) { if (likely(vma->vm_flags & VM_WRITE)) pte = pte_mkwrite(pte); return pte; } #endif /* * Multiple processes may "see" the same page. E.g. for untouched * mappings of /dev/null, all processes see the same page full of * zeroes, and text pages of executables and shared libraries have * only one copy in memory, at most, normally. * * For the non-reserved pages, page_count(page) denotes a reference count. * page_count() == 0 means the page is free. page->lru is then used for * freelist management in the buddy allocator. * page_count() > 0 means the page has been allocated. * * Pages are allocated by the slab allocator in order to provide memory * to kmalloc and kmem_cache_alloc. In this case, the management of the * page, and the fields in 'struct page' are the responsibility of mm/slab.c * unless a particular usage is carefully commented. (the responsibility of * freeing the kmalloc memory is the caller's, of course). * * A page may be used by anyone else who does a __get_free_page(). * In this case, page_count still tracks the references, and should only * be used through the normal accessor functions. The top bits of page->flags * and page->virtual store page management information, but all other fields * are unused and could be used privately, carefully. The management of this * page is the responsibility of the one who allocated it, and those who have * subsequently been given references to it. * * The other pages (we may call them "pagecache pages") are completely * managed by the Linux memory manager: I/O, buffers, swapping etc. * The following discussion applies only to them. * * A pagecache page contains an opaque `private' member, which belongs to the * page's address_space. Usually, this is the address of a circular list of * the page's disk buffers. PG_private must be set to tell the VM to call * into the filesystem to release these pages. * * A page may belong to an inode's memory mapping. In this case, page->mapping * is the pointer to the inode, and page->index is the file offset of the page, * in units of PAGE_CACHE_SIZE. * * If pagecache pages are not associated with an inode, they are said to be * anonymous pages. These may become associated with the swapcache, and in that * case PG_swapcache is set, and page->private is an offset into the swapcache. * * In either case (swapcache or inode backed), the pagecache itself holds one * reference to the page. Setting PG_private should also increment the * refcount. The each user mapping also has a reference to the page. * * The pagecache pages are stored in a per-mapping radix tree, which is * rooted at mapping->page_tree, and indexed by offset. * Where 2.4 and early 2.6 kernels kept dirty/clean pages in per-address_space * lists, we instead now tag pages as dirty/writeback in the radix tree. * * All pagecache pages may be subject to I/O: * - inode pages may need to be read from disk, * - inode pages which have been modified and are MAP_SHARED may need * to be written back to the inode on disk, * - anonymous pages (including MAP_PRIVATE file mappings) which have been * modified may need to be swapped out to swap space and (later) to be read * back into memory. */ /* * The zone field is never updated after free_area_init_core() * sets it, so none of the operations on it need to be atomic. */ /* * page->flags layout: * * There are three possibilities for how page->flags get * laid out. The first is for the normal case, without * sparsemem. The second is for sparsemem when there is * plenty of space for node and section. The last is when * we have run out of space and have to fall back to an * alternate (slower) way of determining the node. * * No sparsemem or sparsemem vmemmap: | NODE | ZONE | ... | FLAGS | * classic sparse with space for node:| SECTION | NODE | ZONE | ... | FLAGS | * classic sparse no space for node: | SECTION | ZONE | ... | FLAGS | */ #if defined(CONFIG_SPARSEMEM) && !defined(CONFIG_SPARSEMEM_VMEMMAP) #define SECTIONS_WIDTH SECTIONS_SHIFT #else #define SECTIONS_WIDTH 0 #endif #define ZONES_WIDTH ZONES_SHIFT #if SECTIONS_WIDTH+ZONES_WIDTH+NODES_SHIFT <= BITS_PER_LONG - NR_PAGEFLAGS #define NODES_WIDTH NODES_SHIFT #else #ifdef CONFIG_SPARSEMEM_VMEMMAP #error "Vmemmap: No space for nodes field in page flags" #endif #define NODES_WIDTH 0 #endif /* Page flags: | [SECTION] | [NODE] | ZONE | ... | FLAGS | */ #define SECTIONS_PGOFF ((sizeof(unsigned long)*8) - SECTIONS_WIDTH) #define NODES_PGOFF (SECTIONS_PGOFF - NODES_WIDTH) #define ZONES_PGOFF (NODES_PGOFF - ZONES_WIDTH) /* * We are going to use the flags for the page to node mapping if its in * there. This includes the case where there is no node, so it is implicit. */ #if !(NODES_WIDTH > 0 || NODES_SHIFT == 0) #define NODE_NOT_IN_PAGE_FLAGS #endif /* * Define the bit shifts to access each section. For non-existent * sections we define the shift as 0; that plus a 0 mask ensures * the compiler will optimise away reference to them. */ #define SECTIONS_PGSHIFT (SECTIONS_PGOFF * (SECTIONS_WIDTH != 0)) #define NODES_PGSHIFT (NODES_PGOFF * (NODES_WIDTH != 0)) #define ZONES_PGSHIFT (ZONES_PGOFF * (ZONES_WIDTH != 0)) /* NODE:ZONE or SECTION:ZONE is used to ID a zone for the buddy allocator */ #ifdef NODE_NOT_IN_PAGE_FLAGS #define ZONEID_SHIFT (SECTIONS_SHIFT + ZONES_SHIFT) #define ZONEID_PGOFF ((SECTIONS_PGOFF < ZONES_PGOFF)? \ SECTIONS_PGOFF : ZONES_PGOFF) #else #define ZONEID_SHIFT (NODES_SHIFT + ZONES_SHIFT) #define ZONEID_PGOFF ((NODES_PGOFF < ZONES_PGOFF)? \ NODES_PGOFF : ZONES_PGOFF) #endif #define ZONEID_PGSHIFT (ZONEID_PGOFF * (ZONEID_SHIFT != 0)) #if SECTIONS_WIDTH+NODES_WIDTH+ZONES_WIDTH > BITS_PER_LONG - NR_PAGEFLAGS #error SECTIONS_WIDTH+NODES_WIDTH+ZONES_WIDTH > BITS_PER_LONG - NR_PAGEFLAGS #endif #define ZONES_MASK ((1UL << ZONES_WIDTH) - 1) #define NODES_MASK ((1UL << NODES_WIDTH) - 1) #define SECTIONS_MASK ((1UL << SECTIONS_WIDTH) - 1) #define ZONEID_MASK ((1UL << ZONEID_SHIFT) - 1) static inline enum zone_type page_zonenum(const struct page *page) { return (page->flags >> ZONES_PGSHIFT) & ZONES_MASK; } /* * The identification function is only used by the buddy allocator for * determining if two pages could be buddies. We are not really * identifying a zone since we could be using a the section number * id if we have not node id available in page flags. * We guarantee only that it will return the same value for two * combinable pages in a zone. */ static inline int page_zone_id(struct page *page) { return (page->flags >> ZONEID_PGSHIFT) & ZONEID_MASK; } static inline int zone_to_nid(struct zone *zone) { #ifdef CONFIG_NUMA return zone->node; #else return 0; #endif } #ifdef NODE_NOT_IN_PAGE_FLAGS extern int page_to_nid(const struct page *page); #else static inline int page_to_nid(const struct page *page) { return (page->flags >> NODES_PGSHIFT) & NODES_MASK; } #endif static inline struct zone *page_zone(const struct page *page) { return &NODE_DATA(page_to_nid(page))->node_zones[page_zonenum(page)]; } #if defined(CONFIG_SPARSEMEM) && !defined(CONFIG_SPARSEMEM_VMEMMAP) static inline void set_page_section(struct page *page, unsigned long section) { page->flags &= ~(SECTIONS_MASK << SECTIONS_PGSHIFT); page->flags |= (section & SECTIONS_MASK) << SECTIONS_PGSHIFT; } static inline unsigned long page_to_section(const struct page *page) { return (page->flags >> SECTIONS_PGSHIFT) & SECTIONS_MASK; } #endif static inline void set_page_zone(struct page *page, enum zone_type zone) { page->flags &= ~(ZONES_MASK << ZONES_PGSHIFT); page->flags |= (zone & ZONES_MASK) << ZONES_PGSHIFT; } static inline void set_page_node(struct page *page, unsigned long node) { page->flags &= ~(NODES_MASK << NODES_PGSHIFT); page->flags |= (node & NODES_MASK) << NODES_PGSHIFT; } static inline void set_page_links(struct page *page, enum zone_type zone, unsigned long node, unsigned long pfn) { set_page_zone(page, zone); set_page_node(page, node); #if defined(CONFIG_SPARSEMEM) && !defined(CONFIG_SPARSEMEM_VMEMMAP) set_page_section(page, pfn_to_section_nr(pfn)); #endif } /* * Some inline functions in vmstat.h depend on page_zone() */ #include <linux/vmstat.h> static __always_inline void *lowmem_page_address(const struct page *page) { return __va(PFN_PHYS(page_to_pfn(page))); } #if defined(CONFIG_HIGHMEM) && !defined(WANT_PAGE_VIRTUAL) #define HASHED_PAGE_VIRTUAL #endif #if defined(WANT_PAGE_VIRTUAL) #define page_address(page) ((page)->virtual) #define set_page_address(page, address) \ do { \ (page)->virtual = (address); \ } while(0) #define page_address_init() do { } while(0) #endif #if defined(HASHED_PAGE_VIRTUAL) void *page_address(const struct page *page); void set_page_address(struct page *page, void *virtual); void page_address_init(void); #endif #if !defined(HASHED_PAGE_VIRTUAL) && !defined(WANT_PAGE_VIRTUAL) #define page_address(page) lowmem_page_address(page) #define set_page_address(page, address) do { } while(0) #define page_address_init() do { } while(0) #endif /* * On an anonymous page mapped into a user virtual memory area, * page->mapping points to its anon_vma, not to a struct address_space; * with the PAGE_MAPPING_ANON bit set to distinguish it. See rmap.h. * * On an anonymous page in a VM_MERGEABLE area, if CONFIG_KSM is enabled, * the PAGE_MAPPING_KSM bit may be set along with the PAGE_MAPPING_ANON bit; * and then page->mapping points, not to an anon_vma, but to a private * structure which KSM associates with that merged page. See ksm.h. * * PAGE_MAPPING_KSM without PAGE_MAPPING_ANON is currently never used. * * Please note that, confusingly, "page_mapping" refers to the inode * address_space which maps the page from disk; whereas "page_mapped" * refers to user virtual address space into which the page is mapped. */ #define PAGE_MAPPING_ANON 1 #define PAGE_MAPPING_KSM 2 #define PAGE_MAPPING_FLAGS (PAGE_MAPPING_ANON | PAGE_MAPPING_KSM) extern struct address_space swapper_space; static inline struct address_space *page_mapping(struct page *page) { struct address_space *mapping = page->mapping; VM_BUG_ON(PageSlab(page)); if (unlikely(PageSwapCache(page))) mapping = &swapper_space; else if ((unsigned long)mapping & PAGE_MAPPING_ANON) mapping = NULL; return mapping; } /* Neutral page->mapping pointer to address_space or anon_vma or other */ static inline void *page_rmapping(struct page *page) { return (void *)((unsigned long)page->mapping & ~PAGE_MAPPING_FLAGS); } extern struct address_space *__page_file_mapping(struct page *); static inline struct address_space *page_file_mapping(struct page *page) { if (unlikely(PageSwapCache(page))) return __page_file_mapping(page); return page->mapping; } static inline int PageAnon(struct page *page) { return ((unsigned long)page->mapping & PAGE_MAPPING_ANON) != 0; } /* * Return the pagecache index of the passed page. Regular pagecache pages * use ->index whereas swapcache pages use ->private */ static inline pgoff_t page_index(struct page *page) { if (unlikely(PageSwapCache(page))) return page_private(page); return page->index; } extern pgoff_t __page_file_index(struct page *page); /* * Return the file index of the page. Regular pagecache pages use ->index * whereas swapcache pages use swp_offset(->private) */ static inline pgoff_t page_file_index(struct page *page) { if (unlikely(PageSwapCache(page))) return __page_file_index(page); return page->index; } /* * Return true if this page is mapped into pagetables. */ static inline int page_mapped(struct page *page) { return atomic_read(&(page)->_mapcount) >= 0; } /* * Different kinds of faults, as returned by handle_mm_fault(). * Used to decide whether a process gets delivered SIGBUS or * just gets major/minor fault counters bumped up. */ #define VM_FAULT_MINOR 0 /* For backwards compat. Remove me quickly. */ #define VM_FAULT_OOM 0x0001 #define VM_FAULT_SIGBUS 0x0002 #define VM_FAULT_MAJOR 0x0004 #define VM_FAULT_WRITE 0x0008 /* Special case for get_user_pages */ #define VM_FAULT_HWPOISON 0x0010 /* Hit poisoned small page */ #define VM_FAULT_HWPOISON_LARGE 0x0020 /* Hit poisoned large page. Index encoded in upper bits */ #define VM_FAULT_NOPAGE 0x0100 /* ->fault installed the pte, not return page */ #define VM_FAULT_LOCKED 0x0200 /* ->fault locked the returned page */ #define VM_FAULT_RETRY 0x0400 /* ->fault blocked, must retry */ #define VM_FAULT_HWPOISON_LARGE_MASK 0xf000 /* encodes hpage index for large hwpoison */ #define VM_FAULT_ERROR (VM_FAULT_OOM | VM_FAULT_SIGBUS | VM_FAULT_HWPOISON | \ VM_FAULT_HWPOISON_LARGE) /* Encode hstate index for a hwpoisoned large page */ #define VM_FAULT_SET_HINDEX(x) ((x) << 12) #define VM_FAULT_GET_HINDEX(x) (((x) >> 12) & 0xf) /* * Can be called by the pagefault handler when it gets a VM_FAULT_OOM. */ extern void pagefault_out_of_memory(void); #define offset_in_page(p) ((unsigned long)(p) & ~PAGE_MASK) /* * Flags passed to show_mem() and show_free_areas() to suppress output in * various contexts. */ #define SHOW_MEM_FILTER_NODES (0x0001u) /* filter disallowed nodes */ extern void show_free_areas(unsigned int flags); extern bool skip_free_areas_node(unsigned int flags, int nid); int shmem_lock(struct file *file, int lock, struct user_struct *user); struct file *shmem_file_setup(const char *name, loff_t size, unsigned long flags); void shmem_set_file(struct vm_area_struct *vma, struct file *file); int shmem_zero_setup(struct vm_area_struct *); extern int can_do_mlock(void); extern int user_shm_lock(size_t, struct user_struct *); extern void user_shm_unlock(size_t, struct user_struct *); /* * Parameter block passed down to zap_pte_range in exceptional cases. */ struct zap_details { struct vm_area_struct *nonlinear_vma; /* Check page->index if set */ struct address_space *check_mapping; /* Check page->mapping if set */ pgoff_t first_index; /* Lowest page->index to unmap */ pgoff_t last_index; /* Highest page->index to unmap */ }; struct page *vm_normal_page(struct vm_area_struct *vma, unsigned long addr, pte_t pte); int zap_vma_ptes(struct vm_area_struct *vma, unsigned long address, unsigned long size); void zap_page_range(struct vm_area_struct *vma, unsigned long address, unsigned long size, struct zap_details *); void unmap_vmas(struct mmu_gather *tlb, struct vm_area_struct *start_vma, unsigned long start_addr, unsigned long end_addr, unsigned long *nr_accounted, struct zap_details *); /** * mm_walk - callbacks for walk_page_range * @pgd_entry: if set, called for each non-empty PGD (top-level) entry * @pud_entry: if set, called for each non-empty PUD (2nd-level) entry * @pmd_entry: if set, called for each non-empty PMD (3rd-level) entry * this handler is required to be able to handle * pmd_trans_huge() pmds. They may simply choose to * split_huge_page() instead of handling it explicitly. * @pte_entry: if set, called for each non-empty PTE (4th-level) entry * @pte_hole: if set, called for each hole at all levels * @hugetlb_entry: if set, called for each hugetlb entry * *Caution*: The caller must hold mmap_sem() if @hugetlb_entry * is used. * * (see walk_page_range for more details) */ struct mm_walk { int (*pgd_entry)(pgd_t *, unsigned long, unsigned long, struct mm_walk *); int (*pud_entry)(pud_t *, unsigned long, unsigned long, struct mm_walk *); int (*pmd_entry)(pmd_t *, unsigned long, unsigned long, struct mm_walk *); int (*pte_entry)(pte_t *, unsigned long, unsigned long, struct mm_walk *); int (*pte_hole)(unsigned long, unsigned long, struct mm_walk *); int (*hugetlb_entry)(pte_t *, unsigned long, unsigned long, unsigned long, struct mm_walk *); struct mm_struct *mm; void *private; }; int walk_page_range(unsigned long addr, unsigned long end, struct mm_walk *walk); void free_pgd_range(struct mmu_gather *tlb, unsigned long addr, unsigned long end, unsigned long floor, unsigned long ceiling); int copy_page_range(struct mm_struct *dst, struct mm_struct *src, struct vm_area_struct *vma); void unmap_mapping_range(struct address_space *mapping, loff_t const holebegin, loff_t const holelen, int even_cows); int follow_pfn(struct vm_area_struct *vma, unsigned long address, unsigned long *pfn); int follow_phys(struct vm_area_struct *vma, unsigned long address, unsigned int flags, unsigned long *prot, resource_size_t *phys); int generic_access_phys(struct vm_area_struct *vma, unsigned long addr, void *buf, int len, int write); static inline void unmap_shared_mapping_range(struct address_space *mapping, loff_t const holebegin, loff_t const holelen) { unmap_mapping_range(mapping, holebegin, holelen, 0); } extern void truncate_pagecache(struct inode *inode, loff_t old, loff_t new); extern void truncate_setsize(struct inode *inode, loff_t newsize); extern int vmtruncate(struct inode *inode, loff_t offset); extern int vmtruncate_range(struct inode *inode, loff_t offset, loff_t end); void truncate_pagecache_range(struct inode *inode, loff_t offset, loff_t end); int truncate_inode_page(struct address_space *mapping, struct page *page); int generic_error_remove_page(struct address_space *mapping, struct page *page); int invalidate_inode_page(struct page *page); #ifdef CONFIG_MMU extern int handle_mm_fault(struct mm_struct *mm, struct vm_area_struct *vma, unsigned long address, unsigned int flags); extern int fixup_user_fault(struct task_struct *tsk, struct mm_struct *mm, unsigned long address, unsigned int fault_flags); #else static inline int handle_mm_fault(struct mm_struct *mm, struct vm_area_struct *vma, unsigned long address, unsigned int flags) { /* should never happen if there's no MMU */ BUG(); return VM_FAULT_SIGBUS; } static inline int fixup_user_fault(struct task_struct *tsk, struct mm_struct *mm, unsigned long address, unsigned int fault_flags) { /* should never happen if there's no MMU */ BUG(); return -EFAULT; } #endif extern int make_pages_present(unsigned long addr, unsigned long end); extern int access_process_vm(struct task_struct *tsk, unsigned long addr, void *buf, int len, int write); extern int access_remote_vm(struct mm_struct *mm, unsigned long addr, void *buf, int len, int write); int __get_user_pages(struct task_struct *tsk, struct mm_struct *mm, unsigned long start, int len, unsigned int foll_flags, struct page **pages, struct vm_area_struct **vmas, int *nonblocking); int get_user_pages(struct task_struct *tsk, struct mm_struct *mm, unsigned long start, int nr_pages, int write, int force, struct page **pages, struct vm_area_struct **vmas); int get_user_pages_fast(unsigned long start, int nr_pages, int write, struct page **pages); struct page *get_dump_page(unsigned long addr); extern int try_to_release_page(struct page * page, gfp_t gfp_mask); extern void do_invalidatepage(struct page *page, unsigned long offset); int __set_page_dirty_nobuffers(struct page *page); int __set_page_dirty_no_writeback(struct page *page); int redirty_page_for_writepage(struct writeback_control *wbc, struct page *page); void account_page_dirtied(struct page *page, struct address_space *mapping); void account_page_writeback(struct page *page); int set_page_dirty(struct page *page); int set_page_dirty_lock(struct page *page); int clear_page_dirty_for_io(struct page *page); /* Is the vma a continuation of the stack vma above it? */ static inline int vma_growsdown(struct vm_area_struct *vma, unsigned long addr) { return vma && (vma->vm_end == addr) && (vma->vm_flags & VM_GROWSDOWN); } static inline int stack_guard_page_start(struct vm_area_struct *vma, unsigned long addr) { return (vma->vm_flags & VM_GROWSDOWN) && (vma->vm_start == addr) && !vma_growsdown(vma->vm_prev, addr); } /* Is the vma a continuation of the stack vma below it? */ static inline int vma_growsup(struct vm_area_struct *vma, unsigned long addr) { return vma && (vma->vm_start == addr) && (vma->vm_flags & VM_GROWSUP); } static inline int stack_guard_page_end(struct vm_area_struct *vma, unsigned long addr) { return (vma->vm_flags & VM_GROWSUP) && (vma->vm_end == addr) && !vma_growsup(vma->vm_next, addr); } extern pid_t vm_is_stack(struct task_struct *task, struct vm_area_struct *vma, int in_group); extern unsigned long move_page_tables(struct vm_area_struct *vma, unsigned long old_addr, struct vm_area_struct *new_vma, unsigned long new_addr, unsigned long len); extern unsigned long do_mremap(unsigned long addr, unsigned long old_len, unsigned long new_len, unsigned long flags, unsigned long new_addr); extern int mprotect_fixup(struct vm_area_struct *vma, struct vm_area_struct **pprev, unsigned long start, unsigned long end, unsigned long newflags); /* * doesn't attempt to fault and will return short. */ int __get_user_pages_fast(unsigned long start, int nr_pages, int write, struct page **pages); /* * per-process(per-mm_struct) statistics. */ static inline unsigned long get_mm_counter(struct mm_struct *mm, int member) { long val = atomic_long_read(&mm->rss_stat.count[member]); #ifdef SPLIT_RSS_COUNTING /* * counter is updated in asynchronous manner and may go to minus. * But it's never be expected number for users. */ if (val < 0) val = 0; #endif return (unsigned long)val; } static inline void add_mm_counter(struct mm_struct *mm, int member, long value) { atomic_long_add(value, &mm->rss_stat.count[member]); } static inline void inc_mm_counter(struct mm_struct *mm, int member) { atomic_long_inc(&mm->rss_stat.count[member]); } static inline void dec_mm_counter(struct mm_struct *mm, int member) { atomic_long_dec(&mm->rss_stat.count[member]); } static inline unsigned long get_mm_rss(struct mm_struct *mm) { return get_mm_counter(mm, MM_FILEPAGES) + get_mm_counter(mm, MM_ANONPAGES); } static inline unsigned long get_mm_hiwater_rss(struct mm_struct *mm) { return max(mm->hiwater_rss, get_mm_rss(mm)); } static inline unsigned long get_mm_hiwater_vm(struct mm_struct *mm) { return max(mm->hiwater_vm, mm->total_vm); } static inline void update_hiwater_rss(struct mm_struct *mm) { unsigned long _rss = get_mm_rss(mm); if ((mm)->hiwater_rss < _rss) (mm)->hiwater_rss = _rss; } static inline void update_hiwater_vm(struct mm_struct *mm) { if (mm->hiwater_vm < mm->total_vm) mm->hiwater_vm = mm->total_vm; } static inline void setmax_mm_hiwater_rss(unsigned long *maxrss, struct mm_struct *mm) { unsigned long hiwater_rss = get_mm_hiwater_rss(mm); if (*maxrss < hiwater_rss) *maxrss = hiwater_rss; } #if defined(SPLIT_RSS_COUNTING) void sync_mm_rss(struct mm_struct *mm); #else static inline void sync_mm_rss(struct mm_struct *mm) { } #endif int vma_wants_writenotify(struct vm_area_struct *vma); extern pte_t *__get_locked_pte(struct mm_struct *mm, unsigned long addr, spinlock_t **ptl); static inline pte_t *get_locked_pte(struct mm_struct *mm, unsigned long addr, spinlock_t **ptl) { pte_t *ptep; __cond_lock(*ptl, ptep = __get_locked_pte(mm, addr, ptl)); return ptep; } #ifdef __PAGETABLE_PUD_FOLDED static inline int __pud_alloc(struct mm_struct *mm, pgd_t *pgd, unsigned long address) { return 0; } #else int __pud_alloc(struct mm_struct *mm, pgd_t *pgd, unsigned long address); #endif #ifdef __PAGETABLE_PMD_FOLDED static inline int __pmd_alloc(struct mm_struct *mm, pud_t *pud, unsigned long address) { return 0; } #else int __pmd_alloc(struct mm_struct *mm, pud_t *pud, unsigned long address); #endif int __pte_alloc(struct mm_struct *mm, struct vm_area_struct *vma, pmd_t *pmd, unsigned long address); int __pte_alloc_kernel(pmd_t *pmd, unsigned long address); /* * The following ifdef needed to get the 4level-fixup.h header to work. * Remove it when 4level-fixup.h has been removed. */ #if defined(CONFIG_MMU) && !defined(__ARCH_HAS_4LEVEL_HACK) static inline pud_t *pud_alloc(struct mm_struct *mm, pgd_t *pgd, unsigned long address) { return (unlikely(pgd_none(*pgd)) && __pud_alloc(mm, pgd, address))? NULL: pud_offset(pgd, address); } static inline pmd_t *pmd_alloc(struct mm_struct *mm, pud_t *pud, unsigned long address) { return (unlikely(pud_none(*pud)) && __pmd_alloc(mm, pud, address))? NULL: pmd_offset(pud, address); } #endif /* CONFIG_MMU && !__ARCH_HAS_4LEVEL_HACK */ #if USE_SPLIT_PTLOCKS /* * We tuck a spinlock to guard each pagetable page into its struct page, * at page->private, with BUILD_BUG_ON to make sure that this will not * overflow into the next struct page (as it might with DEBUG_SPINLOCK). * When freeing, reset page->mapping so free_pages_check won't complain. */ #define __pte_lockptr(page) &((page)->ptl) #define pte_lock_init(_page) do { \ spin_lock_init(__pte_lockptr(_page)); \ } while (0) #define pte_lock_deinit(page) ((page)->mapping = NULL) #define pte_lockptr(mm, pmd) ({(void)(mm); __pte_lockptr(pmd_page(*(pmd)));}) #else /* !USE_SPLIT_PTLOCKS */ /* * We use mm->page_table_lock to guard all pagetable pages of the mm. */ #define pte_lock_init(page) do {} while (0) #define pte_lock_deinit(page) do {} while (0) #define pte_lockptr(mm, pmd) ({(void)(pmd); &(mm)->page_table_lock;}) #endif /* USE_SPLIT_PTLOCKS */ static inline void pgtable_page_ctor(struct page *page) { pte_lock_init(page); inc_zone_page_state(page, NR_PAGETABLE); } static inline void pgtable_page_dtor(struct page *page) { pte_lock_deinit(page); dec_zone_page_state(page, NR_PAGETABLE); } #define pte_offset_map_lock(mm, pmd, address, ptlp) \ ({ \ spinlock_t *__ptl = pte_lockptr(mm, pmd); \ pte_t *__pte = pte_offset_map(pmd, address); \ *(ptlp) = __ptl; \ spin_lock(__ptl); \ __pte; \ }) #define pte_unmap_unlock(pte, ptl) do { \ spin_unlock(ptl); \ pte_unmap(pte); \ } while (0) #define pte_alloc_map(mm, vma, pmd, address) \ ((unlikely(pmd_none(*(pmd))) && __pte_alloc(mm, vma, \ pmd, address))? \ NULL: pte_offset_map(pmd, address)) #define pte_alloc_map_lock(mm, pmd, address, ptlp) \ ((unlikely(pmd_none(*(pmd))) && __pte_alloc(mm, NULL, \ pmd, address))? \ NULL: pte_offset_map_lock(mm, pmd, address, ptlp)) #define pte_alloc_kernel(pmd, address) \ ((unlikely(pmd_none(*(pmd))) && __pte_alloc_kernel(pmd, address))? \ NULL: pte_offset_kernel(pmd, address)) extern void free_area_init(unsigned long * zones_size); extern void free_area_init_node(int nid, unsigned long * zones_size, unsigned long zone_start_pfn, unsigned long *zholes_size); extern void free_initmem(void); #ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP /* * With CONFIG_HAVE_MEMBLOCK_NODE_MAP set, an architecture may initialise its * zones, allocate the backing mem_map and account for memory holes in a more * architecture independent manner. This is a substitute for creating the * zone_sizes[] and zholes_size[] arrays and passing them to * free_area_init_node() * * An architecture is expected to register range of page frames backed by * physical memory with memblock_add[_node]() before calling * free_area_init_nodes() passing in the PFN each zone ends at. At a basic * usage, an architecture is expected to do something like * * unsigned long max_zone_pfns[MAX_NR_ZONES] = {max_dma, max_normal_pfn, * max_highmem_pfn}; * for_each_valid_physical_page_range() * memblock_add_node(base, size, nid) * free_area_init_nodes(max_zone_pfns); * * free_bootmem_with_active_regions() calls free_bootmem_node() for each * registered physical page range. Similarly * sparse_memory_present_with_active_regions() calls memory_present() for * each range when SPARSEMEM is enabled. * * See mm/page_alloc.c for more information on each function exposed by * CONFIG_HAVE_MEMBLOCK_NODE_MAP. */ extern void free_area_init_nodes(unsigned long *max_zone_pfn); unsigned long node_map_pfn_alignment(void); unsigned long __absent_pages_in_range(int nid, unsigned long start_pfn, unsigned long end_pfn); extern unsigned long absent_pages_in_range(unsigned long start_pfn, unsigned long end_pfn); extern void get_pfn_range_for_nid(unsigned int nid, unsigned long *start_pfn, unsigned long *end_pfn); extern unsigned long find_min_pfn_with_active_regions(void); extern void free_bootmem_with_active_regions(int nid, unsigned long max_low_pfn); extern void sparse_memory_present_with_active_regions(int nid); #endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */ #if !defined(CONFIG_HAVE_MEMBLOCK_NODE_MAP) && \ !defined(CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID) static inline int __early_pfn_to_nid(unsigned long pfn) { return 0; } #else /* please see mm/page_alloc.c */ extern int __meminit early_pfn_to_nid(unsigned long pfn); #ifdef CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID /* there is a per-arch backend function. */ extern int __meminit __early_pfn_to_nid(unsigned long pfn); #endif /* CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID */ #endif extern void set_dma_reserve(unsigned long new_dma_reserve); extern void memmap_init_zone(unsigned long, int, unsigned long, unsigned long, enum memmap_context); extern void setup_per_zone_wmarks(void); extern int __meminit init_per_zone_wmark_min(void); extern void mem_init(void); extern void __init mmap_init(void); extern void show_mem(unsigned int flags); extern void si_meminfo(struct sysinfo * val); extern void si_meminfo_node(struct sysinfo *val, int nid); extern int after_bootmem; extern __printf(3, 4) void warn_alloc_failed(gfp_t gfp_mask, int order, const char *fmt, ...); extern void setup_per_cpu_pageset(void); extern void zone_pcp_update(struct zone *zone); /* nommu.c */ extern atomic_long_t mmap_pages_allocated; extern int nommu_shrink_inode_mappings(struct inode *, size_t, size_t); /* prio_tree.c */ void vma_prio_tree_add(struct vm_area_struct *, struct vm_area_struct *old); void vma_prio_tree_insert(struct vm_area_struct *, struct prio_tree_root *); void vma_prio_tree_remove(struct vm_area_struct *, struct prio_tree_root *); struct vm_area_struct *vma_prio_tree_next(struct vm_area_struct *vma, struct prio_tree_iter *iter); #define vma_prio_tree_foreach(vma, iter, root, begin, end) \ for (prio_tree_iter_init(iter, root, begin, end), vma = NULL; \ (vma = vma_prio_tree_next(vma, iter)); ) static inline void vma_nonlinear_insert(struct vm_area_struct *vma, struct list_head *list) { vma->shared.vm_set.parent = NULL; list_add_tail(&vma->shared.vm_set.list, list); } /* mmap.c */ extern int __vm_enough_memory(struct mm_struct *mm, long pages, int cap_sys_admin); extern int vma_adjust(struct vm_area_struct *vma, unsigned long start, unsigned long end, pgoff_t pgoff, struct vm_area_struct *insert); extern struct vm_area_struct *vma_merge(struct mm_struct *, struct vm_area_struct *prev, unsigned long addr, unsigned long end, unsigned long vm_flags, struct anon_vma *, struct file *, pgoff_t, struct mempolicy *); extern struct anon_vma *find_mergeable_anon_vma(struct vm_area_struct *); extern int split_vma(struct mm_struct *, struct vm_area_struct *, unsigned long addr, int new_below); extern int insert_vm_struct(struct mm_struct *, struct vm_area_struct *); extern void __vma_link_rb(struct mm_struct *, struct vm_area_struct *, struct rb_node **, struct rb_node *); extern void unlink_file_vma(struct vm_area_struct *); extern struct vm_area_struct *copy_vma(struct vm_area_struct **, unsigned long addr, unsigned long len, pgoff_t pgoff); extern void exit_mmap(struct mm_struct *); extern int mm_take_all_locks(struct mm_struct *mm); extern void mm_drop_all_locks(struct mm_struct *mm); /* From fs/proc/base.c. callers must _not_ hold the mm's exe_file_lock */ extern void added_exe_file_vma(struct mm_struct *mm); extern void removed_exe_file_vma(struct mm_struct *mm); extern void set_mm_exe_file(struct mm_struct *mm, struct file *new_exe_file); extern struct file *get_mm_exe_file(struct mm_struct *mm); extern int may_expand_vm(struct mm_struct *mm, unsigned long npages); extern int install_special_mapping(struct mm_struct *mm, unsigned long addr, unsigned long len, unsigned long flags, struct page **pages); extern unsigned long get_unmapped_area(struct file *, unsigned long, unsigned long, unsigned long, unsigned long); extern unsigned long mmap_region(struct file *file, unsigned long addr, unsigned long len, unsigned long flags, vm_flags_t vm_flags, unsigned long pgoff); extern unsigned long do_mmap(struct file *, unsigned long, unsigned long, unsigned long, unsigned long, unsigned long); extern int do_munmap(struct mm_struct *, unsigned long, size_t); /* These take the mm semaphore themselves */ extern unsigned long vm_brk(unsigned long, unsigned long); extern int vm_munmap(unsigned long, size_t); extern unsigned long vm_mmap(struct file *, unsigned long, unsigned long, unsigned long, unsigned long, unsigned long); /* truncate.c */ extern void truncate_inode_pages(struct address_space *, loff_t); extern void truncate_inode_pages_range(struct address_space *, loff_t lstart, loff_t lend); /* generic vm_area_ops exported for stackable file systems */ extern int filemap_fault(struct vm_area_struct *, struct vm_fault *); /* mm/page-writeback.c */ int write_one_page(struct page *page, int wait); void task_dirty_inc(struct task_struct *tsk); /* readahead.c */ #define VM_MAX_READAHEAD 512 /* kbytes */ #define VM_MIN_READAHEAD 32 /* kbytes (includes current page) */ extern unsigned long max_readahead_pages; int force_page_cache_readahead(struct address_space *mapping, struct file *filp, pgoff_t offset, unsigned long nr_to_read); void page_cache_sync_readahead(struct address_space *mapping, struct file_ra_state *ra, struct file *filp, pgoff_t offset, unsigned long size); void page_cache_async_readahead(struct address_space *mapping, struct file_ra_state *ra, struct file *filp, struct page *pg, pgoff_t offset, unsigned long size); unsigned long max_sane_readahead(unsigned long nr); unsigned long ra_submit(struct file_ra_state *ra, struct address_space *mapping, struct file *filp); /* Generic expand stack which grows the stack according to GROWS{UP,DOWN} */ extern int expand_stack(struct vm_area_struct *vma, unsigned long address); /* CONFIG_STACK_GROWSUP still needs to to grow downwards at some places */ extern int expand_downwards(struct vm_area_struct *vma, unsigned long address); #if VM_GROWSUP extern int expand_upwards(struct vm_area_struct *vma, unsigned long address); #else #define expand_upwards(vma, address) do { } while (0) #endif /* Look up the first VMA which satisfies addr < vm_end, NULL if none. */ extern struct vm_area_struct * find_vma(struct mm_struct * mm, unsigned long addr); extern struct vm_area_struct * find_vma_prev(struct mm_struct * mm, unsigned long addr, struct vm_area_struct **pprev); /* Look up the first VMA which intersects the interval start_addr..end_addr-1, NULL if none. Assume start_addr < end_addr. */ static inline struct vm_area_struct * find_vma_intersection(struct mm_struct * mm, unsigned long start_addr, unsigned long end_addr) { struct vm_area_struct * vma = find_vma(mm,start_addr); if (vma && end_addr <= vma->vm_start) vma = NULL; return vma; } static inline unsigned long vma_pages(struct vm_area_struct *vma) { return (vma->vm_end - vma->vm_start) >> PAGE_SHIFT; } /* Look up the first VMA which exactly match the interval vm_start ... vm_end */ static inline struct vm_area_struct *find_exact_vma(struct mm_struct *mm, unsigned long vm_start, unsigned long vm_end) { struct vm_area_struct *vma = find_vma(mm, vm_start); if (vma && (vma->vm_start != vm_start || vma->vm_end != vm_end)) vma = NULL; return vma; } #ifdef CONFIG_MMU pgprot_t vm_get_page_prot(unsigned long vm_flags); #else static inline pgprot_t vm_get_page_prot(unsigned long vm_flags) { return __pgprot(0); } #endif struct vm_area_struct *find_extend_vma(struct mm_struct *, unsigned long addr); int remap_pfn_range(struct vm_area_struct *, unsigned long addr, unsigned long pfn, unsigned long size, pgprot_t); int vm_insert_page(struct vm_area_struct *, unsigned long addr, struct page *); int vm_insert_pfn(struct vm_area_struct *vma, unsigned long addr, unsigned long pfn); int vm_insert_mixed(struct vm_area_struct *vma, unsigned long addr, unsigned long pfn); struct page *follow_page(struct vm_area_struct *, unsigned long address, unsigned int foll_flags); #define FOLL_WRITE 0x01 /* check pte is writable */ #define FOLL_TOUCH 0x02 /* mark page accessed */ #define FOLL_GET 0x04 /* do get_page on page */ #define FOLL_DUMP 0x08 /* give error on hole if it would be zero */ #define FOLL_FORCE 0x10 /* get_user_pages read/write w/o permission */ #define FOLL_NOWAIT 0x20 /* if a disk transfer is needed, start the IO * and return without waiting upon it */ #define FOLL_MLOCK 0x40 /* mark page as mlocked */ #define FOLL_SPLIT 0x80 /* don't return transhuge pages, split them */ #define FOLL_HWPOISON 0x100 /* check page is hwpoisoned */ typedef int (*pte_fn_t)(pte_t *pte, pgtable_t token, unsigned long addr, void *data); extern int apply_to_page_range(struct mm_struct *mm, unsigned long address, unsigned long size, pte_fn_t fn, void *data); #ifdef CONFIG_PROC_FS void vm_stat_account(struct mm_struct *, unsigned long, struct file *, long); #else static inline void vm_stat_account(struct mm_struct *mm, unsigned long flags, struct file *file, long pages) { } #endif /* CONFIG_PROC_FS */ #ifdef CONFIG_DEBUG_PAGEALLOC extern void kernel_map_pages(struct page *page, int numpages, int enable); #ifdef CONFIG_HIBERNATION extern bool kernel_page_present(struct page *page); #endif /* CONFIG_HIBERNATION */ #else static inline void kernel_map_pages(struct page *page, int numpages, int enable) {} #ifdef CONFIG_HIBERNATION static inline bool kernel_page_present(struct page *page) { return true; } #endif /* CONFIG_HIBERNATION */ #endif extern struct vm_area_struct *get_gate_vma(struct mm_struct *mm); #ifdef __HAVE_ARCH_GATE_AREA int in_gate_area_no_mm(unsigned long addr); int in_gate_area(struct mm_struct *mm, unsigned long addr); #else int in_gate_area_no_mm(unsigned long addr); #define in_gate_area(mm, addr) ({(void)mm; in_gate_area_no_mm(addr);}) #endif /* __HAVE_ARCH_GATE_AREA */ #ifdef CONFIG_USE_USER_ACCESSIBLE_TIMERS static inline int use_user_accessible_timers(void) { return 1; } extern int in_user_timers_area(struct mm_struct *mm, unsigned long addr); extern struct vm_area_struct *get_user_timers_vma(struct mm_struct *mm); extern int get_user_timer_page(struct vm_area_struct *vma, struct mm_struct *mm, unsigned long start, unsigned int gup_flags, struct page **pages, int idx, int *goto_next_page); #else static inline int use_user_accessible_timers(void) { return 0; } static inline int in_user_timers_area(struct mm_struct *mm, unsigned long addr) { return 0; } static inline struct vm_area_struct *get_user_timers_vma(struct mm_struct *mm) { return NULL; } static inline int get_user_timer_page(struct vm_area_struct *vma, struct mm_struct *mm, unsigned long start, unsigned int gup_flags, struct page **pages, int idx, int *goto_next_page) { *goto_next_page = 0; return 0; } #endif int drop_caches_sysctl_handler(struct ctl_table *, int, void __user *, size_t *, loff_t *); unsigned long shrink_slab(struct shrink_control *shrink, unsigned long nr_pages_scanned, unsigned long lru_pages); #ifndef CONFIG_MMU #define randomize_va_space 0 #else extern int randomize_va_space; #endif const char * arch_vma_name(struct vm_area_struct *vma); void print_vma_addr(char *prefix, unsigned long rip); void sparse_mem_maps_populate_node(struct page **map_map, unsigned long pnum_begin, unsigned long pnum_end, unsigned long map_count, int nodeid); struct page *sparse_mem_map_populate(unsigned long pnum, int nid); pgd_t *vmemmap_pgd_populate(unsigned long addr, int node); pud_t *vmemmap_pud_populate(pgd_t *pgd, unsigned long addr, int node); pmd_t *vmemmap_pmd_populate(pud_t *pud, unsigned long addr, int node); pte_t *vmemmap_pte_populate(pmd_t *pmd, unsigned long addr, int node); void *vmemmap_alloc_block(unsigned long size, int node); void *vmemmap_alloc_block_buf(unsigned long size, int node); void vmemmap_verify(pte_t *, int, unsigned long, unsigned long); int vmemmap_populate_basepages(struct page *start_page, unsigned long pages, int node); int vmemmap_populate(struct page *start_page, unsigned long pages, int node); void vmemmap_populate_print_last(void); enum mf_flags { MF_COUNT_INCREASED = 1 << 0, MF_ACTION_REQUIRED = 1 << 1, }; extern int memory_failure(unsigned long pfn, int trapno, int flags); extern void memory_failure_queue(unsigned long pfn, int trapno, int flags); extern int unpoison_memory(unsigned long pfn); extern int sysctl_memory_failure_early_kill; extern int sysctl_memory_failure_recovery; extern void shake_page(struct page *p, int access); extern atomic_long_t mce_bad_pages; extern int soft_offline_page(struct page *page, int flags); extern void dump_page(struct page *page); #if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_HUGETLBFS) extern void clear_huge_page(struct page *page, unsigned long addr, unsigned int pages_per_huge_page); extern void copy_user_huge_page(struct page *dst, struct page *src, unsigned long addr, struct vm_area_struct *vma, unsigned int pages_per_huge_page); #endif /* CONFIG_TRANSPARENT_HUGEPAGE || CONFIG_HUGETLBFS */ #ifdef CONFIG_DEBUG_PAGEALLOC extern unsigned int _debug_guardpage_minorder; static inline unsigned int debug_guardpage_minorder(void) { return _debug_guardpage_minorder; } static inline bool page_is_guard(struct page *page) { return test_bit(PAGE_DEBUG_FLAG_GUARD, &page->debug_flags); } #else static inline unsigned int debug_guardpage_minorder(void) { return 0; } static inline bool page_is_guard(struct page *page) { return false; } #endif /* CONFIG_DEBUG_PAGEALLOC */ #endif /* __KERNEL__ */ #endif /* _LINUX_MM_H */
vinay94185vinay/Flamingo-kernel
include/linux/mm.h
C
gpl-2.0
57,816
/* * Wazuh app - Check Kibana settings service * * Copyright (C) 2015-2021 Wazuh, 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. * * Find more information about this on the LICENSE file. * */ import { CheckLogger } from '../types/check_logger'; import _ from 'lodash'; import { getUiSettings } from '../../../kibana-services'; export const checkKibanaSettings = (kibanaSettingName: string, defaultAppValue: any, callback?: (checkLogger: CheckLogger, options: {defaultAppValue: any}) => void) => (appConfig: any) => async (checkLogger: CheckLogger) => { checkLogger.info('Getting settings...'); const valueKibanaSetting = getUiSettings().get(kibanaSettingName); const settingsAreDifferent = !_.isEqual( typeof defaultAppValue === 'string' ? stringifySetting(valueKibanaSetting) : valueKibanaSetting, defaultAppValue ); checkLogger.info(`Check Kibana setting [${kibanaSettingName}]: ${stringifySetting(valueKibanaSetting)}`); checkLogger.info(`App setting [${kibanaSettingName}]: ${stringifySetting(defaultAppValue)}`); checkLogger.info(`Settings mismatch [${kibanaSettingName}]: ${settingsAreDifferent ? 'yes' : 'no'}`); if ( !valueKibanaSetting || settingsAreDifferent ){ checkLogger.info(`Updating [${kibanaSettingName}] setting...`); await updateSetting(kibanaSettingName, defaultAppValue); checkLogger.action(`Updated [${kibanaSettingName}] setting to: ${stringifySetting(defaultAppValue)}`); callback && callback(checkLogger,{ defaultAppValue }); } } async function updateSetting(kibanaSettingName, defaultAppValue, retries = 3) { return await getUiSettings() .set(kibanaSettingName, null) .catch(async (error) => { if (retries > 0) { return await updateSetting(kibanaSettingName, defaultAppValue, --retries); } throw error; }); } function stringifySetting(setting: any){ try{ return JSON.stringify(setting); }catch(error){ return setting; }; };
wazuh/wazuh-kibana-app
public/components/health-check/services/check-kibana-settings.service.ts
TypeScript
gpl-2.0
2,170
/* Copyright (C) 1998-99 Paul Barton-Davis 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., 675 Mass Ave, Cambridge, MA 02139, USA. $Id$ */ #include <fcntl.h> #include <glib.h> #include "pbd/error.h" #include "midi++/types.h" #include "midi++/manager.h" #include "midi++/channel.h" #include "midi++/port.h" #include "midi++/mmc.h" using namespace std; using namespace MIDI; using namespace PBD; Manager *Manager::theManager = 0; Manager::Manager (jack_client_t* jack) { _mmc = new MachineControl (this, jack); _mtc_input_port = add_port (new MIDI::Port ("MTC in", Port::IsInput, jack)); _mtc_output_port = add_port (new MIDI::Port ("MTC out", Port::IsOutput, jack)); _midi_input_port = add_port (new MIDI::Port ("MIDI control in", Port::IsInput, jack)); _midi_output_port = add_port (new MIDI::Port ("MIDI control out", Port::IsOutput, jack)); _midi_clock_input_port = add_port (new MIDI::Port ("MIDI clock in", Port::IsInput, jack)); _midi_clock_output_port = add_port (new MIDI::Port ("MIDI clock out", Port::IsOutput, jack)); } Manager::~Manager () { delete _mmc; /* This will delete our MTC etc. ports */ for (PortList::iterator p = _ports.begin(); p != _ports.end(); ++p) { delete *p; } if (theManager == this) { theManager = 0; } } Port * Manager::add_port (Port* p) { _ports.push_back (p); PortsChanged (); /* EMIT SIGNAL */ return p; } void Manager::cycle_start (pframes_t nframes) { for (PortList::iterator p = _ports.begin(); p != _ports.end(); ++p) { (*p)->cycle_start (nframes); } } void Manager::cycle_end() { for (PortList::iterator p = _ports.begin(); p != _ports.end(); ++p) { (*p)->cycle_end (); } } /** Re-register ports that disappear on JACK shutdown */ void Manager::reestablish (jack_client_t* jack) { for (PortList::const_iterator p = _ports.begin(); p != _ports.end(); ++p) { (*p)->reestablish (jack); } } /** Re-connect ports after a reestablish () */ void Manager::reconnect () { for (PortList::const_iterator p = _ports.begin(); p != _ports.end(); ++p) { (*p)->reconnect (); } } Port* Manager::port (string const & n) { PortList::const_iterator p = _ports.begin(); while (p != _ports.end() && (*p)->name() != n) { ++p; } if (p == _ports.end()) { return 0; } return *p; } void Manager::create (jack_client_t* jack) { assert (theManager == 0); theManager = new Manager (jack); } void Manager::set_port_states (list<XMLNode*> s) { for (list<XMLNode*>::iterator i = s.begin(); i != s.end(); ++i) { for (PortList::const_iterator j = _ports.begin(); j != _ports.end(); ++j) { (*j)->set_state (**i); } } }
davidhalter-archive/ardour
libs/midi++2/manager.cc
C++
gpl-2.0
3,234
/** * MaNGOS is a full featured server for World of Warcraft, supporting * the following clients: 1.12.x, 2.4.3, 3.3.5a, 4.3.4a and 5.4.8 * * Copyright (C) 2005-2022 MaNGOS <https://getmangos.eu> * * 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 * * World of Warcraft, and all World of Warcraft or Warcraft art, images, * and lore are copyrighted by Blizzard Entertainment, Inc. */ #ifndef MANGOS_H_PLAYER #define MANGOS_H_PLAYER #include "Common.h" #include "ItemPrototype.h" #include "Unit.h" #include "Item.h" #include "Database/DatabaseEnv.h" #include "NPCHandler.h" #include "QuestDef.h" #include "Group.h" #include "Bag.h" #include "WorldSession.h" #include "Pet.h" #include "MapReference.h" #include "Util.h" // for Tokens typedef #include "AchievementMgr.h" #include "ReputationMgr.h" #include "BattleGround.h" #include "SharedDefines.h" #include "Chat.h" #include<string> #include<vector> struct Mail; class Channel; class DynamicObject; class Creature; class PlayerMenu; class Transport; class UpdateMask; class SpellCastTargets; class PlayerSocial; class DungeonPersistentState; class Spell; class Item; struct AreaTrigger; typedef std::deque<Mail*> PlayerMails; #define PLAYER_MAX_SKILLS 127 #define PLAYER_MAX_DAILY_QUESTS 25 #define PLAYER_EXPLORED_ZONES_SIZE 128 // Note: SPELLMOD_* values is aura types in fact enum SpellModType { SPELLMOD_FLAT = 107, // SPELL_AURA_ADD_FLAT_MODIFIER SPELLMOD_PCT = 108 // SPELL_AURA_ADD_PCT_MODIFIER }; // 2^n internal values, they are never sent to the client enum PlayerUnderwaterState { UNDERWATER_NONE = 0x00, UNDERWATER_INWATER = 0x01, // terrain type is water and player is afflicted by it UNDERWATER_INLAVA = 0x02, // terrain type is lava and player is afflicted by it UNDERWATER_INSLIME = 0x04, // terrain type is lava and player is afflicted by it UNDERWATER_INDARKWATER = 0x08, // terrain type is dark water and player is afflicted by it UNDERWATER_EXIST_TIMERS = 0x10 }; enum BuyBankSlotResult { ERR_BANKSLOT_FAILED_TOO_MANY = 0, ERR_BANKSLOT_INSUFFICIENT_FUNDS = 1, ERR_BANKSLOT_NOTBANKER = 2, ERR_BANKSLOT_OK = 3 }; enum PlayerSpellState { PLAYERSPELL_UNCHANGED = 0, PLAYERSPELL_CHANGED = 1, PLAYERSPELL_NEW = 2, PLAYERSPELL_REMOVED = 3 }; struct PlayerSpell { PlayerSpellState state : 8; bool active : 1; // show in spellbook bool dependent : 1; // learned as result another spell learn, skill grow, quest reward, etc bool disabled : 1; // first rank has been learned in result talent learn but currently talent unlearned, save max learned ranks }; struct PlayerTalent { TalentEntry const* talentEntry; uint32 currentRank; PlayerSpellState state; }; typedef UNORDERED_MAP<uint32, PlayerSpell> PlayerSpellMap; typedef UNORDERED_MAP<uint32, PlayerTalent> PlayerTalentMap; struct SpellCooldown { time_t end; uint16 itemid; }; typedef std::map<uint32, SpellCooldown> SpellCooldowns; enum TrainerSpellState { TRAINER_SPELL_GREEN = 0, TRAINER_SPELL_RED = 1, TRAINER_SPELL_GRAY = 2, TRAINER_SPELL_GREEN_DISABLED = 10 // custom value, not send to client: formally green but learn not allowed }; enum ActionButtonUpdateState { ACTIONBUTTON_UNCHANGED = 0, ACTIONBUTTON_CHANGED = 1, ACTIONBUTTON_NEW = 2, ACTIONBUTTON_DELETED = 3 }; enum ActionButtonType { ACTION_BUTTON_SPELL = 0x00, ACTION_BUTTON_C = 0x01, // click? ACTION_BUTTON_EQSET = 0x20, ACTION_BUTTON_MACRO = 0x40, ACTION_BUTTON_CMACRO = ACTION_BUTTON_C | ACTION_BUTTON_MACRO, ACTION_BUTTON_ITEM = 0x80 }; #define ACTION_BUTTON_ACTION(X) (uint32(X) & 0x00FFFFFF) #define ACTION_BUTTON_TYPE(X) ((uint32(X) & 0xFF000000) >> 24) #define MAX_ACTION_BUTTON_ACTION_VALUE (0x00FFFFFF+1) struct ActionButton { ActionButton() : packedData(0), uState(ACTIONBUTTON_NEW) {} uint32 packedData; ActionButtonUpdateState uState; // helpers ActionButtonType GetType() const { return ActionButtonType(ACTION_BUTTON_TYPE(packedData)); } uint32 GetAction() const { return ACTION_BUTTON_ACTION(packedData); } void SetActionAndType(uint32 action, ActionButtonType type) { uint32 newData = action | (uint32(type) << 24); if (newData != packedData || uState == ACTIONBUTTON_DELETED) { packedData = newData; if (uState != ACTIONBUTTON_NEW) { uState = ACTIONBUTTON_CHANGED; } } } }; // some action button indexes used in code or clarify structure enum ActionButtonIndex { ACTION_BUTTON_SHAMAN_TOTEMS_BAR = 132, }; #define MAX_ACTION_BUTTONS 144 // checked in 3.2.0 typedef std::map<uint8, ActionButton> ActionButtonList; enum GlyphUpdateState { GLYPH_UNCHANGED = 0, GLYPH_CHANGED = 1, GLYPH_NEW = 2, GLYPH_DELETED = 3 }; struct Glyph { uint32 id; GlyphUpdateState uState; Glyph() : id(0), uState(GLYPH_UNCHANGED) { } uint32 GetId() { return id; } void SetId(uint32 newId) { if (newId == id) { return; } if (id == 0 && uState == GLYPH_UNCHANGED) // not exist yet in db and already saved { uState = GLYPH_NEW; } else if (newId == 0) { if (uState == GLYPH_NEW) // delete before add new -> no change { uState = GLYPH_UNCHANGED; } else // delete existing data { uState = GLYPH_DELETED; } } else if (uState != GLYPH_NEW) // if not new data, change current data { uState = GLYPH_CHANGED; } id = newId; } }; struct PlayerCreateInfoItem { PlayerCreateInfoItem(uint32 id, uint32 amount) : item_id(id), item_amount(amount) {} uint32 item_id; uint32 item_amount; }; typedef std::list<PlayerCreateInfoItem> PlayerCreateInfoItems; struct PlayerClassLevelInfo { PlayerClassLevelInfo() : basehealth(0), basemana(0) {} uint16 basehealth; uint16 basemana; }; struct PlayerClassInfo { PlayerClassInfo() : levelInfo(NULL) { } PlayerClassLevelInfo* levelInfo; //[level-1] 0..MaxPlayerLevel-1 }; struct PlayerLevelInfo { PlayerLevelInfo() { for (int i = 0; i < MAX_STATS; ++i) { stats[i] = 0; } } uint8 stats[MAX_STATS]; }; typedef std::list<uint32> PlayerCreateInfoSpells; struct PlayerCreateInfoAction { PlayerCreateInfoAction() : button(0), type(0), action(0) {} PlayerCreateInfoAction(uint8 _button, uint32 _action, uint8 _type) : button(_button), type(_type), action(_action) {} uint8 button; uint8 type; uint32 action; }; typedef std::list<PlayerCreateInfoAction> PlayerCreateInfoActions; struct PlayerInfo { // existence checked by displayId != 0 // existence checked by displayId != 0 PlayerInfo() : displayId_m(0), displayId_f(0), levelInfo(NULL) { } uint32 mapId; uint32 areaId; float positionX; float positionY; float positionZ; float orientation; uint16 displayId_m; uint16 displayId_f; PlayerCreateInfoItems item; PlayerCreateInfoSpells spell; PlayerCreateInfoActions action; PlayerLevelInfo* levelInfo; //[level-1] 0..MaxPlayerLevel-1 }; struct PvPInfo { PvPInfo() : inHostileArea(false), endTimer(0) {} bool inHostileArea; time_t endTimer; }; struct DuelInfo { DuelInfo() : initiator(NULL), opponent(NULL), startTimer(0), startTime(0), outOfBound(0) {} Player* initiator; Player* opponent; time_t startTimer; time_t startTime; time_t outOfBound; }; struct Areas { uint32 areaID; uint32 areaFlag; float x1; float x2; float y1; float y2; }; #define MAX_RUNES 6 #define RUNE_COOLDOWN (2*5*IN_MILLISECONDS) // msec enum RuneType { RUNE_BLOOD = 0, RUNE_UNHOLY = 1, RUNE_FROST = 2, RUNE_DEATH = 3, NUM_RUNE_TYPES = 4 }; struct RuneInfo { uint8 BaseRune; uint8 CurrentRune; uint16 Cooldown; // msec }; struct Runes { RuneInfo runes[MAX_RUNES]; uint8 runeState; // mask of available runes void SetRuneState(uint8 index, bool set = true) { if (set) { runeState |= (1 << index); // usable } else { runeState &= ~(1 << index); // on cooldown } } }; struct EnchantDuration { EnchantDuration() : item(NULL), slot(MAX_ENCHANTMENT_SLOT), leftduration(0) {}; EnchantDuration(Item* _item, EnchantmentSlot _slot, uint32 _leftduration) : item(_item), slot(_slot), leftduration(_leftduration) { MANGOS_ASSERT(item); }; Item* item; EnchantmentSlot slot; uint32 leftduration; }; typedef std::list<EnchantDuration> EnchantDurationList; typedef std::list<Item*> ItemDurationList; enum LfgRoles { LEADER = 0x01, TANK = 0x02, HEALER = 0x04, DAMAGE = 0x08 }; enum RaidGroupError { ERR_RAID_GROUP_NONE = 0, ERR_RAID_GROUP_LOWLEVEL = 1, ERR_RAID_GROUP_ONLY = 2, ERR_RAID_GROUP_FULL = 3, ERR_RAID_GROUP_REQUIREMENTS_UNMATCH = 4 }; enum DrunkenState { DRUNKEN_SOBER = 0, DRUNKEN_TIPSY = 1, DRUNKEN_DRUNK = 2, DRUNKEN_SMASHED = 3 }; #define MAX_DRUNKEN 4 enum PlayerFlags { PLAYER_FLAGS_NONE = 0x00000000, PLAYER_FLAGS_GROUP_LEADER = 0x00000001, PLAYER_FLAGS_AFK = 0x00000002, PLAYER_FLAGS_DND = 0x00000004, PLAYER_FLAGS_GM = 0x00000008, PLAYER_FLAGS_GHOST = 0x00000010, PLAYER_FLAGS_RESTING = 0x00000020, PLAYER_FLAGS_UNK7 = 0x00000040, // admin? PLAYER_FLAGS_UNK8 = 0x00000080, // pre-3.0.3 PLAYER_FLAGS_FFA_PVP flag for FFA PVP state PLAYER_FLAGS_CONTESTED_PVP = 0x00000100, // Player has been involved in a PvP combat and will be attacked by contested guards PLAYER_FLAGS_IN_PVP = 0x00000200, PLAYER_FLAGS_HIDE_HELM = 0x00000400, PLAYER_FLAGS_HIDE_CLOAK = 0x00000800, PLAYER_FLAGS_PARTIAL_PLAY_TIME = 0x00001000, // played long time PLAYER_FLAGS_NO_PLAY_TIME = 0x00002000, // played too long time PLAYER_FLAGS_IS_OUT_OF_BOUNDS = 0x00004000, // Lua_IsOutOfBounds PLAYER_FLAGS_DEVELOPER = 0x00008000, // <Dev> chat tag, name prefix PLAYER_FLAGS_ENABLE_LOW_LEVEL_RAID = 0x00010000, // triggers lua event EVENT_ENABLE_LOW_LEVEL_RAID PLAYER_FLAGS_TAXI_BENCHMARK = 0x00020000, // taxi benchmark mode (on/off) (2.0.1) PLAYER_FLAGS_PVP_TIMER = 0x00040000, // 3.0.2, pvp timer active (after you disable pvp manually) PLAYER_FLAGS_COMMENTATOR = 0x00080000, PLAYER_FLAGS_UNK21 = 0x00100000, PLAYER_FLAGS_UNK22 = 0x00200000, PLAYER_FLAGS_COMMENTATOR_UBER = 0x00400000, // something like COMMENTATOR_CAN_USE_INSTANCE_COMMAND PLAYER_FLAGS_UNK24 = 0x00800000, // EVENT_SPELL_UPDATE_USABLE and EVENT_UPDATE_SHAPESHIFT_USABLE, disabled all abilitys on tab except autoattack PLAYER_FLAGS_UNK25 = 0x01000000, // EVENT_SPELL_UPDATE_USABLE and EVENT_UPDATE_SHAPESHIFT_USABLE, disabled all melee ability on tab include autoattack PLAYER_FLAGS_XP_USER_DISABLED = 0x02000000, }; // used for PLAYER__FIELD_KNOWN_TITLES field (uint64), (1<<bit_index) without (-1) // can't use enum for uint64 values #define PLAYER_TITLE_DISABLED UI64LIT(0x0000000000000000) #define PLAYER_TITLE_NONE UI64LIT(0x0000000000000001) #define PLAYER_TITLE_PRIVATE UI64LIT(0x0000000000000002) // 1 #define PLAYER_TITLE_CORPORAL UI64LIT(0x0000000000000004) // 2 #define PLAYER_TITLE_SERGEANT_A UI64LIT(0x0000000000000008) // 3 #define PLAYER_TITLE_MASTER_SERGEANT UI64LIT(0x0000000000000010) // 4 #define PLAYER_TITLE_SERGEANT_MAJOR UI64LIT(0x0000000000000020) // 5 #define PLAYER_TITLE_KNIGHT UI64LIT(0x0000000000000040) // 6 #define PLAYER_TITLE_KNIGHT_LIEUTENANT UI64LIT(0x0000000000000080) // 7 #define PLAYER_TITLE_KNIGHT_CAPTAIN UI64LIT(0x0000000000000100) // 8 #define PLAYER_TITLE_KNIGHT_CHAMPION UI64LIT(0x0000000000000200) // 9 #define PLAYER_TITLE_LIEUTENANT_COMMANDER UI64LIT(0x0000000000000400) // 10 #define PLAYER_TITLE_COMMANDER UI64LIT(0x0000000000000800) // 11 #define PLAYER_TITLE_MARSHAL UI64LIT(0x0000000000001000) // 12 #define PLAYER_TITLE_FIELD_MARSHAL UI64LIT(0x0000000000002000) // 13 #define PLAYER_TITLE_GRAND_MARSHAL UI64LIT(0x0000000000004000) // 14 #define PLAYER_TITLE_SCOUT UI64LIT(0x0000000000008000) // 15 #define PLAYER_TITLE_GRUNT UI64LIT(0x0000000000010000) // 16 #define PLAYER_TITLE_SERGEANT_H UI64LIT(0x0000000000020000) // 17 #define PLAYER_TITLE_SENIOR_SERGEANT UI64LIT(0x0000000000040000) // 18 #define PLAYER_TITLE_FIRST_SERGEANT UI64LIT(0x0000000000080000) // 19 #define PLAYER_TITLE_STONE_GUARD UI64LIT(0x0000000000100000) // 20 #define PLAYER_TITLE_BLOOD_GUARD UI64LIT(0x0000000000200000) // 21 #define PLAYER_TITLE_LEGIONNAIRE UI64LIT(0x0000000000400000) // 22 #define PLAYER_TITLE_CENTURION UI64LIT(0x0000000000800000) // 23 #define PLAYER_TITLE_CHAMPION UI64LIT(0x0000000001000000) // 24 #define PLAYER_TITLE_LIEUTENANT_GENERAL UI64LIT(0x0000000002000000) // 25 #define PLAYER_TITLE_GENERAL UI64LIT(0x0000000004000000) // 26 #define PLAYER_TITLE_WARLORD UI64LIT(0x0000000008000000) // 27 #define PLAYER_TITLE_HIGH_WARLORD UI64LIT(0x0000000010000000) // 28 #define PLAYER_TITLE_GLADIATOR UI64LIT(0x0000000020000000) // 29 #define PLAYER_TITLE_DUELIST UI64LIT(0x0000000040000000) // 30 #define PLAYER_TITLE_RIVAL UI64LIT(0x0000000080000000) // 31 #define PLAYER_TITLE_CHALLENGER UI64LIT(0x0000000100000000) // 32 #define PLAYER_TITLE_SCARAB_LORD UI64LIT(0x0000000200000000) // 33 #define PLAYER_TITLE_CONQUEROR UI64LIT(0x0000000400000000) // 34 #define PLAYER_TITLE_JUSTICAR UI64LIT(0x0000000800000000) // 35 #define PLAYER_TITLE_CHAMPION_OF_THE_NAARU UI64LIT(0x0000001000000000) // 36 #define PLAYER_TITLE_MERCILESS_GLADIATOR UI64LIT(0x0000002000000000) // 37 #define PLAYER_TITLE_OF_THE_SHATTERED_SUN UI64LIT(0x0000004000000000) // 38 #define PLAYER_TITLE_HAND_OF_ADAL UI64LIT(0x0000008000000000) // 39 #define PLAYER_TITLE_VENGEFUL_GLADIATOR UI64LIT(0x0000010000000000) // 40 #define KNOWN_TITLES_SIZE 3 #define MAX_TITLE_INDEX (KNOWN_TITLES_SIZE*64) // 3 uint64 fields // used in (PLAYER_FIELD_BYTES, 0) byte values enum PlayerFieldByteFlags { PLAYER_FIELD_BYTE_TRACK_STEALTHED = 0x02, PLAYER_FIELD_BYTE_RELEASE_TIMER = 0x08, // Display time till auto release spirit PLAYER_FIELD_BYTE_NO_RELEASE_WINDOW = 0x10 // Display no "release spirit" window at all }; // used in byte (PLAYER_FIELD_BYTES2,3) values enum PlayerFieldByte2Flags { PLAYER_FIELD_BYTE2_NONE = 0x00, PLAYER_FIELD_BYTE2_DETECT_AMORE_0 = 0x02, // SPELL_AURA_DETECT_AMORE, not used as value and maybe not relcted to, but used in code as base for mask apply PLAYER_FIELD_BYTE2_DETECT_AMORE_1 = 0x04, // SPELL_AURA_DETECT_AMORE value 1 PLAYER_FIELD_BYTE2_DETECT_AMORE_2 = 0x08, // SPELL_AURA_DETECT_AMORE value 2 PLAYER_FIELD_BYTE2_DETECT_AMORE_3 = 0x10, // SPELL_AURA_DETECT_AMORE value 3 PLAYER_FIELD_BYTE2_STEALTH = 0x20, PLAYER_FIELD_BYTE2_INVISIBILITY_GLOW = 0x40 }; enum MirrorTimerType { FATIGUE_TIMER = 0, BREATH_TIMER = 1, FIRE_TIMER = 2 }; #define MAX_TIMERS 3 #define DISABLED_MIRROR_TIMER -1 // 2^n values enum PlayerExtraFlags { // gm abilities PLAYER_EXTRA_GM_ON = 0x0001, PLAYER_EXTRA_GM_ACCEPT_TICKETS = 0x0002, PLAYER_EXTRA_ACCEPT_WHISPERS = 0x0004, PLAYER_EXTRA_TAXICHEAT = 0x0008, PLAYER_EXTRA_GM_INVISIBLE = 0x0010, PLAYER_EXTRA_GM_CHAT = 0x0020, // Show GM badge in chat messages PLAYER_EXTRA_AUCTION_NEUTRAL = 0x0040, PLAYER_EXTRA_AUCTION_ENEMY = 0x0080, // overwrite PLAYER_EXTRA_AUCTION_NEUTRAL // other states PLAYER_EXTRA_PVP_DEATH = 0x0100 // store PvP death status until corpse creating. }; // 2^n values enum AtLoginFlags { AT_LOGIN_NONE = 0x00, AT_LOGIN_RENAME = 0x01, AT_LOGIN_RESET_SPELLS = 0x02, AT_LOGIN_RESET_TALENTS = 0x04, AT_LOGIN_CUSTOMIZE = 0x08, AT_LOGIN_RESET_PET_TALENTS = 0x10, AT_LOGIN_FIRST = 0x20, }; typedef std::map<uint32, QuestStatusData> QuestStatusMap; enum QuestSlotOffsets { QUEST_ID_OFFSET = 0, QUEST_STATE_OFFSET = 1, QUEST_COUNTS_OFFSET = 2, // 2 and 3 QUEST_TIME_OFFSET = 4 }; #define MAX_QUEST_OFFSET 5 enum QuestSlotStateMask { QUEST_STATE_NONE = 0x0000, QUEST_STATE_COMPLETE = 0x0001, QUEST_STATE_FAIL = 0x0002 }; enum SkillUpdateState { SKILL_UNCHANGED = 0, SKILL_CHANGED = 1, SKILL_NEW = 2, SKILL_DELETED = 3 }; struct SkillStatusData { SkillStatusData(uint8 _pos, SkillUpdateState _uState) : pos(_pos), uState(_uState) { } uint8 pos; SkillUpdateState uState; }; typedef UNORDERED_MAP<uint32, SkillStatusData> SkillStatusMap; enum PlayerSlots { // first slot for item stored (in any way in player m_items data) PLAYER_SLOT_START = 0, // last+1 slot for item stored (in any way in player m_items data) PLAYER_SLOT_END = 150, PLAYER_SLOTS_COUNT = (PLAYER_SLOT_END - PLAYER_SLOT_START) }; #define INVENTORY_SLOT_BAG_0 255 enum EquipmentSlots // 19 slots { EQUIPMENT_SLOT_START = 0, EQUIPMENT_SLOT_HEAD = 0, EQUIPMENT_SLOT_NECK = 1, EQUIPMENT_SLOT_SHOULDERS = 2, EQUIPMENT_SLOT_BODY = 3, EQUIPMENT_SLOT_CHEST = 4, EQUIPMENT_SLOT_WAIST = 5, EQUIPMENT_SLOT_LEGS = 6, EQUIPMENT_SLOT_FEET = 7, EQUIPMENT_SLOT_WRISTS = 8, EQUIPMENT_SLOT_HANDS = 9, EQUIPMENT_SLOT_FINGER1 = 10, EQUIPMENT_SLOT_FINGER2 = 11, EQUIPMENT_SLOT_TRINKET1 = 12, EQUIPMENT_SLOT_TRINKET2 = 13, EQUIPMENT_SLOT_BACK = 14, EQUIPMENT_SLOT_MAINHAND = 15, EQUIPMENT_SLOT_OFFHAND = 16, EQUIPMENT_SLOT_RANGED = 17, EQUIPMENT_SLOT_TABARD = 18, EQUIPMENT_SLOT_END = 19 }; enum InventorySlots // 4 slots { INVENTORY_SLOT_BAG_START = 19, INVENTORY_SLOT_BAG_END = 23 }; enum InventoryPackSlots // 16 slots { INVENTORY_SLOT_ITEM_START = 23, INVENTORY_SLOT_ITEM_END = 39 }; enum BankItemSlots // 28 slots { BANK_SLOT_ITEM_START = 39, BANK_SLOT_ITEM_END = 67 }; enum BankBagSlots // 7 slots { BANK_SLOT_BAG_START = 67, BANK_SLOT_BAG_END = 74 }; enum BuyBackSlots // 12 slots { // stored in m_buybackitems BUYBACK_SLOT_START = 74, BUYBACK_SLOT_END = 86 }; enum KeyRingSlots // 32 slots { KEYRING_SLOT_START = 86, KEYRING_SLOT_END = 118 }; enum CurrencyTokenSlots // 32 slots { CURRENCYTOKEN_SLOT_START = 118, CURRENCYTOKEN_SLOT_END = 150 }; enum EquipmentSetUpdateState { EQUIPMENT_SET_UNCHANGED = 0, EQUIPMENT_SET_CHANGED = 1, EQUIPMENT_SET_NEW = 2, EQUIPMENT_SET_DELETED = 3 }; struct EquipmentSet { EquipmentSet() : Guid(0), IgnoreMask(0), state(EQUIPMENT_SET_NEW) { for (int i = 0; i < EQUIPMENT_SLOT_END; ++i) { Items[i] = 0; } } uint64 Guid; std::string Name; std::string IconName; uint32 IgnoreMask; uint32 Items[EQUIPMENT_SLOT_END]; EquipmentSetUpdateState state; }; #define MAX_EQUIPMENT_SET_INDEX 10 // client limit typedef std::map<uint32, EquipmentSet> EquipmentSets; struct ItemPosCount { ItemPosCount(uint16 _pos, uint32 _count) : pos(_pos), count(_count) {} bool isContainedIn(std::vector<ItemPosCount> const& vec) const; uint16 pos; uint32 count; }; typedef std::vector<ItemPosCount> ItemPosCountVec; enum TradeSlots { TRADE_SLOT_COUNT = 7, TRADE_SLOT_TRADED_COUNT = 6, TRADE_SLOT_NONTRADED = 6 }; enum TransferAbortReason { TRANSFER_ABORT_NONE = 0x00, TRANSFER_ABORT_ERROR = 0x01, TRANSFER_ABORT_MAX_PLAYERS = 0x02, // Transfer Aborted: instance is full TRANSFER_ABORT_NOT_FOUND = 0x03, // Transfer Aborted: instance not found TRANSFER_ABORT_TOO_MANY_INSTANCES = 0x04, // You have entered too many instances recently. TRANSFER_ABORT_ZONE_IN_COMBAT = 0x06, // Unable to zone in while an encounter is in progress. TRANSFER_ABORT_INSUF_EXPAN_LVL = 0x07, // You must have <TBC,WotLK> expansion installed to access this area. TRANSFER_ABORT_DIFFICULTY = 0x08, // <Normal,Heroic,Epic> difficulty mode is not available for %s. TRANSFER_ABORT_UNIQUE_MESSAGE = 0x09, // Until you've escaped TLK's grasp, you cannot leave this place! TRANSFER_ABORT_TOO_MANY_REALM_INSTANCES = 0x0A, // Additional instances cannot be launched, please try again later. TRANSFER_ABORT_NEED_GROUP = 0x0B, // 3.1 TRANSFER_ABORT_NOT_FOUND2 = 0x0C, // 3.1 TRANSFER_ABORT_NOT_FOUND3 = 0x0D, // 3.1 TRANSFER_ABORT_NOT_FOUND4 = 0x0E, // 3.2 TRANSFER_ABORT_REALM_ONLY = 0x0F, // All players on party must be from the same realm. TRANSFER_ABORT_MAP_NOT_ALLOWED = 0x10, // Map can't be entered at this time. }; enum InstanceResetWarningType { RAID_INSTANCE_WARNING_HOURS = 1, // WARNING! %s is scheduled to reset in %d hour(s). RAID_INSTANCE_WARNING_MIN = 2, // WARNING! %s is scheduled to reset in %d minute(s)! RAID_INSTANCE_WARNING_MIN_SOON = 3, // WARNING! %s is scheduled to reset in %d minute(s). Please exit the zone or you will be returned to your bind location! RAID_INSTANCE_WELCOME = 4, // Welcome to %s. This raid instance is scheduled to reset in %s. RAID_INSTANCE_EXPIRED = 5 }; // PLAYER_FIELD_ARENA_TEAM_INFO_1_1 offsets enum ArenaTeamInfoType { ARENA_TEAM_ID = 0, ARENA_TEAM_TYPE = 1, // new in 3.2 - team type? ARENA_TEAM_MEMBER = 2, // 0 - captain, 1 - member ARENA_TEAM_GAMES_WEEK = 3, ARENA_TEAM_GAMES_SEASON = 4, ARENA_TEAM_WINS_SEASON = 5, ARENA_TEAM_PERSONAL_RATING = 6, ARENA_TEAM_END = 7 }; enum RestType { REST_TYPE_NO = 0, REST_TYPE_IN_TAVERN = 1, REST_TYPE_IN_CITY = 2 }; enum DuelCompleteType { DUEL_INTERRUPTED = 0, DUEL_WON = 1, DUEL_FLED = 2 }; enum TeleportToOptions { TELE_TO_GM_MODE = 0x01, TELE_TO_NOT_LEAVE_TRANSPORT = 0x02, TELE_TO_NOT_LEAVE_COMBAT = 0x04, TELE_TO_NOT_UNSUMMON_PET = 0x08, TELE_TO_SPELL = 0x10, }; /// Type of environmental damages enum EnviromentalDamage { DAMAGE_EXHAUSTED = 0, DAMAGE_DROWNING = 1, DAMAGE_FALL = 2, DAMAGE_LAVA = 3, DAMAGE_SLIME = 4, DAMAGE_FIRE = 5, DAMAGE_FALL_TO_VOID = 6 // custom case for fall without durability loss }; enum PlayedTimeIndex { PLAYED_TIME_TOTAL = 0, PLAYED_TIME_LEVEL = 1 }; #define MAX_PLAYED_TIME_INDEX 2 // used at player loading query list preparing, and later result selection enum PlayerLoginQueryIndex { PLAYER_LOGIN_QUERY_LOADFROM, PLAYER_LOGIN_QUERY_LOADGROUP, PLAYER_LOGIN_QUERY_LOADBOUNDINSTANCES, PLAYER_LOGIN_QUERY_LOADAURAS, PLAYER_LOGIN_QUERY_LOADSPELLS, PLAYER_LOGIN_QUERY_LOADQUESTSTATUS, PLAYER_LOGIN_QUERY_LOADDAILYQUESTSTATUS, PLAYER_LOGIN_QUERY_LOADREPUTATION, PLAYER_LOGIN_QUERY_LOADINVENTORY, PLAYER_LOGIN_QUERY_LOADITEMLOOT, PLAYER_LOGIN_QUERY_LOADACTIONS, PLAYER_LOGIN_QUERY_LOADSOCIALLIST, PLAYER_LOGIN_QUERY_LOADHOMEBIND, PLAYER_LOGIN_QUERY_LOADSPELLCOOLDOWNS, PLAYER_LOGIN_QUERY_LOADDECLINEDNAMES, PLAYER_LOGIN_QUERY_LOADGUILD, PLAYER_LOGIN_QUERY_LOADARENAINFO, PLAYER_LOGIN_QUERY_LOADACHIEVEMENTS, PLAYER_LOGIN_QUERY_LOADCRITERIAPROGRESS, PLAYER_LOGIN_QUERY_LOADEQUIPMENTSETS, PLAYER_LOGIN_QUERY_LOADBGDATA, PLAYER_LOGIN_QUERY_LOADACCOUNTDATA, PLAYER_LOGIN_QUERY_LOADSKILLS, PLAYER_LOGIN_QUERY_LOADGLYPHS, PLAYER_LOGIN_QUERY_LOADMAILS, PLAYER_LOGIN_QUERY_LOADMAILEDITEMS, PLAYER_LOGIN_QUERY_LOADTALENTS, PLAYER_LOGIN_QUERY_LOADRANDOMBG, PLAYER_LOGIN_QUERY_LOADWEEKLYQUESTSTATUS, PLAYER_LOGIN_QUERY_LOADMONTHLYQUESTSTATUS, MAX_PLAYER_LOGIN_QUERY }; enum PlayerDelayedOperations { DELAYED_SAVE_PLAYER = 0x01, DELAYED_RESURRECT_PLAYER = 0x02, DELAYED_SPELL_CAST_DESERTER = 0x04, DELAYED_BG_MOUNT_RESTORE = 0x08, ///< Flag to restore mount state after teleport from BG DELAYED_BG_TAXI_RESTORE = 0x10, ///< Flag to restore taxi state after teleport from BG DELAYED_END }; enum ReputationSource { REPUTATION_SOURCE_KILL, REPUTATION_SOURCE_QUEST, REPUTATION_SOURCE_SPELL }; // Player summoning auto-decline time (in secs) #define MAX_PLAYER_SUMMON_DELAY (2*MINUTE) #define MAX_MONEY_AMOUNT (0x7FFFFFFF-1) struct InstancePlayerBind { DungeonPersistentState* state; bool perm; /* permanent PlayerInstanceBinds are created in Raid/Heroic instances for players that aren't already permanently bound when they are inside when a boss is killed or when they enter an instance that the group leader is permanently bound to. */ InstancePlayerBind() : state(NULL), perm(false) {} }; enum PlayerRestState { REST_STATE_RESTED = 0x01, REST_STATE_NORMAL = 0x02, REST_STATE_RAF_LINKED = 0x04 // Exact use unknown }; class PlayerTaxi { public: PlayerTaxi(); ~PlayerTaxi() {} // Nodes void InitTaxiNodesForLevel(uint32 race, uint32 chrClass, uint32 level); void LoadTaxiMask(const char* data); bool IsTaximaskNodeKnown(uint32 nodeidx) const { uint8 field = uint8((nodeidx - 1) / 32); uint32 submask = 1 << ((nodeidx - 1) % 32); return (m_taximask[field] & submask) == submask; } bool SetTaximaskNode(uint32 nodeidx) { uint8 field = uint8((nodeidx - 1) / 32); uint32 submask = 1 << ((nodeidx - 1) % 32); if ((m_taximask[field] & submask) != submask) { m_taximask[field] |= submask; return true; } else { return false; } } void AppendTaximaskTo(ByteBuffer& data, bool all); // Destinations bool LoadTaxiDestinationsFromString(const std::string& values, Team team); std::string SaveTaxiDestinationsToString(); void ClearTaxiDestinations() { m_TaxiDestinations.clear(); } void AddTaxiDestination(uint32 dest) { m_TaxiDestinations.push_back(dest); } uint32 GetTaxiSource() const { return m_TaxiDestinations.empty() ? 0 : m_TaxiDestinations.front(); } uint32 GetTaxiDestination() const { return m_TaxiDestinations.size() < 2 ? 0 : m_TaxiDestinations[1]; } uint32 GetCurrentTaxiPath() const; uint32 NextTaxiDestination() { m_TaxiDestinations.pop_front(); return GetTaxiDestination(); } bool empty() const { return m_TaxiDestinations.empty(); } friend std::ostringstream& operator<< (std::ostringstream& ss, PlayerTaxi const& taxi); private: TaxiMask m_taximask; std::deque<uint32> m_TaxiDestinations; }; std::ostringstream& operator<< (std::ostringstream& ss, PlayerTaxi const& taxi); /// Holder for BattleGround data struct BGData { BGData() : bgInstanceID(0), bgTypeID(BATTLEGROUND_TYPE_NONE), bgAfkReportedCount(0), bgAfkReportedTimer(0), bgTeam(TEAM_NONE), mountSpell(0), m_needSave(false) { ClearTaxiPath(); } uint32 bgInstanceID; ///< This variable is set to bg->m_InstanceID, saved /// when player is teleported to BG - (it is battleground's GUID) BattleGroundTypeId bgTypeID; std::set<uint32> bgAfkReporter; uint8 bgAfkReportedCount; time_t bgAfkReportedTimer; Team bgTeam; ///< What side the player will be added to, saved uint32 mountSpell; ///< Mount used before join to bg, saved uint32 taxiPath[2]; ///< Current taxi active path start/end nodes, saved WorldLocation joinPos; ///< From where player entered BG, saved bool m_needSave; ///< true, if saved to DB fields modified after prev. save (marked as "saved" above) void ClearTaxiPath() { taxiPath[0] = taxiPath[1] = 0; } bool HasTaxiPath() const { return taxiPath[0] && taxiPath[1]; } }; class TradeData { public: // constructors TradeData(Player* player, Player* trader) : m_player(player), m_trader(trader), m_accepted(false), m_acceptProccess(false), m_money(0), m_spell(0) {} public: // access functions Player* GetTrader() const { return m_trader; } TradeData* GetTraderData() const; Item* GetItem(TradeSlots slot) const; bool HasItem(ObjectGuid item_guid) const; uint32 GetSpell() const { return m_spell; } Item* GetSpellCastItem() const; bool HasSpellCastItem() const { return !m_spellCastItem.IsEmpty(); } uint32 GetMoney() const { return m_money; } bool IsAccepted() const { return m_accepted; } bool IsInAcceptProcess() const { return m_acceptProccess; } public: // access functions void SetItem(TradeSlots slot, Item* item); void SetSpell(uint32 spell_id, Item* castItem = NULL); void SetMoney(uint32 money); void SetAccepted(bool state, bool crosssend = false); // must be called only from accept handler helper functions void SetInAcceptProcess(bool state) { m_acceptProccess = state; } private: // internal functions void Update(bool for_trader = true); private: // fields Player* m_player; // Player who own of this TradeData Player* m_trader; // Player who trade with m_player bool m_accepted; // m_player press accept for trade list bool m_acceptProccess; // one from player/trader press accept and this processed uint32 m_money; // m_player place money to trade uint32 m_spell; // m_player apply spell to non-traded slot item ObjectGuid m_spellCastItem; // applied spell casted by item use ObjectGuid m_items[TRADE_SLOT_COUNT]; // traded itmes from m_player side including non-traded slot }; class Player : public Unit { friend class WorldSession; friend void Item::AddToUpdateQueueOf(Player* player); friend void Item::RemoveFromUpdateQueueOf(Player* player); public: explicit Player(WorldSession* session); ~Player(); void CleanupsBeforeDelete() override; static UpdateMask updateVisualBits; static void InitVisibleBits(); void AddToWorld() override; void RemoveFromWorld() override; bool TeleportTo(uint32 mapid, float x, float y, float z, float orientation, uint32 options = 0, AreaTrigger const* at = NULL); bool TeleportTo(WorldLocation const& loc, uint32 options = 0) { return TeleportTo(loc.mapid, loc.coord_x, loc.coord_y, loc.coord_z, loc.orientation, options); } bool TeleportToBGEntryPoint(); void SetSummonPoint(uint32 mapid, float x, float y, float z) { m_summon_expire = time(NULL) + MAX_PLAYER_SUMMON_DELAY; m_summon_mapid = mapid; m_summon_x = x; m_summon_y = y; m_summon_z = z; } void SummonIfPossible(bool agree); bool Create(uint32 guidlow, const std::string& name, uint8 race, uint8 class_, uint8 gender, uint8 skin, uint8 face, uint8 hairStyle, uint8 hairColor, uint8 facialHair, uint8 outfitId); void Update(uint32 update_diff, uint32 time) override; static bool BuildEnumData(QueryResult* result, WorldPacket* p_data); void SetInWater(bool apply); bool IsInWater() const override { return m_isInWater; } bool IsUnderWater() const override; bool IsFalling() { return GetPositionZ() < m_lastFallZ; } void SendInitialPacketsBeforeAddToMap(); void SendInitialPacketsAfterAddToMap(); void SendInstanceResetWarning(uint32 mapid, Difficulty difficulty, uint32 time); Creature* GetNPCIfCanInteractWith(ObjectGuid guid, uint32 npcflagmask); GameObject* GetGameObjectIfCanInteractWith(ObjectGuid guid, uint32 gameobject_type = MAX_GAMEOBJECT_TYPE) const; void ToggleAFK(); void ToggleDND(); bool isAFK() const { return HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK); } bool isDND() const { return HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND); } ChatTagFlags GetChatTag() const; std::string autoReplyMsg; uint32 GetBarberShopCost(uint8 newhairstyle, uint8 newhaircolor, uint8 newfacialhair, uint32 newskintone); PlayerSocial* GetSocial() { return m_social; } void SetCreatedDate(uint32 createdDate) { m_created_date = createdDate; } uint32 GetCreatedDate() { return m_created_date; } PlayerTaxi m_taxi; void InitTaxiNodesForLevel() { m_taxi.InitTaxiNodesForLevel(getRace(), getClass(), getLevel()); } bool ActivateTaxiPathTo(std::vector<uint32> const& nodes, Creature* npc = NULL, uint32 spellid = 0); bool ActivateTaxiPathTo(uint32 taxi_path_id, uint32 spellid = 0); // mount_id can be used in scripting calls void ContinueTaxiFlight(); bool isAcceptTickets() const { return GetSession()->GetSecurity() >= SEC_GAMEMASTER && (m_ExtraFlags & PLAYER_EXTRA_GM_ACCEPT_TICKETS); } void SetAcceptTicket(bool on) { if (on) { m_ExtraFlags |= PLAYER_EXTRA_GM_ACCEPT_TICKETS; } else { m_ExtraFlags &= ~PLAYER_EXTRA_GM_ACCEPT_TICKETS; } } bool isAcceptWhispers() const { return m_ExtraFlags & PLAYER_EXTRA_ACCEPT_WHISPERS; } void SetAcceptWhispers(bool on) { if (on) { m_ExtraFlags |= PLAYER_EXTRA_ACCEPT_WHISPERS; } else { m_ExtraFlags &= ~PLAYER_EXTRA_ACCEPT_WHISPERS; } } bool isGameMaster() const { return m_ExtraFlags & PLAYER_EXTRA_GM_ON; } void SetGameMaster(bool on); bool isGMChat() const { return GetSession()->GetSecurity() >= SEC_MODERATOR && (m_ExtraFlags & PLAYER_EXTRA_GM_CHAT); } void SetGMChat(bool on) { if (on) { m_ExtraFlags |= PLAYER_EXTRA_GM_CHAT; } else { m_ExtraFlags &= ~PLAYER_EXTRA_GM_CHAT; } } bool IsTaxiCheater() const { return m_ExtraFlags & PLAYER_EXTRA_TAXICHEAT; } void SetTaxiCheater(bool on) { if (on) { m_ExtraFlags |= PLAYER_EXTRA_TAXICHEAT; } else { m_ExtraFlags &= ~PLAYER_EXTRA_TAXICHEAT; } } bool isGMVisible() const { return !(m_ExtraFlags & PLAYER_EXTRA_GM_INVISIBLE); } void SetGMVisible(bool on); void SetPvPDeath(bool on) { if (on) { m_ExtraFlags |= PLAYER_EXTRA_PVP_DEATH; } else { m_ExtraFlags &= ~PLAYER_EXTRA_PVP_DEATH; } } // 0 = own auction, -1 = enemy auction, 1 = goblin auction int GetAuctionAccessMode() const { return m_ExtraFlags & PLAYER_EXTRA_AUCTION_ENEMY ? -1 : (m_ExtraFlags & PLAYER_EXTRA_AUCTION_NEUTRAL ? 1 : 0); } void SetAuctionAccessMode(int state) { m_ExtraFlags &= ~(PLAYER_EXTRA_AUCTION_ENEMY | PLAYER_EXTRA_AUCTION_NEUTRAL); if (state < 0) { m_ExtraFlags |= PLAYER_EXTRA_AUCTION_ENEMY; } else if (state > 0) { m_ExtraFlags |= PLAYER_EXTRA_AUCTION_NEUTRAL; } } void GiveXP(uint32 xp, Unit* victim); void GiveLevel(uint32 level); /* DO NOT REMOVE: Used for Eluna compatibility */ void SetLevel(uint32 level); void InitStatsForLevel(bool reapplyMods = false); // Played Time Stuff time_t m_logintime; time_t m_Last_tick; uint32 m_Played_time[MAX_PLAYED_TIME_INDEX]; uint32 GetTotalPlayedTime() { return m_Played_time[PLAYED_TIME_TOTAL]; } uint32 GetLevelPlayedTime() { return m_Played_time[PLAYED_TIME_LEVEL]; } void ResetTimeSync(); void SendTimeSync(); void SetDeathState(DeathState s) override; // overwrite Unit::SetDeathState float GetRestBonus() const { return m_rest_bonus; } void SetRestBonus(float rest_bonus_new); /** * \brief: compute rest bonus * \param: time_t timePassed > time from last check * \param: bool offline > is the player was offline? * \param: bool inRestPlace > if it was offline, is the player was in city/tavern/inn? * \returns: float **/ float ComputeRest(time_t timePassed, bool offline = false, bool inRestPlace = false); RestType GetRestType() const { return rest_type; } void SetRestType(RestType n_r_type, uint32 areaTriggerId = 0); time_t GetTimeInnEnter() const { return time_inn_enter; } void UpdateInnerTime(time_t time) { time_inn_enter = time; } void RemovePet(PetSaveMode mode); uint32 GetPhaseMaskForSpawn() const; // used for proper set phase for DB at GM-mode creature/GO spawn void Say(const std::string& text, const uint32 language); void Yell(const std::string& text, const uint32 language); void TextEmote(const std::string& text); void Whisper(const std::string& text, const uint32 language, ObjectGuid receiver); /*********************************************************/ /*** STORAGE SYSTEM ***/ /*********************************************************/ void SetVirtualItemSlot(uint8 i, Item* item); void SetSheath(SheathState sheathed) override; // overwrite Unit version uint8 FindEquipSlot(ItemPrototype const* proto, uint32 slot, bool swap) const; uint32 GetItemCount(uint32 item, bool inBankAlso = false, Item* skipItem = NULL) const; uint32 GetItemCountWithLimitCategory(uint32 limitCategory, Item* skipItem = NULL) const; Item* GetItemByGuid(ObjectGuid guid) const; Item* GetItemByEntry(uint32 item) const; // only for special cases Item* GetItemByLimitedCategory(uint32 limitedCategory) const; Item* GetItemByPos(uint16 pos) const; Item* GetItemByPos(uint8 bag, uint8 slot) const; uint32 GetItemDisplayIdInSlot(uint8 bag, uint8 slot) const; Item* GetWeaponForAttack(WeaponAttackType attackType) const { return GetWeaponForAttack(attackType, false, false); } Item* GetWeaponForAttack(WeaponAttackType attackType, bool nonbroken, bool useable) const; Item* GetShield(bool useable = false) const; static uint32 GetAttackBySlot(uint8 slot); // MAX_ATTACK if not weapon slot std::vector<Item*>& GetItemUpdateQueue() { return m_itemUpdateQueue; } static bool IsInventoryPos(uint16 pos) { return IsInventoryPos(pos >> 8, pos & 255); } static bool IsInventoryPos(uint8 bag, uint8 slot); static bool IsEquipmentPos(uint16 pos) { return IsEquipmentPos(pos >> 8, pos & 255); } static bool IsEquipmentPos(uint8 bag, uint8 slot); static bool IsBagPos(uint16 pos); static bool IsBankPos(uint16 pos) { return IsBankPos(pos >> 8, pos & 255); } static bool IsBankPos(uint8 bag, uint8 slot); bool IsValidPos(uint16 pos, bool explicit_pos) const { return IsValidPos(pos >> 8, pos & 255, explicit_pos); } bool IsValidPos(uint8 bag, uint8 slot, bool explicit_pos) const; uint8 GetBankBagSlotCount() const { return GetByteValue(PLAYER_BYTES_2, 2); } void SetBankBagSlotCount(uint8 count) { SetByteValue(PLAYER_BYTES_2, 2, count); } bool HasItemCount(uint32 item, uint32 count, bool inBankAlso = false) const; bool HasItemFitToSpellReqirements(SpellEntry const* spellInfo, Item const* ignoreItem = NULL); bool CanNoReagentCast(SpellEntry const* spellInfo) const; bool HasItemOrGemWithIdEquipped(uint32 item, uint32 count, uint8 except_slot = NULL_SLOT) const; bool HasItemOrGemWithLimitCategoryEquipped(uint32 limitCategory, uint32 count, uint8 except_slot = NULL_SLOT) const; InventoryResult CanTakeMoreSimilarItems(Item* pItem) const { return _CanTakeMoreSimilarItems(pItem->GetEntry(), pItem->GetCount(), pItem); } InventoryResult CanTakeMoreSimilarItems(uint32 entry, uint32 count) const { return _CanTakeMoreSimilarItems(entry, count, NULL); } InventoryResult CanStoreNewItem(uint8 bag, uint8 slot, ItemPosCountVec& dest, uint32 item, uint32 count, uint32* no_space_count = NULL) const { return _CanStoreItem(bag, slot, dest, item, count, NULL, false, no_space_count); } InventoryResult CanStoreItem(uint8 bag, uint8 slot, ItemPosCountVec& dest, Item* pItem, bool swap = false) const { if (!pItem) { return EQUIP_ERR_ITEM_NOT_FOUND; } uint32 count = pItem->GetCount(); return _CanStoreItem(bag, slot, dest, pItem->GetEntry(), count, pItem, swap, NULL); } InventoryResult CanStoreItems(Item** pItem, int count) const; InventoryResult CanEquipNewItem(uint8 slot, uint16& dest, uint32 item, bool swap) const; InventoryResult CanEquipItem(uint8 slot, uint16& dest, Item* pItem, bool swap, bool direct_action = true) const; InventoryResult CanEquipUniqueItem(Item* pItem, uint8 except_slot = NULL_SLOT, uint32 limit_count = 1) const; InventoryResult CanEquipUniqueItem(ItemPrototype const* itemProto, uint8 except_slot = NULL_SLOT, uint32 limit_count = 1) const; InventoryResult CanUnequipItems(uint32 item, uint32 count) const; InventoryResult CanUnequipItem(uint16 src, bool swap) const; InventoryResult CanBankItem(uint8 bag, uint8 slot, ItemPosCountVec& dest, Item* pItem, bool swap, bool not_loading = true) const; InventoryResult CanUseItem(Item* pItem, bool direct_action = true) const; bool HasItemTotemCategory(uint32 TotemCategory) const; InventoryResult CanUseItem(ItemPrototype const* pItem) const; InventoryResult CanUseAmmo(uint32 item) const; Item* StoreNewItem(ItemPosCountVec const& pos, uint32 item, bool update, int32 randomPropertyId = 0); Item* StoreItem(ItemPosCountVec const& pos, Item* pItem, bool update); Item* EquipNewItem(uint16 pos, uint32 item, bool update); Item* EquipItem(uint16 pos, Item* pItem, bool update); void AutoUnequipOffhandIfNeed(); bool StoreNewItemInBestSlots(uint32 item_id, uint32 item_count); Item* StoreNewItemInInventorySlot(uint32 itemEntry, uint32 amount); void AutoStoreLoot(WorldObject const* lootTarget, uint32 loot_id, LootStore const& store, bool broadcast = false, uint8 bag = NULL_BAG, uint8 slot = NULL_SLOT); void AutoStoreLoot(Loot& loot, bool broadcast = false, uint8 bag = NULL_BAG, uint8 slot = NULL_SLOT); Item* ConvertItem(Item* item, uint32 newItemId); InventoryResult _CanTakeMoreSimilarItems(uint32 entry, uint32 count, Item* pItem, uint32* no_space_count = NULL) const; InventoryResult _CanStoreItem(uint8 bag, uint8 slot, ItemPosCountVec& dest, uint32 entry, uint32 count, Item* pItem = NULL, bool swap = false, uint32* no_space_count = NULL) const; void ApplyEquipCooldown(Item* pItem); void SetAmmo(uint32 item); void RemoveAmmo(); float GetAmmoDPS() const { return m_ammoDPS; } bool CheckAmmoCompatibility(const ItemPrototype* ammo_proto) const; void QuickEquipItem(uint16 pos, Item* pItem); void VisualizeItem(uint8 slot, Item* pItem); void SetVisibleItemSlot(uint8 slot, Item* pItem); Item* BankItem(ItemPosCountVec const& dest, Item* pItem, bool update) { return StoreItem(dest, pItem, update); } Item* BankItem(uint16 pos, Item* pItem, bool update); void RemoveItem(uint8 bag, uint8 slot, bool update);// see ApplyItemOnStoreSpell notes void MoveItemFromInventory(uint8 bag, uint8 slot, bool update); // in trade, auction, guild bank, mail.... void MoveItemToInventory(ItemPosCountVec const& dest, Item* pItem, bool update, bool in_characterInventoryDB = false); // in trade, guild bank, mail.... void RemoveItemDependentAurasAndCasts(Item* pItem); void DestroyItem(uint8 bag, uint8 slot, bool update); void DestroyItemCount(uint32 item, uint32 count, bool update, bool unequip_check = false, bool inBankAlso = false); void DestroyItemCount(Item* item, uint32& count, bool update); void DestroyConjuredItems(bool update); void DestroyZoneLimitedItem(bool update, uint32 new_zone); void SplitItem(uint16 src, uint16 dst, uint32 count); void SwapItem(uint16 src, uint16 dst); void AddItemToBuyBackSlot(Item* pItem); Item* GetItemFromBuyBackSlot(uint32 slot); void RemoveItemFromBuyBackSlot(uint32 slot, bool del); void TakeExtendedCost(uint32 extendedCostId, uint32 count); uint32 GetMaxKeyringSize() const { return KEYRING_SLOT_END - KEYRING_SLOT_START; } void SendEquipError(InventoryResult msg, Item* pItem, Item* pItem2 = NULL, uint32 itemid = 0) const; void SendBuyError(BuyResult msg, Creature* pCreature, uint32 item, uint32 param); void SendSellError(SellResult msg, Creature* pCreature, ObjectGuid itemGuid, uint32 param); void AddWeaponProficiency(uint32 newflag) { m_WeaponProficiency |= newflag; } void AddArmorProficiency(uint32 newflag) { m_ArmorProficiency |= newflag; } uint32 GetWeaponProficiency() const { return m_WeaponProficiency; } uint32 GetArmorProficiency() const { return m_ArmorProficiency; } bool IsTwoHandUsed() const { Item* mainItem = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND); return mainItem && mainItem->GetProto()->InventoryType == INVTYPE_2HWEAPON && !CanTitanGrip(); } bool HasTwoHandWeaponInOneHand() const { Item* offItem = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND); Item* mainItem = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND); return offItem && ((mainItem && mainItem->GetProto()->InventoryType == INVTYPE_2HWEAPON) || offItem->GetProto()->InventoryType == INVTYPE_2HWEAPON); } void SendNewItem(Item* item, uint32 count, bool received, bool created, bool broadcast = false, bool showInChat = true); bool BuyItemFromVendorSlot(ObjectGuid vendorGuid, uint32 vendorslot, uint32 item, uint8 count, uint8 bag, uint8 slot); bool BuyItemFromVendor(ObjectGuid vendorGuid, uint32 item, uint8 count, uint8 bag, uint8 slot); float GetReputationPriceDiscount(Creature const* pCreature) const; Player* GetTrader() const { return m_trade ? m_trade->GetTrader() : NULL; } TradeData* GetTradeData() const { return m_trade; } void TradeCancel(bool sendback); void UpdateEnchantTime(uint32 time); void UpdateItemDuration(uint32 time, bool realtimeonly = false); void AddEnchantmentDurations(Item* item); void RemoveEnchantmentDurations(Item* item); void RemoveAllEnchantments(EnchantmentSlot slot); void AddEnchantmentDuration(Item* item, EnchantmentSlot slot, uint32 duration); void ApplyEnchantment(Item* item, EnchantmentSlot slot, bool apply, bool apply_dur = true, bool ignore_condition = false); void ApplyEnchantment(Item* item, bool apply); void SendEnchantmentDurations(); void BuildEnchantmentsInfoData(WorldPacket* data); void AddItemDurations(Item* item); void RemoveItemDurations(Item* item); void SendItemDurations(); void LoadCorpse(); void LoadPet(); uint32 m_stableSlots; uint32 GetEquipGearScore(bool withBags = true, bool withBank = false); void ResetCachedGearScore() { m_cachedGS = 0; } typedef std::vector < uint32/*item level*/ > GearScoreVec; /*********************************************************/ /*** GOSSIP SYSTEM ***/ /*********************************************************/ void PrepareGossipMenu(WorldObject* pSource, uint32 menuId = 0); void SendPreparedGossip(WorldObject* pSource); void OnGossipSelect(WorldObject* pSource, uint32 gossipListId, uint32 menuId); uint32 GetGossipTextId(uint32 menuId, WorldObject* pSource); uint32 GetGossipTextId(WorldObject* pSource); uint32 GetDefaultGossipMenuForSource(WorldObject* pSource); /*********************************************************/ /*** QUEST SYSTEM ***/ /*********************************************************/ // Return player level when QuestLevel is dynamic (-1) uint32 GetQuestLevelForPlayer(Quest const* pQuest) const { return pQuest && (pQuest->GetQuestLevel() > 0) ? (uint32)pQuest->GetQuestLevel() : getLevel(); } void PrepareQuestMenu(ObjectGuid guid); void SendPreparedQuest(ObjectGuid guid); bool IsActiveQuest(uint32 quest_id) const; // can be taken or taken // Quest is taken and not yet rewarded // if completed_or_not = 0 (or any other value except 1 or 2) - returns true, if quest is taken and doesn't depend if quest is completed or not // if completed_or_not = 1 - returns true, if quest is taken but not completed // if completed_or_not = 2 - returns true, if quest is taken and already completed bool IsCurrentQuest(uint32 quest_id, uint8 completed_or_not = 0) const; // taken and not yet rewarded Quest const* GetNextQuest(ObjectGuid guid, Quest const* pQuest); bool CanSeeStartQuest(Quest const* pQuest) const; bool CanTakeQuest(Quest const* pQuest, bool msg) const; bool CanAddQuest(Quest const* pQuest, bool msg) const; bool CanCompleteQuest(uint32 quest_id) const; bool CanCompleteRepeatableQuest(Quest const* pQuest) const; bool CanRewardQuest(Quest const* pQuest, bool msg) const; bool CanRewardQuest(Quest const* pQuest, uint32 reward, bool msg) const; void AddQuest(Quest const* pQuest, Object* questGiver); void CompleteQuest(uint32 quest_id, QuestStatus status = QUEST_STATUS_COMPLETE); void IncompleteQuest(uint32 quest_id); void RewardQuest(Quest const* pQuest, uint32 reward, Object* questGiver, bool announce = true); void FailQuest(uint32 quest_id); bool SatisfyQuestSkill(Quest const* qInfo, bool msg) const; bool SatisfyQuestLevel(Quest const* qInfo, bool msg) const; bool SatisfyQuestLog(bool msg) const; bool SatisfyQuestPreviousQuest(Quest const* qInfo, bool msg) const; bool SatisfyQuestClass(Quest const* qInfo, bool msg) const; bool SatisfyQuestRace(Quest const* qInfo, bool msg) const; bool SatisfyQuestReputation(Quest const* qInfo, bool msg) const; bool SatisfyQuestStatus(Quest const* qInfo, bool msg) const; bool SatisfyQuestTimed(Quest const* qInfo, bool msg) const; bool SatisfyQuestExclusiveGroup(Quest const* qInfo, bool msg) const; bool SatisfyQuestNextChain(Quest const* qInfo, bool msg) const; bool SatisfyQuestPrevChain(Quest const* qInfo, bool msg) const; bool SatisfyQuestDay(Quest const* qInfo, bool msg) const; bool SatisfyQuestWeek(Quest const* qInfo) const; bool SatisfyQuestMonth(Quest const* qInfo) const; bool CanGiveQuestSourceItemIfNeed(Quest const* pQuest, ItemPosCountVec* dest = NULL) const; void GiveQuestSourceItemIfNeed(Quest const* pQuest); bool TakeQuestSourceItem(uint32 quest_id, bool msg); bool GetQuestRewardStatus(uint32 quest_id) const; QuestStatus GetQuestStatus(uint32 quest_id) const; void SetQuestStatus(uint32 quest_id, QuestStatus status); void SetDailyQuestStatus(uint32 quest_id); void SetWeeklyQuestStatus(uint32 quest_id); void SetMonthlyQuestStatus(uint32 quest_id); void ResetDailyQuestStatus(); void ResetWeeklyQuestStatus(); void ResetMonthlyQuestStatus(); uint16 FindQuestSlot(uint32 quest_id) const; uint32 GetQuestSlotQuestId(uint16 slot) const { return GetUInt32Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_ID_OFFSET); } void SetQuestSlot(uint16 slot, uint32 quest_id, uint32 timer = 0) { SetUInt32Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_ID_OFFSET, quest_id); SetUInt32Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_STATE_OFFSET, 0); SetUInt32Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_COUNTS_OFFSET, 0); SetUInt32Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_COUNTS_OFFSET + 1, 0); SetUInt32Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_TIME_OFFSET, timer); } void SetQuestSlotCounter(uint16 slot, uint8 counter, uint16 count) { uint64 val = GetUInt64Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_COUNTS_OFFSET); val &= ~((uint64)0xFFFF << (counter * 16)); val |= ((uint64)count << (counter * 16)); SetUInt64Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_COUNTS_OFFSET, val); } void SetQuestSlotState(uint16 slot, uint32 state) { SetFlag(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_STATE_OFFSET, state); } void RemoveQuestSlotState(uint16 slot, uint32 state) { RemoveFlag(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_STATE_OFFSET, state); } void SetQuestSlotTimer(uint16 slot, uint32 timer) { SetUInt32Value(PLAYER_QUEST_LOG_1_1 + slot * MAX_QUEST_OFFSET + QUEST_TIME_OFFSET, timer); } void SwapQuestSlot(uint16 slot1, uint16 slot2) { for (int i = 0; i < MAX_QUEST_OFFSET; ++i) { uint32 temp1 = GetUInt32Value(PLAYER_QUEST_LOG_1_1 + MAX_QUEST_OFFSET * slot1 + i); uint32 temp2 = GetUInt32Value(PLAYER_QUEST_LOG_1_1 + MAX_QUEST_OFFSET * slot2 + i); SetUInt32Value(PLAYER_QUEST_LOG_1_1 + MAX_QUEST_OFFSET * slot1 + i, temp2); SetUInt32Value(PLAYER_QUEST_LOG_1_1 + MAX_QUEST_OFFSET * slot2 + i, temp1); } } uint32 GetReqKillOrCastCurrentCount(uint32 quest_id, int32 entry); void AreaExploredOrEventHappens(uint32 questId); void GroupEventHappens(uint32 questId, WorldObject const* pEventObject); void ItemAddedQuestCheck(uint32 entry, uint32 count); void ItemRemovedQuestCheck(uint32 entry, uint32 count); void KilledMonster(CreatureInfo const* cInfo, ObjectGuid guid); void KilledMonsterCredit(uint32 entry, ObjectGuid guid = ObjectGuid()); void CastedCreatureOrGO(uint32 entry, ObjectGuid guid, uint32 spell_id, bool original_caster = true); void TalkedToCreature(uint32 entry, ObjectGuid guid); void MoneyChanged(uint32 value); void ReputationChanged(FactionEntry const* factionEntry); bool HasQuestForItem(uint32 itemid) const; bool HasQuestForGO(int32 GOId) const; void UpdateForQuestWorldObjects(); bool CanShareQuest(uint32 quest_id) const; void SendQuestCompleteEvent(uint32 quest_id); void SendQuestReward(Quest const* pQuest, uint32 XP); void SendQuestFailed(uint32 quest_id, InventoryResult reason = EQUIP_ERR_OK); void SendQuestTimerFailed(uint32 quest_id); void SendCanTakeQuestResponse(uint32 msg) const; void SendQuestConfirmAccept(Quest const* pQuest, Player* pReceiver); void SendPushToPartyResponse(Player* pPlayer, uint32 msg); void SendQuestUpdateAddItem(Quest const* pQuest, uint32 item_idx, uint32 count); void SendQuestUpdateAddCreatureOrGo(Quest const* pQuest, ObjectGuid guid, uint32 creatureOrGO_idx, uint32 count); ObjectGuid GetDividerGuid() const { return m_dividerGuid; } void SetDividerGuid(ObjectGuid guid) { m_dividerGuid = guid; } void ClearDividerGuid() { m_dividerGuid.Clear(); } uint32 GetInGameTime() { return m_ingametime; } void SetInGameTime(uint32 time) { m_ingametime = time; } void AddTimedQuest(uint32 quest_id) { m_timedquests.insert(quest_id); } void RemoveTimedQuest(uint32 quest_id) { m_timedquests.erase(quest_id); } /// Return collision height sent to client float GetCollisionHeight(bool mounted) const; /*********************************************************/ /*** LOAD SYSTEM ***/ /*********************************************************/ bool LoadFromDB(ObjectGuid guid, SqlQueryHolder* holder); static uint32 GetZoneIdFromDB(ObjectGuid guid); static uint32 GetLevelFromDB(ObjectGuid guid); static bool LoadPositionFromDB(ObjectGuid guid, uint32& mapid, float& x, float& y, float& z, float& o, bool& in_flight); /*********************************************************/ /*** SAVE SYSTEM ***/ /*********************************************************/ void SaveToDB(); void SaveInventoryAndGoldToDB(); // fast save function for item/money cheating preventing void SaveGoldToDB(); static void SetUInt32ValueInArray(Tokens& data, uint16 index, uint32 value); static void SetFloatValueInArray(Tokens& data, uint16 index, float value); static void Customize(ObjectGuid guid, uint8 gender, uint8 skin, uint8 face, uint8 hairStyle, uint8 hairColor, uint8 facialHair); static void SavePositionInDB(ObjectGuid guid, uint32 mapid, float x, float y, float z, float o, uint32 zone); static void DeleteFromDB(ObjectGuid playerguid, uint32 accountId, bool updateRealmChars = true, bool deleteFinally = false); static void DeleteOldCharacters(); static void DeleteOldCharacters(uint32 keepDays); bool m_mailsUpdated; void SendPetTameFailure(PetTameFailureReason reason); void SetBindPoint(ObjectGuid guid); void SendTalentWipeConfirm(ObjectGuid guid); void RewardRage(uint32 damage, uint32 weaponSpeedHitFactor, bool attacker); void SendPetSkillWipeConfirm(); void CalcRage(uint32 damage, bool attacker); void RegenerateAll(uint32 diff = REGEN_TIME_FULL); void Regenerate(Powers power, uint32 diff); void RegenerateHealth(uint32 diff); void setRegenTimer(uint32 time) { m_regenTimer = time; } void setWeaponChangeTimer(uint32 time) { m_weaponChangeTimer = time; } uint32 GetMoney() const { return GetUInt32Value(PLAYER_FIELD_COINAGE); } void ModifyMoney(int32 d); void SetMoney(uint32 value) { SetUInt32Value(PLAYER_FIELD_COINAGE, value); MoneyChanged(value); UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_GOLD_VALUE_OWNED); } QuestStatusMap& getQuestStatusMap() { return mQuestStatus; }; ObjectGuid const& GetSelectionGuid() const { return m_curSelectionGuid; } void SetSelectionGuid(ObjectGuid guid) { m_curSelectionGuid = guid; SetTargetGuid(guid); } uint8 GetComboPoints() const { return m_comboPoints; } ObjectGuid const& GetComboTargetGuid() const { return m_comboTargetGuid; } void AddComboPoints(Unit* target, int8 count); void ClearComboPoints(); void SendComboPoints(); void SendMailResult(uint32 mailId, MailResponseType mailAction, MailResponseResult mailError, uint32 equipError = 0, uint32 item_guid = 0, uint32 item_count = 0); void SendNewMail(); void UpdateNextMailTimeAndUnreads(); void AddNewMailDeliverTime(time_t deliver_time); void RemoveMail(uint32 id); void AddMail(Mail* mail) { m_mail.push_front(mail); // for call from WorldSession::SendMailTo } uint32 GetMailSize() { return m_mail.size(); } Mail* GetMail(uint32 id); PlayerMails::iterator GetMailBegin() { return m_mail.begin(); } PlayerMails::iterator GetMailEnd() { return m_mail.end(); } /*********************************************************/ /*** MAILED ITEMS SYSTEM ***/ /*********************************************************/ uint8 unReadMails; time_t m_nextMailDelivereTime; typedef UNORDERED_MAP<uint32, Item*> ItemMap; ItemMap mMitems; // template defined in objectmgr.cpp Item* GetMItem(uint32 id) { ItemMap::const_iterator itr = mMitems.find(id); return itr != mMitems.end() ? itr->second : NULL; } void AddMItem(Item* it) { MANGOS_ASSERT(it); // ASSERT deleted, because items can be added before loading mMitems[it->GetGUIDLow()] = it; } bool RemoveMItem(uint32 id) { return mMitems.erase(id) ? true : false; } void PetSpellInitialize(); void SendPetGUIDs(); void CharmSpellInitialize(); void PossessSpellInitialize(); void RemovePetActionBar(); bool HasSpell(uint32 spell) const override; bool HasActiveSpell(uint32 spell) const; // show in spellbook TrainerSpellState GetTrainerSpellState(TrainerSpell const* trainer_spell, uint32 reqLevel) const; bool IsSpellFitByClassAndRace(uint32 spell_id, uint32* pReqlevel = NULL) const; bool IsNeedCastPassiveLikeSpellAtLearn(SpellEntry const* spellInfo) const; bool IsImmuneToSpellEffect(SpellEntry const* spellInfo, SpellEffectIndex index, bool castOnSelf) const override; void SendProficiency(ItemClass itemClass, uint32 itemSubclassMask); void SendInitialSpells(); bool addSpell(uint32 spell_id, bool active, bool learning, bool dependent, bool disabled); void learnSpell(uint32 spell_id, bool dependent); void removeSpell(uint32 spell_id, bool disabled = false, bool learn_low_rank = true, bool sendUpdate = true); void resetSpells(); void learnDefaultSpells(); void learnQuestRewardedSpells(); void learnQuestRewardedSpells(Quest const* quest); void learnSpellHighRank(uint32 spellid); uint32 GetFreeTalentPoints() const { return GetUInt32Value(PLAYER_CHARACTER_POINTS1); } void SetFreeTalentPoints(uint32 points); void UpdateFreeTalentPoints(bool resetIfNeed = true); bool resetTalents(bool no_cost = false, bool all_specs = false); uint32 resetTalentsCost() const; void InitTalentForLevel(); void BuildPlayerTalentsInfoData(WorldPacket* data); void BuildPetTalentsInfoData(WorldPacket* data); void SendTalentsInfoData(bool pet); void LearnTalent(uint32 talentId, uint32 talentRank); void LearnPetTalent(ObjectGuid petGuid, uint32 talentId, uint32 talentRank); bool HasTalent(uint32 spell_id, uint8 spec) const; uint32 CalculateTalentsPoints() const; // Dual Spec uint8 GetActiveSpec() { return m_activeSpec; } void SetActiveSpec(uint8 spec) { m_activeSpec = spec; } uint8 GetSpecsCount() { return m_specsCount; } void SetSpecsCount(uint8 count) { m_specsCount = count; } void ActivateSpec(uint8 specNum); void UpdateSpecCount(uint8 count); void InitGlyphsForLevel(); void SetGlyphSlot(uint8 slot, uint32 slottype) { SetUInt32Value(PLAYER_FIELD_GLYPH_SLOTS_1 + slot, slottype); } uint32 GetGlyphSlot(uint8 slot) { return GetUInt32Value(PLAYER_FIELD_GLYPH_SLOTS_1 + slot); } void SetGlyph(uint8 slot, uint32 glyph) { m_glyphs[m_activeSpec][slot].SetId(glyph); } uint32 GetGlyph(uint8 slot) { return m_glyphs[m_activeSpec][slot].GetId(); } void ApplyGlyph(uint8 slot, bool apply); void ApplyGlyphs(bool apply); uint32 GetFreePrimaryProfessionPoints() const { return GetUInt32Value(PLAYER_CHARACTER_POINTS2); } void SetFreePrimaryProfessions(uint16 profs) { SetUInt32Value(PLAYER_CHARACTER_POINTS2, profs); } void InitPrimaryProfessions(); PlayerSpellMap const& GetSpellMap() const { return m_spells; } PlayerSpellMap& GetSpellMap() { return m_spells; } SpellCooldowns const& GetSpellCooldownMap() const { return m_spellCooldowns; } PlayerTalent const* GetKnownTalentById(int32 talentId) const; SpellEntry const* GetKnownTalentRankById(int32 talentId) const; void AddSpellMod(Aura* aura, bool apply); template <class T> T ApplySpellMod(uint32 spellId, SpellModOp op, T& basevalue); static uint32 const infinityCooldownDelay = MONTH; // used for set "infinity cooldowns" for spells and check static uint32 const infinityCooldownDelayCheck = MONTH / 2; bool HasSpellCooldown(uint32 spell_id) const { SpellCooldowns::const_iterator itr = m_spellCooldowns.find(spell_id); return itr != m_spellCooldowns.end() && itr->second.end > time(NULL); } time_t GetSpellCooldownDelay(uint32 spell_id) const { SpellCooldowns::const_iterator itr = m_spellCooldowns.find(spell_id); time_t t = time(NULL); return itr != m_spellCooldowns.end() && itr->second.end > t ? itr->second.end - t : 0; } void AddSpellAndCategoryCooldowns(SpellEntry const* spellInfo, uint32 itemId, Spell* spell = NULL, bool infinityCooldown = false); void AddSpellCooldown(uint32 spell_id, uint32 itemid, time_t end_time); void SendCooldownEvent(SpellEntry const* spellInfo, uint32 itemId = 0, Spell* spell = NULL); void ProhibitSpellSchool(SpellSchoolMask idSchoolMask, uint32 unTimeMs) override; void RemoveSpellCooldown(uint32 spell_id, bool update = false); void RemoveSpellCategoryCooldown(uint32 cat, bool update = false); void SendClearCooldown(uint32 spell_id, Unit* target); GlobalCooldownMgr& GetGlobalCooldownMgr() { return m_GlobalCooldownMgr; } void RemoveArenaSpellCooldowns(); void RemoveAllSpellCooldown(); void _LoadSpellCooldowns(QueryResult* result); void _SaveSpellCooldowns(); void SetLastPotionId(uint32 item_id) { m_lastPotionId = item_id; } uint32 GetLastPotionId() { return m_lastPotionId; } void UpdatePotionCooldown(Spell* spell = NULL); void setResurrectRequestData(ObjectGuid guid, uint32 mapId, float X, float Y, float Z, uint32 health, uint32 mana) { m_resurrectGuid = guid; m_resurrectMap = mapId; m_resurrectX = X; m_resurrectY = Y; m_resurrectZ = Z; m_resurrectHealth = health; m_resurrectMana = mana; } void clearResurrectRequestData() { setResurrectRequestData(ObjectGuid(), 0, 0.0f, 0.0f, 0.0f, 0, 0); } bool isRessurectRequestedBy(ObjectGuid guid) const { return m_resurrectGuid == guid; } bool isRessurectRequested() const { return !m_resurrectGuid.IsEmpty(); } void ResurectUsingRequestData(); uint32 getCinematic() { return m_cinematic; } void setCinematic(uint32 cine) { m_cinematic = cine; } static bool IsActionButtonDataValid(uint8 button, uint32 action, uint8 type, Player* player, bool msg = true); ActionButton* addActionButton(uint8 spec, uint8 button, uint32 action, uint8 type); void removeActionButton(uint8 spec, uint8 button); void SendInitialActionButtons() const; void SendLockActionButtons() const; ActionButton const* GetActionButton(uint8 button); PvPInfo pvpInfo; void UpdatePvP(bool state, bool ovrride = false); void UpdateZone(uint32 newZone, uint32 newArea); void UpdateArea(uint32 newArea); uint32 GetCachedZoneId() const { return m_zoneUpdateId; } void UpdateZoneDependentAuras(); void UpdateAreaDependentAuras(); // subzones void UpdateZoneDependentPets(); void UpdateAfkReport(time_t currTime); void UpdatePvPFlag(time_t currTime); void UpdateContestedPvP(uint32 currTime); void SetContestedPvPTimer(uint32 newTime) { m_contestedPvPTimer = newTime; } void ResetContestedPvP() { clearUnitState(UNIT_STAT_ATTACK_PLAYER); RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_CONTESTED_PVP); m_contestedPvPTimer = 0; } /** todo: -maybe move UpdateDuelFlag+DuelComplete to independent DuelHandler.. **/ DuelInfo* duel; bool IsInDuelWith(Player const* player) const { return duel && duel->opponent == player && duel->startTime != 0; } void UpdateDuelFlag(time_t currTime); void CheckDuelDistance(time_t currTime); void DuelComplete(DuelCompleteType type); void SendDuelCountdown(uint32 counter); bool IsGroupVisibleFor(Player* p) const; bool IsInSameGroupWith(Player const* p) const; bool IsInSameRaidWith(Player const* p) const { return p == this || (GetGroup() != NULL && GetGroup() == p->GetGroup()); } void UninviteFromGroup(); static void RemoveFromGroup(Group* group, ObjectGuid guid, ObjectGuid kicker, std::string reason); void RemoveFromGroup() { RemoveFromGroup(GetGroup(), GetObjectGuid(), GetObjectGuid(), ""); } void SendUpdateToOutOfRangeGroupMembers(); void SetAllowLowLevelRaid(bool allow) { ApplyModFlag(PLAYER_FLAGS, PLAYER_FLAGS_ENABLE_LOW_LEVEL_RAID, allow); } bool GetAllowLowLevelRaid() const { return HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_ENABLE_LOW_LEVEL_RAID); } void SetInGuild(uint32 GuildId) { SetUInt32Value(PLAYER_GUILDID, GuildId); } void SetRank(uint32 rankId) { SetUInt32Value(PLAYER_GUILDRANK, rankId); } void SetGuildIdInvited(uint32 GuildId) { m_GuildIdInvited = GuildId; } uint32 GetGuildId() { return GetUInt32Value(PLAYER_GUILDID); } static uint32 GetGuildIdFromDB(ObjectGuid guid); uint32 GetRank() { return GetUInt32Value(PLAYER_GUILDRANK); } static uint32 GetRankFromDB(ObjectGuid guid); int GetGuildIdInvited() { return m_GuildIdInvited; } static void RemovePetitionsAndSigns(ObjectGuid guid, uint32 type); // Arena Team void SetInArenaTeam(uint32 ArenaTeamId, uint8 slot, ArenaType type) { SetArenaTeamInfoField(slot, ARENA_TEAM_ID, ArenaTeamId); SetArenaTeamInfoField(slot, ARENA_TEAM_TYPE, type); } void SetArenaTeamInfoField(uint8 slot, ArenaTeamInfoType type, uint32 value) { SetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (slot * ARENA_TEAM_END) + type, value); } uint32 GetArenaTeamId(uint8 slot) { return GetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (slot * ARENA_TEAM_END) + ARENA_TEAM_ID); } uint32 GetArenaPersonalRating(uint8 slot) { return GetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (slot * ARENA_TEAM_END) + ARENA_TEAM_PERSONAL_RATING); } static uint32 GetArenaTeamIdFromDB(ObjectGuid guid, ArenaType type); void SetArenaTeamIdInvited(uint32 ArenaTeamId) { m_ArenaTeamIdInvited = ArenaTeamId; } uint32 GetArenaTeamIdInvited() { return m_ArenaTeamIdInvited; } static void LeaveAllArenaTeams(ObjectGuid guid); Difficulty GetDifficulty(bool isRaid) const { return isRaid ? m_raidDifficulty : m_dungeonDifficulty; } Difficulty GetDungeonDifficulty() const { return m_dungeonDifficulty; } Difficulty GetRaidDifficulty() const { return m_raidDifficulty; } void SetDungeonDifficulty(Difficulty dungeon_difficulty) { m_dungeonDifficulty = dungeon_difficulty; } void SetRaidDifficulty(Difficulty raid_difficulty) { m_raidDifficulty = raid_difficulty; } bool UpdateSkill(uint32 skill_id, uint32 step); bool UpdateSkillPro(uint16 SkillId, int32 Chance, uint32 step); bool UpdateCraftSkill(uint32 spellid); bool UpdateGatherSkill(uint32 SkillId, uint32 SkillValue, uint32 RedLevel, uint32 Multiplicator = 1); bool UpdateFishingSkill(); uint32 GetBaseDefenseSkillValue() const { return GetBaseSkillValue(SKILL_DEFENSE); } uint32 GetBaseWeaponSkillValue(WeaponAttackType attType) const; uint32 GetSpellByProto(ItemPrototype* proto); float GetHealthBonusFromStamina(); float GetManaBonusFromIntellect(); bool UpdateStats(Stats stat) override; bool UpdateAllStats() override; void UpdateResistances(uint32 school) override; void UpdateArmor() override; void UpdateMaxHealth() override; void UpdateMaxPower(Powers power) override; void ApplyFeralAPBonus(int32 amount, bool apply); void UpdateAttackPowerAndDamage(bool ranged = false) override; void UpdateShieldBlockValue(); void UpdateDamagePhysical(WeaponAttackType attType) override; void ApplySpellPowerBonus(int32 amount, bool apply); void UpdateSpellDamageAndHealingBonus(); void ApplyRatingMod(CombatRating cr, int32 value, bool apply); void UpdateRating(CombatRating cr); void UpdateAllRatings(); void CalculateMinMaxDamage(WeaponAttackType attType, bool normalized, float& min_damage, float& max_damage); void UpdateDefenseBonusesMod(); float GetMeleeCritFromAgility(); void GetDodgeFromAgility(float& diminishing, float& nondiminishing); float GetSpellCritFromIntellect(); float OCTRegenHPPerSpirit(); float OCTRegenMPPerSpirit(); float GetRatingMultiplier(CombatRating cr) const; float GetRatingBonusValue(CombatRating cr) const; uint32 GetBaseSpellPowerBonus() { return m_baseSpellPower; } float GetExpertiseDodgeOrParryReduction(WeaponAttackType attType) const; void UpdateBlockPercentage(); void UpdateCritPercentage(WeaponAttackType attType); void UpdateAllCritPercentages(); void UpdateParryPercentage(); void UpdateDodgePercentage(); void UpdateMeleeHitChances(); void UpdateRangedHitChances(); void UpdateSpellHitChances(); void UpdateAllSpellCritChances(); void UpdateSpellCritChance(uint32 school); void UpdateExpertise(WeaponAttackType attType); void UpdateArmorPenetration(); void ApplyManaRegenBonus(int32 amount, bool apply); void UpdateManaRegen(); ObjectGuid const& GetLootGuid() const { return m_lootGuid; } void SetLootGuid(ObjectGuid const& guid) { m_lootGuid = guid; } void RemovedInsignia(Player* looterPlr); WorldSession* GetSession() const { return m_session; } void SetSession(WorldSession* s) { m_session = s; } void BuildCreateUpdateBlockForPlayer(UpdateData* data, Player* target) const override; void DestroyForPlayer(Player* target, bool anim = false) const override; void SendLogXPGain(uint32 GivenXP, Unit* victim, uint32 RestXP); uint8 LastSwingErrorMsg() const { return m_swingErrorMsg; } void SwingErrorMsg(uint8 val) { m_swingErrorMsg = val; } // notifiers void SendAttackSwingCantAttack(); void SendAttackSwingCancelAttack(); void SendAttackSwingDeadTarget(); void SendAttackSwingNotInRange(); void SendAttackSwingBadFacingAttack(); void SendAutoRepeatCancel(Unit* target); void SendExplorationExperience(uint32 Area, uint32 Experience); void SendDungeonDifficulty(bool IsInGroup); void SendRaidDifficulty(bool IsInGroup); void ResetInstances(InstanceResetMethod method, bool isRaid); void SendResetInstanceSuccess(uint32 MapId); void SendResetInstanceFailed(uint32 reason, uint32 MapId); void SendResetFailedNotify(uint32 mapid); bool SetPosition(float x, float y, float z, float orientation, bool teleport = false); void UpdateUnderwaterState(Map* m, float x, float y, float z); void SendMessageToSet(WorldPacket* data, bool self) const override;// overwrite Object::SendMessageToSet void SendMessageToSetInRange(WorldPacket* data, float fist, bool self) const override; // overwrite Object::SendMessageToSetInRange void SendMessageToSetInRange(WorldPacket* data, float dist, bool self, bool own_team_only) const; Corpse* GetCorpse() const; void SpawnCorpseBones(); Corpse* CreateCorpse(); void KillPlayer(); uint32 GetResurrectionSpellId(); void ResurrectPlayer(float restore_percent, bool applySickness = false); void BuildPlayerRepop(); void RepopAtGraveyard(); void DurabilityLossAll(double percent, bool inventory); void DurabilityLoss(Item* item, double percent); void DurabilityPointsLossAll(int32 points, bool inventory); void DurabilityPointsLoss(Item* item, int32 points); void DurabilityPointLossForEquipSlot(EquipmentSlots slot); uint32 DurabilityRepairAll(bool cost, float discountMod, bool guildBank); uint32 DurabilityRepair(uint16 pos, bool cost, float discountMod, bool guildBank); void UpdateMirrorTimers(); void StopMirrorTimers() { StopMirrorTimer(FATIGUE_TIMER); StopMirrorTimer(BREATH_TIMER); StopMirrorTimer(FIRE_TIMER); } void SetLevitate(bool enable) override; void SetCanFly(bool enable) override; void SetFeatherFall(bool enable) override; void SetHover(bool enable) override; void SetRoot(bool enable) override; void SetWaterWalk(bool enable) override; void JoinedChannel(Channel* c); void LeftChannel(Channel* c); void CleanupChannels(); void UpdateLocalChannels(uint32 newZone); void LeaveLFGChannel(); void UpdateDefense(); void UpdateWeaponSkill(WeaponAttackType attType); void UpdateCombatSkills(Unit* pVictim, WeaponAttackType attType, bool defence); void SetSkill(uint16 id, uint16 currVal, uint16 maxVal, uint16 step = 0); uint16 GetMaxSkillValue(uint32 skill) const; // max + perm. bonus + temp bonus uint16 GetPureMaxSkillValue(uint32 skill) const; // max uint16 GetSkillValue(uint32 skill) const; // skill value + perm. bonus + temp bonus uint16 GetBaseSkillValue(uint32 skill) const; // skill value + perm. bonus uint16 GetPureSkillValue(uint32 skill) const; // skill value int16 GetSkillPermBonusValue(uint32 skill) const; int16 GetSkillTempBonusValue(uint32 skill) const; bool HasSkill(uint32 skill) const; void learnSkillRewardedSpells(uint32 id, uint32 value); WorldLocation& GetTeleportDest() { return m_teleport_dest; } bool IsBeingTeleported() const { return mSemaphoreTeleport_Near || mSemaphoreTeleport_Far; } bool IsBeingTeleportedNear() const { return mSemaphoreTeleport_Near; } bool IsBeingTeleportedFar() const { return mSemaphoreTeleport_Far; } void SetSemaphoreTeleportNear(bool semphsetting) { mSemaphoreTeleport_Near = semphsetting; } void SetSemaphoreTeleportFar(bool semphsetting) { mSemaphoreTeleport_Far = semphsetting; } void ProcessDelayedOperations(); void CheckAreaExploreAndOutdoor(); static Team TeamForRace(uint8 race); Team GetTeam() const { return m_team; } TeamId GetTeamId() const { return m_team == ALLIANCE ? TEAM_ALLIANCE : TEAM_HORDE; } static uint32 getFactionForRace(uint8 race); void setFactionForRace(uint8 race); void InitDisplayIds(); bool IsAtGroupRewardDistance(WorldObject const* pRewardSource) const; void RewardSinglePlayerAtKill(Unit* pVictim); void RewardPlayerAndGroupAtEvent(uint32 creature_id, WorldObject* pRewardSource); void RewardPlayerAndGroupAtCast(WorldObject* pRewardSource, uint32 spellid = 0); bool isHonorOrXPTarget(Unit* pVictim) const; ReputationMgr& GetReputationMgr() { return m_reputationMgr; } ReputationMgr const& GetReputationMgr() const { return m_reputationMgr; } ReputationRank GetReputationRank(uint32 faction_id) const; void RewardReputation(Unit* pVictim, float rate); void RewardReputation(Quest const* pQuest); int32 CalculateReputationGain(ReputationSource source, int32 rep, int32 faction, uint32 creatureOrQuestLevel = 0, bool noAuraBonus = false); void UpdateSkillsForLevel(); void UpdateSkillsToMaxSkillsForLevel(); // for .levelup void ModifySkillBonus(uint32 skillid, int32 val, bool talent); /*********************************************************/ /*** PVP SYSTEM ***/ /*********************************************************/ void UpdateArenaFields(); void UpdateHonorFields(); bool RewardHonor(Unit* pVictim, uint32 groupsize, float honor = -1); uint32 GetHonorPoints() const { return GetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY); } uint32 GetArenaPoints() const { return GetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY); } void SetHonorPoints(uint32 value); void SetArenaPoints(uint32 value); void ModifyHonorPoints(int32 value); void ModifyArenaPoints(int32 value); uint32 GetMaxPersonalArenaRatingRequirement(uint32 minarenaslot); // End of PvP System void SetDrunkValue(uint8 newDrunkValue, uint32 itemId = 0); uint8 GetDrunkValue() const { return GetByteValue(PLAYER_BYTES_3, 1); } static DrunkenState GetDrunkenstateByValue(uint8 value); uint32 GetDeathTimer() const { return m_deathTimer; } uint32 GetCorpseReclaimDelay(bool pvp) const; void UpdateCorpseReclaimDelay(); void SendCorpseReclaimDelay(bool load = false); uint32 GetShieldBlockValue() const override; // overwrite Unit version (virtual) bool CanParry() const { return m_canParry; } void SetCanParry(bool value); bool CanBlock() const { return m_canBlock; } void SetCanBlock(bool value); bool CanDualWield() const { return m_canDualWield; } void SetCanDualWield(bool value) { m_canDualWield = value; } bool CanTitanGrip() const { return m_canTitanGrip; } void SetCanTitanGrip(bool value) { m_canTitanGrip = value; } bool CanTameExoticPets() const { return isGameMaster() || HasAuraType(SPELL_AURA_ALLOW_TAME_PET_TYPE); } void SetRegularAttackTime(); void SetBaseModValue(BaseModGroup modGroup, BaseModType modType, float value) { m_auraBaseMod[modGroup][modType] = value; } void HandleBaseModValue(BaseModGroup modGroup, BaseModType modType, float amount, bool apply); float GetBaseModValue(BaseModGroup modGroup, BaseModType modType) const; float GetTotalBaseModValue(BaseModGroup modGroup) const; float GetTotalPercentageModValue(BaseModGroup modGroup) const { return m_auraBaseMod[modGroup][FLAT_MOD] + m_auraBaseMod[modGroup][PCT_MOD]; } void _ApplyAllStatBonuses(); void _RemoveAllStatBonuses(); float GetArmorPenetrationPct() const { return m_armorPenetrationPct; } int32 GetSpellPenetrationItemMod() const { return m_spellPenetrationItemMod; } void _ApplyWeaponDependentAuraMods(Item* item, WeaponAttackType attackType, bool apply); void _ApplyWeaponDependentAuraCritMod(Item* item, WeaponAttackType attackType, Aura* aura, bool apply); void _ApplyWeaponDependentAuraDamageMod(Item* item, WeaponAttackType attackType, Aura* aura, bool apply); void _ApplyItemMods(Item* item, uint8 slot, bool apply); void _RemoveAllItemMods(); void _ApplyAllItemMods(); void _ApplyAllLevelScaleItemMods(bool apply); void _ApplyItemBonuses(ItemPrototype const* proto, uint8 slot, bool apply, bool only_level_scale = false); void _ApplyAmmoBonuses(); bool EnchantmentFitsRequirements(uint32 enchantmentcondition, int8 slot); void ToggleMetaGemsActive(uint8 exceptslot, bool apply); void CorrectMetaGemEnchants(uint8 slot, bool apply); void InitDataForForm(bool reapplyMods = false); void ApplyItemEquipSpell(Item* item, bool apply, bool form_change = false); void ApplyEquipSpell(SpellEntry const* spellInfo, Item* item, bool apply, bool form_change = false); void UpdateEquipSpellsAtFormChange(); void CastItemCombatSpell(Unit* Target, WeaponAttackType attType); void CastItemUseSpell(Item* item, SpellCastTargets const& targets, uint8 cast_count, uint32 glyphIndex); void ApplyItemOnStoreSpell(Item* item, bool apply); void DestroyItemWithOnStoreSpell(Item* item, uint32 spellId); void SendEquipmentSetList(); void SetEquipmentSet(uint32 index, EquipmentSet eqset); void DeleteEquipmentSet(uint64 setGuid); void SendInitWorldStates(uint32 zone, uint32 area); void SendUpdateWorldState(uint32 Field, uint32 Value); void SendDirectMessage(WorldPacket* data) const; void FillBGWeekendWorldStates(WorldPacket& data, uint32& count); void SendAurasForTarget(Unit* target); PlayerMenu* PlayerTalkClass; std::vector<ItemSetEffect*> ItemSetEff; void SendLoot(ObjectGuid guid, LootType loot_type); void SendLootRelease(ObjectGuid guid); void SendNotifyLootItemRemoved(uint8 lootSlot); void SendNotifyLootMoneyRemoved(); /*********************************************************/ /*** BATTLEGROUND SYSTEM ***/ /*********************************************************/ bool InBattleGround() const { return m_bgData.bgInstanceID != 0; } bool InArena() const; uint32 GetBattleGroundId() const { return m_bgData.bgInstanceID; } BattleGroundTypeId GetBattleGroundTypeId() const { return m_bgData.bgTypeID; } BattleGround* GetBattleGround() const; bool InBattleGroundQueue() const { for (int i = 0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; ++i) if (m_bgBattleGroundQueueID[i].bgQueueTypeId != BATTLEGROUND_QUEUE_NONE) { return true; } return false; } BattleGroundQueueTypeId GetBattleGroundQueueTypeId(uint32 index) const { return m_bgBattleGroundQueueID[index].bgQueueTypeId; } uint32 GetBattleGroundQueueIndex(BattleGroundQueueTypeId bgQueueTypeId) const { for (int i = 0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; ++i) if (m_bgBattleGroundQueueID[i].bgQueueTypeId == bgQueueTypeId) { return i; } return PLAYER_MAX_BATTLEGROUND_QUEUES; } bool IsInvitedForBattleGroundQueueType(BattleGroundQueueTypeId bgQueueTypeId) const { for (int i = 0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; ++i) if (m_bgBattleGroundQueueID[i].bgQueueTypeId == bgQueueTypeId) { return m_bgBattleGroundQueueID[i].invitedToInstance != 0; } return false; } bool InBattleGroundQueueForBattleGroundQueueType(BattleGroundQueueTypeId bgQueueTypeId) const { return GetBattleGroundQueueIndex(bgQueueTypeId) < PLAYER_MAX_BATTLEGROUND_QUEUES; } void SetBattleGroundId(uint32 val, BattleGroundTypeId bgTypeId) { m_bgData.bgInstanceID = val; m_bgData.bgTypeID = bgTypeId; m_bgData.m_needSave = true; } uint32 AddBattleGroundQueueId(BattleGroundQueueTypeId val) { for (int i = 0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; ++i) { if (m_bgBattleGroundQueueID[i].bgQueueTypeId == BATTLEGROUND_QUEUE_NONE || m_bgBattleGroundQueueID[i].bgQueueTypeId == val) { m_bgBattleGroundQueueID[i].bgQueueTypeId = val; m_bgBattleGroundQueueID[i].invitedToInstance = 0; return i; } } return PLAYER_MAX_BATTLEGROUND_QUEUES; } bool HasFreeBattleGroundQueueId() { for (int i = 0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; ++i) if (m_bgBattleGroundQueueID[i].bgQueueTypeId == BATTLEGROUND_QUEUE_NONE) { return true; } return false; } void RemoveBattleGroundQueueId(BattleGroundQueueTypeId val) { for (int i = 0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; ++i) { if (m_bgBattleGroundQueueID[i].bgQueueTypeId == val) { m_bgBattleGroundQueueID[i].bgQueueTypeId = BATTLEGROUND_QUEUE_NONE; m_bgBattleGroundQueueID[i].invitedToInstance = 0; return; } } } void SetInviteForBattleGroundQueueType(BattleGroundQueueTypeId bgQueueTypeId, uint32 instanceId) { for (int i = 0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; ++i) if (m_bgBattleGroundQueueID[i].bgQueueTypeId == bgQueueTypeId) { m_bgBattleGroundQueueID[i].invitedToInstance = instanceId; } } bool IsInvitedForBattleGroundInstance(uint32 instanceId) const { for (int i = 0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; ++i) if (m_bgBattleGroundQueueID[i].invitedToInstance == instanceId) { return true; } return false; } WorldLocation const& GetBattleGroundEntryPoint() const { return m_bgData.joinPos; } void SetBattleGroundEntryPoint(); void SetBGTeam(Team team) { m_bgData.bgTeam = team; m_bgData.m_needSave = true; } Team GetBGTeam() const { return m_bgData.bgTeam ? m_bgData.bgTeam : GetTeam(); } void LeaveBattleground(bool teleportToEntryPoint = true); bool CanJoinToBattleground() const; bool CanReportAfkDueToLimit(); void ReportedAfkBy(Player* reporter); void ClearAfkReports() { m_bgData.bgAfkReporter.clear(); } bool GetBGAccessByLevel(BattleGroundTypeId bgTypeId) const; bool CanUseBattleGroundObject(); bool isTotalImmune(); // returns true if the player is in active state for capture point capturing bool CanUseCapturePoint(); bool GetRandomWinner() { return m_IsBGRandomWinner; } void SetRandomWinner(bool isWinner); /*********************************************************/ /*** REST SYSTEM ***/ /*********************************************************/ bool isRested() const { return GetRestTime() >= 10 * IN_MILLISECONDS; } uint32 GetXPRestBonus(uint32 xp); uint32 GetRestTime() const { return m_restTime; } void SetRestTime(uint32 v) { m_restTime = v; } /*********************************************************/ /*** ENVIRONMENTAL SYSTEM ***/ /*********************************************************/ uint32 EnvironmentalDamage(EnviromentalDamage type, uint32 damage); /*********************************************************/ /*** FLOOD FILTER SYSTEM ***/ /*********************************************************/ void UpdateSpeakTime(); bool CanSpeak() const; void ChangeSpeakTime(int utime); /*********************************************************/ /*** VARIOUS SYSTEMS ***/ /*********************************************************/ bool HasMovementFlag(MovementFlags f) const; // for script access to m_movementInfo.HasMovementFlag void UpdateFallInformationIfNeed(MovementInfo const& minfo, uint16 opcode); void SetFallInformation(uint32 time, float z) { m_lastFallTime = time; m_lastFallZ = z; } void HandleFall(MovementInfo const& movementInfo); void BuildTeleportAckMsg(WorldPacket& data, float x, float y, float z, float ang) const; bool isMoving() const { return m_movementInfo.HasMovementFlag(movementFlagsMask); } bool isMovingOrTurning() const { return m_movementInfo.HasMovementFlag(movementOrTurningFlagsMask); } bool CanSwim() const { return true; } bool CanFly() const { return m_movementInfo.HasMovementFlag(MOVEFLAG_CAN_FLY); } bool IsFlying() const { return m_movementInfo.HasMovementFlag(MOVEFLAG_FLYING); } bool IsFreeFlying() const { return HasAuraType(SPELL_AURA_MOD_FLIGHT_SPEED_MOUNTED) || HasAuraType(SPELL_AURA_FLY); } bool CanStartFlyInArea(uint32 mapid, uint32 zone, uint32 area) const; void SetClientControl(Unit* target, uint8 allowMove); void SetMover(Unit* target) { m_mover = target ? target : this; } Unit* GetMover() const { return m_mover; } bool IsSelfMover() const { return m_mover == this; }// normal case for player not controlling other unit ObjectGuid const& GetFarSightGuid() const { return GetGuidValue(PLAYER_FARSIGHT); } // Transports Transport* GetTransport() const { return m_transport; } void SetTransport(Transport* t) { m_transport = t; } float GetTransOffsetX() const { return m_movementInfo.GetTransportPos()->x; } float GetTransOffsetY() const { return m_movementInfo.GetTransportPos()->y; } float GetTransOffsetZ() const { return m_movementInfo.GetTransportPos()->z; } float GetTransOffsetO() const { return m_movementInfo.GetTransportPos()->o; } uint32 GetTransTime() const { return m_movementInfo.GetTransportTime(); } int8 GetTransSeat() const { return m_movementInfo.GetTransportSeat(); } uint32 GetSaveTimer() const { return m_nextSave; } void SetSaveTimer(uint32 timer) { m_nextSave = timer; } // Recall position uint32 m_recallMap; float m_recallX; float m_recallY; float m_recallZ; float m_recallO; void SaveRecallPosition(); void SetHomebindToLocation(WorldLocation const& loc, uint32 area_id); void RelocateToHomebind() { SetLocationMapId(m_homebindMapId); Relocate(m_homebindX, m_homebindY, m_homebindZ); } bool TeleportToHomebind(uint32 options = 0) { return TeleportTo(m_homebindMapId, m_homebindX, m_homebindY, m_homebindZ, GetOrientation(), options); } Object* GetObjectByTypeMask(ObjectGuid guid, TypeMask typemask); // currently visible objects at player client GuidSet m_clientGUIDs; bool HaveAtClient(WorldObject const* u) { return u == this || m_clientGUIDs.find(u->GetObjectGuid()) != m_clientGUIDs.end(); } bool IsVisibleInGridForPlayer(Player* pl) const override; bool IsVisibleGloballyFor(Player* pl) const; void UpdateVisibilityOf(WorldObject const* viewPoint, WorldObject* target); template<class T> void UpdateVisibilityOf(WorldObject const* viewPoint, T* target, UpdateData& data, std::set<WorldObject*>& visibleNow); // Stealth detection system void HandleStealthedUnitsDetection(); Camera& GetCamera() { return m_camera; } virtual void SetPhaseMask(uint32 newPhaseMask, bool update) override;// overwrite Unit::SetPhaseMask uint8 m_forced_speed_changes[MAX_MOVE_TYPE]; bool HasAtLoginFlag(AtLoginFlags f) const { return m_atLoginFlags & f; } void SetAtLoginFlag(AtLoginFlags f) { m_atLoginFlags |= f; } void RemoveAtLoginFlag(AtLoginFlags f, bool in_db_also = false); // Temporarily removed pet cache uint32 GetTemporaryUnsummonedPetNumber() const { return m_temporaryUnsummonedPetNumber; } void SetTemporaryUnsummonedPetNumber(uint32 petnumber) { m_temporaryUnsummonedPetNumber = petnumber; } void UnsummonPetTemporaryIfAny(); void ResummonPetTemporaryUnSummonedIfAny(); bool IsPetNeedBeTemporaryUnsummoned() const { return !IsInWorld() || !IsAlive() || IsMounted() /*+in flight*/; } void SendCinematicStart(uint32 CinematicSequenceId); void SendMovieStart(uint32 MovieId); /*********************************************************/ /*** INSTANCE SYSTEM ***/ /*********************************************************/ typedef UNORDERED_MAP < uint32 /*mapId*/, InstancePlayerBind > BoundInstancesMap; void UpdateHomebindTime(uint32 time); uint32 m_HomebindTimer; bool m_InstanceValid; // permanent binds and solo binds by difficulty BoundInstancesMap m_boundInstances[MAX_DIFFICULTY]; InstancePlayerBind* GetBoundInstance(uint32 mapid, Difficulty difficulty); BoundInstancesMap& GetBoundInstances(Difficulty difficulty) { return m_boundInstances[difficulty]; } void UnbindInstance(uint32 mapid, Difficulty difficulty, bool unload = false); void UnbindInstance(BoundInstancesMap::iterator& itr, Difficulty difficulty, bool unload = false); InstancePlayerBind* BindToInstance(DungeonPersistentState* save, bool permanent, bool load = false); void SendRaidInfo(); void SendSavedInstances(); static void ConvertInstancesToGroup(Player* player, Group* group = NULL, ObjectGuid player_guid = ObjectGuid()); DungeonPersistentState* GetBoundInstanceSaveForSelfOrGroup(uint32 mapid); AreaLockStatus GetAreaTriggerLockStatus(AreaTrigger const* at, Difficulty difficulty, uint32& miscRequirement); void SendTransferAbortedByLockStatus(MapEntry const* mapEntry, AreaLockStatus lockStatus, uint32 miscRequirement = 0); /*********************************************************/ /*** GROUP SYSTEM ***/ /*********************************************************/ Group* GetGroupInvite() { return m_groupInvite; } void SetGroupInvite(Group* group) { m_groupInvite = group; } Group* GetGroup() { return m_group.getTarget(); } const Group* GetGroup() const { return (const Group*)m_group.getTarget(); } GroupReference& GetGroupRef() { return m_group; } void SetGroup(Group* group, int8 subgroup = -1); uint8 GetSubGroup() const { return m_group.getSubGroup(); } uint32 GetGroupUpdateFlag() const { return m_groupUpdateMask; } void SetGroupUpdateFlag(uint32 flag) { m_groupUpdateMask |= flag; } const uint64& GetAuraUpdateMask() const { return m_auraUpdateMask; } void SetAuraUpdateMask(uint8 slot) { m_auraUpdateMask |= (uint64(1) << slot); } Player* GetNextRandomRaidMember(float radius); PartyResult CanUninviteFromGroup() const; // BattleGround Group System void SetBattleGroundRaid(Group* group, int8 subgroup = -1); void RemoveFromBattleGroundRaid(); Group* GetOriginalGroup() { return m_originalGroup.getTarget(); } GroupReference& GetOriginalGroupRef() { return m_originalGroup; } uint8 GetOriginalSubGroup() const { return m_originalGroup.getSubGroup(); } void SetOriginalGroup(Group* group, int8 subgroup = -1); GridReference<Player>& GetGridRef() { return m_gridRef; } MapReference& GetMapRef() { return m_mapRef; } bool isAllowedToLoot(Creature* creature); DeclinedName const* GetDeclinedNames() const { return m_declinedname; } // Rune functions, need check getClass() == CLASS_DEATH_KNIGHT before access uint8 GetRunesState() const { return m_runes->runeState; } RuneType GetBaseRune(uint8 index) const { return RuneType(m_runes->runes[index].BaseRune); } RuneType GetCurrentRune(uint8 index) const { return RuneType(m_runes->runes[index].CurrentRune); } uint16 GetRuneCooldown(uint8 index) const { return m_runes->runes[index].Cooldown; } bool IsBaseRuneSlotsOnCooldown(RuneType runeType) const; void SetBaseRune(uint8 index, RuneType baseRune) { m_runes->runes[index].BaseRune = baseRune; } void SetCurrentRune(uint8 index, RuneType currentRune) { m_runes->runes[index].CurrentRune = currentRune; } void SetRuneCooldown(uint8 index, uint16 cooldown) { m_runes->runes[index].Cooldown = cooldown; m_runes->SetRuneState(index, (cooldown == 0) ? true : false); } void ConvertRune(uint8 index, RuneType newType); bool ActivateRunes(RuneType type, uint32 count); void ResyncRunes(); void AddRunePower(uint8 index); void InitRunes(); AchievementMgr const& GetAchievementMgr() const { return m_achievementMgr; } AchievementMgr& GetAchievementMgr() { return m_achievementMgr; } void UpdateAchievementCriteria(AchievementCriteriaTypes type, uint32 miscvalue1 = 0, uint32 miscvalue2 = 0, Unit* unit = NULL, uint32 time = 0); void StartTimedAchievementCriteria(AchievementCriteriaTypes type, uint32 timedRequirementId, time_t startTime = 0); bool HasTitle(uint32 bitIndex) const; bool HasTitle(CharTitlesEntry const* title) const { return HasTitle(title->bit_index); } void SetTitle(CharTitlesEntry const* title, bool lost = false); bool canSeeSpellClickOn(Creature const* creature) const; protected: uint32 m_contestedPvPTimer; /*********************************************************/ /*** BATTLEGROUND SYSTEM ***/ /*********************************************************/ /* this is an array of BG queues (BgTypeIDs) in which is player */ struct BgBattleGroundQueueID_Rec { BattleGroundQueueTypeId bgQueueTypeId; uint32 invitedToInstance; }; BgBattleGroundQueueID_Rec m_bgBattleGroundQueueID[PLAYER_MAX_BATTLEGROUND_QUEUES]; BGData m_bgData; bool m_IsBGRandomWinner; /*********************************************************/ /*** QUEST SYSTEM ***/ /*********************************************************/ // We allow only one timed quest active at the same time. Below can then be simple value instead of set. typedef std::set<uint32> QuestSet; QuestSet m_timedquests; QuestSet m_weeklyquests; QuestSet m_monthlyquests; ObjectGuid m_dividerGuid; uint32 m_ingametime; /*********************************************************/ /*** LOAD SYSTEM ***/ /*********************************************************/ void _LoadActions(QueryResult* result); void _LoadAuras(QueryResult* result, uint32 timediff); void _LoadBoundInstances(QueryResult* result); void _LoadInventory(QueryResult* result, uint32 timediff); void _LoadItemLoot(QueryResult* result); void _LoadMails(QueryResult* result); void _LoadMailedItems(QueryResult* result); void _LoadQuestStatus(QueryResult* result); void _LoadDailyQuestStatus(QueryResult* result); void _LoadRandomBGStatus(QueryResult* result); void _LoadWeeklyQuestStatus(QueryResult* result); void _LoadMonthlyQuestStatus(QueryResult* result); void _LoadGroup(QueryResult* result); void _LoadSkills(QueryResult* result); void _LoadSpells(QueryResult* result); void _LoadTalents(QueryResult* result); void _LoadFriendList(QueryResult* result); bool _LoadHomeBind(QueryResult* result); void _LoadDeclinedNames(QueryResult* result); void _LoadArenaTeamInfo(QueryResult* result); void _LoadEquipmentSets(QueryResult* result); void _LoadBGData(QueryResult* result); void _LoadGlyphs(QueryResult* result); void _LoadIntoDataField(const char* data, uint32 startOffset, uint32 count); /*********************************************************/ /*** SAVE SYSTEM ***/ /*********************************************************/ void _SaveActions(); void _SaveAuras(); void _SaveInventory(); void _SaveMail(); void _SaveQuestStatus(); void _SaveDailyQuestStatus(); void _SaveWeeklyQuestStatus(); void _SaveMonthlyQuestStatus(); void _SaveSkills(); void _SaveSpells(); void _SaveEquipmentSets(); void _SaveBGData(); void _SaveGlyphs(); void _SaveTalents(); void _SaveStats(); void _SetCreateBits(UpdateMask* updateMask, Player* target) const override; void _SetUpdateBits(UpdateMask* updateMask, Player* target) const override; /*********************************************************/ /*** ENVIRONMENTAL SYSTEM ***/ /*********************************************************/ void HandleSobering(); void SendMirrorTimer(MirrorTimerType Type, uint32 MaxValue, uint32 CurrentValue, int32 Regen); void StopMirrorTimer(MirrorTimerType Type); void HandleDrowning(uint32 time_diff); int32 getMaxTimer(MirrorTimerType timer); /*********************************************************/ /*** HONOR SYSTEM ***/ /*********************************************************/ time_t m_lastHonorUpdateTime; void outDebugStatsValues() const; ObjectGuid m_lootGuid; Team m_team; uint32 m_nextSave; time_t m_speakTime; uint32 m_speakCount; Difficulty m_dungeonDifficulty; Difficulty m_raidDifficulty; uint32 m_atLoginFlags; Item* m_items[PLAYER_SLOTS_COUNT]; uint32 m_currentBuybackSlot; std::vector<Item*> m_itemUpdateQueue; bool m_itemUpdateQueueBlocked; uint32 m_ExtraFlags; ObjectGuid m_curSelectionGuid; ObjectGuid m_comboTargetGuid; int8 m_comboPoints; QuestStatusMap mQuestStatus; SkillStatusMap mSkillStatus; uint32 m_GuildIdInvited; uint32 m_ArenaTeamIdInvited; PlayerMails m_mail; PlayerSpellMap m_spells; PlayerTalentMap m_talents[MAX_TALENT_SPEC_COUNT]; SpellCooldowns m_spellCooldowns; uint32 m_lastPotionId; // last used health/mana potion in combat, that block next potion use GlobalCooldownMgr m_GlobalCooldownMgr; uint8 m_activeSpec; uint8 m_specsCount; ActionButtonList m_actionButtons[MAX_TALENT_SPEC_COUNT]; Glyph m_glyphs[MAX_TALENT_SPEC_COUNT][MAX_GLYPH_SLOT_INDEX]; float m_auraBaseMod[BASEMOD_END][MOD_END]; int16 m_baseRatingValue[MAX_COMBAT_RATING]; uint16 m_baseSpellPower; uint16 m_baseFeralAP; uint16 m_baseManaRegen; float m_armorPenetrationPct; int32 m_spellPenetrationItemMod; AuraList m_spellMods[MAX_SPELLMOD]; EnchantDurationList m_enchantDuration; ItemDurationList m_itemDuration; ObjectGuid m_resurrectGuid; uint32 m_resurrectMap; float m_resurrectX, m_resurrectY, m_resurrectZ; uint32 m_resurrectHealth, m_resurrectMana; WorldSession* m_session; typedef std::list<Channel*> JoinedChannelsList; JoinedChannelsList m_channels; uint32 m_cinematic; TradeData* m_trade; bool m_DailyQuestChanged; bool m_WeeklyQuestChanged; bool m_MonthlyQuestChanged; uint32 m_drunkTimer; uint32 m_weaponChangeTimer; uint32 m_zoneUpdateId; uint32 m_zoneUpdateTimer; uint32 m_areaUpdateId; uint32 m_positionStatusUpdateTimer; uint32 m_deathTimer; time_t m_deathExpireTime; uint32 m_restTime; uint32 m_WeaponProficiency; uint32 m_ArmorProficiency; bool m_canParry; bool m_canBlock; bool m_canDualWield; bool m_canTitanGrip; uint8 m_swingErrorMsg; float m_ammoDPS; //////////////////// Rest System///////////////////// time_t time_inn_enter; uint32 inn_trigger_id; float m_rest_bonus; RestType rest_type; //////////////////// Rest System///////////////////// // Transports Transport* m_transport; uint32 m_resetTalentsCost; time_t m_resetTalentsTime; uint32 m_usedTalentCount; uint32 m_questRewardTalentCount; // Social PlayerSocial* m_social; // Groups GroupReference m_group; GroupReference m_originalGroup; Group* m_groupInvite; uint32 m_groupUpdateMask; uint64 m_auraUpdateMask; // Player summoning time_t m_summon_expire; uint32 m_summon_mapid; float m_summon_x; float m_summon_y; float m_summon_z; DeclinedName* m_declinedname; Runes* m_runes; EquipmentSets m_EquipmentSets; /// class dependent melee diminishing constant for dodge/parry/missed chances static const float m_diminishing_k[MAX_CLASSES]; private: void _HandleDeadlyPoison(Unit* Target, WeaponAttackType attType, SpellEntry const* spellInfo); // internal common parts for CanStore/StoreItem functions uint32 m_created_date = 0; InventoryResult _CanStoreItem_InSpecificSlot(uint8 bag, uint8 slot, ItemPosCountVec& dest, ItemPrototype const* pProto, uint32& count, bool swap, Item* pSrcItem) const; InventoryResult _CanStoreItem_InBag(uint8 bag, ItemPosCountVec& dest, ItemPrototype const* pProto, uint32& count, bool merge, bool non_specialized, Item* pSrcItem, uint8 skip_bag, uint8 skip_slot) const; InventoryResult _CanStoreItem_InInventorySlots(uint8 slot_begin, uint8 slot_end, ItemPosCountVec& dest, ItemPrototype const* pProto, uint32& count, bool merge, Item* pSrcItem, uint8 skip_bag, uint8 skip_slot) const; Item* _StoreItem(uint16 pos, Item* pItem, uint32 count, bool clone, bool update); void UpdateKnownCurrencies(uint32 itemId, bool apply); void AdjustQuestReqItemCount(Quest const* pQuest, QuestStatusData& questStatusData); void SetCanDelayTeleport(bool setting) { m_bCanDelayTeleport = setting; } bool IsHasDelayedTeleport() const { // we should not execute delayed teleports for now dead players but has been alive at teleport // because we don't want player's ghost teleported from graveyard return m_bHasDelayedTeleport && (IsAlive() || !m_bHasBeenAliveAtDelayedTeleport); } bool SetDelayedTeleportFlagIfCan() { m_bHasDelayedTeleport = m_bCanDelayTeleport; m_bHasBeenAliveAtDelayedTeleport = IsAlive(); return m_bHasDelayedTeleport; } void ScheduleDelayedOperation(uint32 operation) { if (operation < DELAYED_END) { m_DelayedOperations |= operation; } } void _fillGearScoreData(Item* item, GearScoreVec* gearScore, uint32& twoHandScore); Unit* m_mover; Camera m_camera; GridReference<Player> m_gridRef; MapReference m_mapRef; // Homebind coordinates uint32 m_homebindMapId; uint16 m_homebindAreaId; float m_homebindX; float m_homebindY; float m_homebindZ; uint32 m_lastFallTime; float m_lastFallZ; LiquidTypeEntry const* m_lastLiquid; int32 m_MirrorTimer[MAX_TIMERS]; uint8 m_MirrorTimerFlags; uint8 m_MirrorTimerFlagsLast; bool m_isInWater; // Current teleport data WorldLocation m_teleport_dest; uint32 m_teleport_options; bool mSemaphoreTeleport_Near; bool mSemaphoreTeleport_Far; uint32 m_DelayedOperations; bool m_bCanDelayTeleport; bool m_bHasDelayedTeleport; bool m_bHasBeenAliveAtDelayedTeleport; uint32 m_DetectInvTimer; // Temporary removed pet cache uint32 m_temporaryUnsummonedPetNumber; AchievementMgr m_achievementMgr; ReputationMgr m_reputationMgr; uint32 m_timeSyncCounter; uint32 m_timeSyncTimer; uint32 m_timeSyncClient; uint32 m_timeSyncServer; uint32 m_cachedGS; }; void AddItemsSetItem(Player* player, Item* item); void RemoveItemsSetItem(Player* player, ItemPrototype const* proto); #endif
mangostwo/server
src/game/Object/Player.h
C
gpl-2.0
121,126
// Emacs style mode select -*- C++ -*- //----------------------------------------------------------------------------- // // $Id$ // // Copyright (C) 1993-1996 by id Software, Inc. // Copyright (C) 2006-2015 by The Odamex Team. // // 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. // // DESCRIPTION: // System specific network interface stuff. // //----------------------------------------------------------------------------- #ifndef __I_NET_H__ #define __I_NET_H__ #include "doomtype.h" #include "huffman.h" #include <string> // Max packet size to send and receive, in bytes #define MAX_UDP_PACKET 8192 #define SERVERPORT 10666 #define CLIENTPORT 10667 #define PLAYER_FULLBRIGHTFRAME 70 #define CHALLENGE 5560020 // challenge #define LAUNCHER_CHALLENGE 777123 // csdl challenge #define VERSION 65 // GhostlyDeath -- this should remain static from now on extern int localport; extern int msg_badread; // network message info struct msg_info_t { int id; const char *msgName; const char *msgFormat; // 'b'=byte, 'n'=short, 'N'=long, 's'=string const char *getName() { return msgName ? msgName : ""; } }; // network messages enum svc_t { svc_abort, svc_full, svc_disconnect, svc_reserved3, svc_playerinfo, // weapons, ammo, maxammo, raisedweapon for local player svc_moveplayer, // [byte] [int] [int] [int] [int] [byte] svc_updatelocalplayer, // [int] [int] [int] [int] [int] svc_updatesecrets, // [byte] - secrets discovered to a client svc_pingrequest, // [SL] 2011-05-11 [long:timestamp] svc_updateping, // [byte] [byte] svc_spawnmobj, // svc_disconnectclient, svc_loadmap, svc_consoleplayer, svc_mobjspeedangle, svc_explodemissile, // [short] - netid svc_removemobj, svc_userinfo, svc_movemobj, // [short] [byte] [int] [int] [int] svc_spawnplayer, svc_damageplayer, svc_killmobj, svc_firepistol, // [byte] - playernum svc_fireshotgun, // [byte] - playernum svc_firessg, // [byte] - playernum svc_firechaingun, // [byte] - playernum svc_fireweapon, // [byte] svc_sector, svc_print, svc_mobjinfo, svc_updatefrags, // [byte] [short] svc_teampoints, svc_activateline, svc_movingsector, svc_startsound, svc_reconnect, svc_exitlevel, svc_touchspecial, svc_changeweapon, svc_reserved42, svc_corpse, svc_missedpacket, svc_soundorigin, svc_reserved46, svc_reserved47, svc_forceteam, // [Toke] Allows server to change a clients team setting. svc_switch, svc_say, // [AM] Similar to a broadcast print except we know who said it. svc_reserved51, svc_spawnhiddenplayer, // [denis] when client can't see player svc_updatedeaths, // [byte] [short] svc_ctfevent, // [Toke - CTF] - [int] svc_serversettings, // 55 [Toke] - informs clients of server settings svc_spectate, // [Nes] - [byte:state], [short:playernum] svc_connectclient, svc_midprint, svc_svgametic, // [SL] 2011-05-11 - [byte] svc_timeleft, svc_inttimeleft, // [ML] For intermission timer svc_mobjtranslation, // [SL] 2011-09-11 - [byte] svc_fullupdatedone, // [SL] Inform client the full update is over svc_railtrail, // [SL] Draw railgun trail and play sound svc_readystate, // [AM] Broadcast ready state to client svc_playerstate, // [SL] Health, armor, and weapon of a player svc_playercheatstate, // Ch0wW : Give the player cheat status svc_warmupstate, // [AM] Broadcast warmup state to client svc_resetmap, // [AM] Server is resetting the map // for co-op svc_mobjstate = 70, svc_actor_movedir, svc_actor_target, svc_actor_tracer, svc_damagemobj, // for downloading svc_wadinfo, // denis - [ulong:filesize] svc_wadchunk, // denis - [ulong:offset], [ushort:len], [byte[]:data] // netdemos - NullPoint svc_netdemocap = 100, svc_netdemostop = 101, svc_netdemoloadsnap = 102, svc_vote_update = 150, // [AM] - Send the latest voting state to the client. svc_maplist = 155, // [AM] - Return a maplist status. svc_maplist_update = 156, // [AM] - Send the entire maplist to the client in chunks. svc_maplist_index = 157, // [AM] - Send the current and next map index to the client. // for compressed packets svc_compressed = 200, // for when launcher packets go astray svc_launcher_challenge = 212, svc_challenge = 163, svc_max = 255 }; // network messages enum clc_t { clc_abort, clc_reserved1, clc_disconnect, clc_say, clc_move, // send cmds clc_userinfo, // send userinfo clc_pingreply, // [SL] 2011-05-11 - [long: timestamp] clc_rate, clc_ack, clc_rcon, clc_rcon_password, clc_changeteam, // [NightFang] - Change your team [Toke - Teams] Made this actualy work clc_ctfcommand, clc_spectate, // denis - [byte:state] clc_wantwad, // denis - string:name, string:hash clc_kill, // denis - suicide clc_cheat, // denis - god, pumpkins, etc clc_cheatgive, // Ch0wW - "give" cheat clc_callvote, // [AM] - Calling a vote clc_vote, // [AM] - Casting a vote clc_maplist, // [AM] - Maplist status request. clc_maplist_update, // [AM] - Request the entire maplist from the server. clc_getplayerinfo, clc_ready, // [AM] Toggle ready state. clc_spy, // [SL] Tell server to send info about this player clc_privmsg, // [AM] Targeted chat to a specific player. // for when launcher packets go astray clc_launcher_challenge = 212, clc_challenge = 163, clc_max = 255 }; extern msg_info_t clc_info[clc_max]; extern msg_info_t svc_info[svc_max]; enum svc_compressed_masks { adaptive_mask = 1, adaptive_select_mask = 2, adaptive_record_mask = 4, minilzo_mask = 8 }; typedef struct { byte ip[4]; unsigned short port; unsigned short pad; } netadr_t; extern netadr_t net_from; // address of who sent the packet class buf_t { public: byte *data; size_t allocsize, cursize, readpos; bool overflowed; // set to true if the buffer size failed // Buffer seeking flags typedef enum { BT_SSET // From beginning ,BT_SCUR // From current position ,BT_SEND // From end } seek_loc_t; public: void WriteByte(byte b) { byte *buf = SZ_GetSpace(sizeof(b)); if(!overflowed) { *buf = b; } } void WriteShort(short s) { byte *buf = SZ_GetSpace(sizeof(s)); if(!overflowed) { buf[0] = s&0xff; buf[1] = s>>8; } } void WriteLong(int l) { byte *buf = SZ_GetSpace(sizeof(l)); if(!overflowed) { buf[0] = l&0xff; buf[1] = (l>>8)&0xff; buf[2] = (l>>16)&0xff; buf[3] = l>>24; } } void WriteString(const char *c) { if(c && *c) { size_t l = strlen(c); byte *buf = SZ_GetSpace(l + 1); if(!overflowed) { memcpy(buf, c, l + 1); } } else WriteByte(0); } void WriteChunk(const char *c, unsigned l, int startpos = 0) { byte *buf = SZ_GetSpace(l); if(!overflowed) { memcpy(buf, c + startpos, l); } } int ReadByte() { if(readpos+1 > cursize) { overflowed = true; return -1; } return (unsigned char)data[readpos++]; } int NextByte() { if(readpos+1 > cursize) { overflowed = true; return -1; } return (unsigned char)data[readpos]; } byte *ReadChunk(size_t size) { if(readpos+size > cursize) { overflowed = true; return NULL; } size_t oldpos = readpos; readpos += size; return data+oldpos; } int ReadShort() { if(readpos+2 > cursize) { overflowed = true; return -1; } size_t oldpos = readpos; readpos += 2; return (short)(data[oldpos] + (data[oldpos+1]<<8)); } int ReadLong() { if(readpos+4 > cursize) { overflowed = true; return -1; } size_t oldpos = readpos; readpos += 4; return data[oldpos] + (data[oldpos+1]<<8) + (data[oldpos+2]<<16)+ (data[oldpos+3]<<24); } const char *ReadString() { byte *begin = data + readpos; while(ReadByte() > 0); if(overflowed) { return ""; } return (const char *)begin; } size_t SetOffset (const size_t &offset, const seek_loc_t &loc) { switch (loc) { case BT_SSET: { if (offset > cursize) { overflowed = true; return 0; } readpos = offset; } break; case BT_SCUR: { if (readpos+offset > cursize) { overflowed = true; return 0; } readpos += offset; } case BT_SEND: { if ((int)(readpos-offset) < 0) { // lies, an underflow occured overflowed = true; return 0; } readpos -= offset; } } return readpos; } size_t BytesLeftToRead() const { return overflowed || cursize < readpos ? 0 : cursize - readpos; } size_t BytesRead() const { return readpos; } byte *ptr() { return data; } size_t size() const { return cursize; } size_t maxsize() const { return allocsize; } void setcursize(size_t len) { cursize = len > allocsize ? allocsize : len; } void clear() { cursize = 0; readpos = 0; overflowed = false; } void resize(size_t len, bool clearbuf = true) { byte *olddata = data; data = new byte[len]; allocsize = len; if (!clearbuf) { if (cursize < allocsize) { memcpy(data, olddata, cursize); } else { clear(); overflowed = true; Printf (PRINT_HIGH, "buf_t::resize(): overflow\n"); } } else { clear(); } delete[] olddata; } byte *SZ_GetSpace(size_t length) { if (cursize + length >= allocsize) { clear(); overflowed = true; Printf (PRINT_HIGH, "SZ_GetSpace: overflow\n"); } byte *ret = data + cursize; cursize += length; return ret; } buf_t &operator =(const buf_t &other) { // Avoid self-assignment if (this == &other) return *this; delete[] data; data = new byte[other.allocsize]; allocsize = other.allocsize; cursize = other.cursize; overflowed = other.overflowed; readpos = other.readpos; if(!overflowed) for(size_t i = 0; i < cursize; i++) data[i] = other.data[i]; return *this; } buf_t() : data(0), allocsize(0), cursize(0), readpos(0), overflowed(false) { } buf_t(size_t len) : data(new byte[len]), allocsize(len), cursize(0), readpos(0), overflowed(false) { } buf_t(const buf_t &other) : data(new byte[other.allocsize]), allocsize(other.allocsize), cursize(other.cursize), readpos(other.readpos), overflowed(other.overflowed) { if(!overflowed) for(size_t i = 0; i < cursize; i++) data[i] = other.data[i]; } ~buf_t() { delete[] data; data = NULL; } }; extern buf_t net_message; void CloseNetwork (void); void InitNetCommon(void); void I_SetPort(netadr_t &addr, int port); bool NetWaitOrTimeout(size_t ms); char *NET_AdrToString (netadr_t a); bool NET_StringToAdr (const char *s, netadr_t *a); bool NET_CompareAdr (netadr_t a, netadr_t b); int NET_GetPacket (void); int NET_SendPacket (buf_t &buf, netadr_t &to); std::string NET_GetLocalAddress (void); void SZ_Clear (buf_t *buf); void SZ_Write (buf_t *b, const void *data, int length); void SZ_Write (buf_t *b, const byte *data, int startpos, int length); void MSG_WriteByte (buf_t *b, byte c); void MSG_WriteMarker (buf_t *b, svc_t c); void MSG_WriteMarker (buf_t *b, clc_t c); void MSG_WriteShort (buf_t *b, short c); void MSG_WriteLong (buf_t *b, int c); void MSG_WriteBool(buf_t *b, bool); void MSG_WriteFloat(buf_t *b, float); void MSG_WriteString (buf_t *b, const char *s); void MSG_WriteHexString(buf_t *b, const char *s); void MSG_WriteChunk (buf_t *b, const void *p, unsigned l); int MSG_BytesLeft(void); int MSG_NextByte (void); int MSG_ReadByte (void); void *MSG_ReadChunk (const size_t &size); int MSG_ReadShort (void); int MSG_ReadLong (void); bool MSG_ReadBool(void); float MSG_ReadFloat(void); const char *MSG_ReadString (void); size_t MSG_SetOffset (const size_t &offset, const buf_t::seek_loc_t &loc); bool MSG_DecompressMinilzo (); bool MSG_CompressMinilzo (buf_t &buf, size_t start_offset, size_t write_gap); bool MSG_DecompressAdaptive (huffman &huff); bool MSG_CompressAdaptive (huffman &huff, buf_t &buf, size_t start_offset, size_t write_gap); #endif
Ch0wW/odamex
common/i_net.h
C
gpl-2.0
12,818
using System.Collections.Generic; using System.Threading.Tasks; using AutoMapper; using ComboSurf.Domain.Repositories; using MongoDB.Bson; using MongoDB.Bson.Serialization; using MongoDB.Driver; using DataTransferObjects; namespace ComboSurf.Infrastructure { public class SpotRepository : ISpotRepository { public List<string> GetAll() { //hard code this for now because we are only doing 3 spots //later we will extend to actually query database here var spots = new List<string> {"Sydney North", "Sydney East", "Sydney South"}; return spots; } public SpotDto GetByName(string name) { var document = Task.Run(() => QueryDatabaseByName(name)).Result; var jsonDocument = BsonSerializer.Deserialize<SpotDto>(document); var spot = Mapper.Map<SpotDto>(jsonDocument); if (spot.reports.Count < 1) { var oldResults = Task.Run(() => GetLatestReport()).Result; var json = BsonSerializer.Deserialize<SpotDto>(oldResults); var oldSpot = Mapper.Map<SpotDto>(json); return oldSpot; } return spot; } public async Task<BsonDocument> QueryDatabaseByName(string name) { var client = new MongoClient(); var database = client.GetDatabase("partywave"); var collection = database.GetCollection<BsonDocument>("scrapeResults"); var query = Builders<BsonDocument>.Filter.Eq("name", name); var sortFilter = Builders<BsonDocument>.Sort.Descending("_id"); var document = await collection.Find(query).Sort(sortFilter).FirstOrDefaultAsync(); return document; } public async Task<BsonDocument> GetLatestReport() { var client = new MongoClient(); var database = client.GetDatabase("partywave"); var collection = database.GetCollection<BsonDocument>("scrapeResults"); FilterDefinition<BsonDocument> query = ("{'reports.1': {$exists: true}}.limit(1).sort({$natural:-1})"); var document = await collection.Find(query).FirstOrDefaultAsync(); return document; } } }
thomasdane/combosurf
ComboSurf.Infrastructure/SpotRepository.cs
C#
gpl-2.0
1,960