repo_name
string
path
string
copies
string
size
string
content
string
license
string
lategoodbye/linux-lcd6610
sound/soc/samsung/tobermory.c
766
5570
/* * Tobermory audio support * * Copyright 2011 Wolfson Microelectronics * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. */ #include <sound/soc.h> #include <sound/soc-dapm.h> #include <sound/jack.h> #include <linux/gpio.h> #include <linux/module.h> #include "../codecs/wm8962.h" static int sample_rate = 44100; static int tobermory_set_bias_level(struct snd_soc_card *card, struct snd_soc_dapm_context *dapm, enum snd_soc_bias_level level) { struct snd_soc_dai *codec_dai = card->rtd[0].codec_dai; int ret; if (dapm->dev != codec_dai->dev) return 0; switch (level) { case SND_SOC_BIAS_PREPARE: if (dapm->bias_level == SND_SOC_BIAS_STANDBY) { ret = snd_soc_dai_set_pll(codec_dai, WM8962_FLL, WM8962_FLL_MCLK, 32768, sample_rate * 512); if (ret < 0) pr_err("Failed to start FLL: %d\n", ret); ret = snd_soc_dai_set_sysclk(codec_dai, WM8962_SYSCLK_FLL, sample_rate * 512, SND_SOC_CLOCK_IN); if (ret < 0) { pr_err("Failed to set SYSCLK: %d\n", ret); snd_soc_dai_set_pll(codec_dai, WM8962_FLL, 0, 0, 0); return ret; } } break; default: break; } return 0; } static int tobermory_set_bias_level_post(struct snd_soc_card *card, struct snd_soc_dapm_context *dapm, enum snd_soc_bias_level level) { struct snd_soc_dai *codec_dai = card->rtd[0].codec_dai; int ret; if (dapm->dev != codec_dai->dev) return 0; switch (level) { case SND_SOC_BIAS_STANDBY: ret = snd_soc_dai_set_sysclk(codec_dai, WM8962_SYSCLK_MCLK, 32768, SND_SOC_CLOCK_IN); if (ret < 0) { pr_err("Failed to switch away from FLL: %d\n", ret); return ret; } ret = snd_soc_dai_set_pll(codec_dai, WM8962_FLL, 0, 0, 0); if (ret < 0) { pr_err("Failed to stop FLL: %d\n", ret); return ret; } break; default: break; } dapm->bias_level = level; return 0; } static int tobermory_hw_params(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *params) { sample_rate = params_rate(params); return 0; } static struct snd_soc_ops tobermory_ops = { .hw_params = tobermory_hw_params, }; static struct snd_soc_dai_link tobermory_dai[] = { { .name = "CPU", .stream_name = "CPU", .cpu_dai_name = "samsung-i2s.0", .codec_dai_name = "wm8962", .platform_name = "samsung-i2s.0", .codec_name = "wm8962.1-001a", .dai_fmt = SND_SOC_DAIFMT_I2S | SND_SOC_DAIFMT_NB_NF | SND_SOC_DAIFMT_CBM_CFM, .ops = &tobermory_ops, }, }; static const struct snd_kcontrol_new controls[] = { SOC_DAPM_PIN_SWITCH("Main Speaker"), SOC_DAPM_PIN_SWITCH("DMIC"), }; static struct snd_soc_dapm_widget widgets[] = { SND_SOC_DAPM_HP("Headphone", NULL), SND_SOC_DAPM_MIC("Headset Mic", NULL), SND_SOC_DAPM_MIC("DMIC", NULL), SND_SOC_DAPM_MIC("AMIC", NULL), SND_SOC_DAPM_SPK("Main Speaker", NULL), }; static struct snd_soc_dapm_route audio_paths[] = { { "Headphone", NULL, "HPOUTL" }, { "Headphone", NULL, "HPOUTR" }, { "Main Speaker", NULL, "SPKOUTL" }, { "Main Speaker", NULL, "SPKOUTR" }, { "Headset Mic", NULL, "MICBIAS" }, { "IN4L", NULL, "Headset Mic" }, { "IN4R", NULL, "Headset Mic" }, { "AMIC", NULL, "MICBIAS" }, { "IN1L", NULL, "AMIC" }, { "IN1R", NULL, "AMIC" }, { "DMIC", NULL, "MICBIAS" }, { "DMICDAT", NULL, "DMIC" }, }; static struct snd_soc_jack tobermory_headset; /* Headset jack detection DAPM pins */ static struct snd_soc_jack_pin tobermory_headset_pins[] = { { .pin = "Headset Mic", .mask = SND_JACK_MICROPHONE, }, { .pin = "Headphone", .mask = SND_JACK_MICROPHONE, }, }; static int tobermory_late_probe(struct snd_soc_card *card) { struct snd_soc_codec *codec = card->rtd[0].codec; struct snd_soc_dai *codec_dai = card->rtd[0].codec_dai; int ret; ret = snd_soc_dai_set_sysclk(codec_dai, WM8962_SYSCLK_MCLK, 32768, SND_SOC_CLOCK_IN); if (ret < 0) return ret; ret = snd_soc_card_jack_new(card, "Headset", SND_JACK_HEADSET | SND_JACK_BTN_0, &tobermory_headset, tobermory_headset_pins, ARRAY_SIZE(tobermory_headset_pins)); if (ret) return ret; wm8962_mic_detect(codec, &tobermory_headset); return 0; } static struct snd_soc_card tobermory = { .name = "Tobermory", .owner = THIS_MODULE, .dai_link = tobermory_dai, .num_links = ARRAY_SIZE(tobermory_dai), .set_bias_level = tobermory_set_bias_level, .set_bias_level_post = tobermory_set_bias_level_post, .controls = controls, .num_controls = ARRAY_SIZE(controls), .dapm_widgets = widgets, .num_dapm_widgets = ARRAY_SIZE(widgets), .dapm_routes = audio_paths, .num_dapm_routes = ARRAY_SIZE(audio_paths), .fully_routed = true, .late_probe = tobermory_late_probe, }; static int tobermory_probe(struct platform_device *pdev) { struct snd_soc_card *card = &tobermory; int ret; card->dev = &pdev->dev; ret = devm_snd_soc_register_card(&pdev->dev, card); if (ret) dev_err(&pdev->dev, "snd_soc_register_card() failed: %d\n", ret); return ret; } static struct platform_driver tobermory_driver = { .driver = { .name = "tobermory", .pm = &snd_soc_pm_ops, }, .probe = tobermory_probe, }; module_platform_driver(tobermory_driver); MODULE_DESCRIPTION("Tobermory audio support"); MODULE_AUTHOR("Mark Brown <broonie@opensource.wolfsonmicro.com>"); MODULE_LICENSE("GPL"); MODULE_ALIAS("platform:tobermory");
gpl-2.0
lategoodbye/linux-lcd6610
fs/nfs/getroot.c
1022
3553
/* getroot.c: get the root dentry for an NFS mount * * Copyright (C) 2006 Red Hat, Inc. All Rights Reserved. * Written by David Howells (dhowells@redhat.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. */ #include <linux/module.h> #include <linux/init.h> #include <linux/time.h> #include <linux/kernel.h> #include <linux/mm.h> #include <linux/string.h> #include <linux/stat.h> #include <linux/errno.h> #include <linux/unistd.h> #include <linux/sunrpc/clnt.h> #include <linux/sunrpc/stats.h> #include <linux/nfs_fs.h> #include <linux/nfs_mount.h> #include <linux/lockd/bind.h> #include <linux/seq_file.h> #include <linux/mount.h> #include <linux/vfs.h> #include <linux/namei.h> #include <linux/security.h> #include <asm/uaccess.h> #include "internal.h" #define NFSDBG_FACILITY NFSDBG_CLIENT /* * Set the superblock root dentry. * Note that this function frees the inode in case of error. */ static int nfs_superblock_set_dummy_root(struct super_block *sb, struct inode *inode) { /* The mntroot acts as the dummy root dentry for this superblock */ if (sb->s_root == NULL) { sb->s_root = d_make_root(inode); if (sb->s_root == NULL) return -ENOMEM; ihold(inode); /* * Ensure that this dentry is invisible to d_find_alias(). * Otherwise, it may be spliced into the tree by * d_splice_alias if a parent directory from the same * filesystem gets mounted at a later time. * This again causes shrink_dcache_for_umount_subtree() to * Oops, since the test for IS_ROOT() will fail. */ spin_lock(&d_inode(sb->s_root)->i_lock); spin_lock(&sb->s_root->d_lock); hlist_del_init(&sb->s_root->d_u.d_alias); spin_unlock(&sb->s_root->d_lock); spin_unlock(&d_inode(sb->s_root)->i_lock); } return 0; } /* * get an NFS2/NFS3 root dentry from the root filehandle */ struct dentry *nfs_get_root(struct super_block *sb, struct nfs_fh *mntfh, const char *devname) { struct nfs_server *server = NFS_SB(sb); struct nfs_fsinfo fsinfo; struct dentry *ret; struct inode *inode; void *name = kstrdup(devname, GFP_KERNEL); int error; if (!name) return ERR_PTR(-ENOMEM); /* get the actual root for this mount */ fsinfo.fattr = nfs_alloc_fattr(); if (fsinfo.fattr == NULL) { kfree(name); return ERR_PTR(-ENOMEM); } error = server->nfs_client->rpc_ops->getroot(server, mntfh, &fsinfo); if (error < 0) { dprintk("nfs_get_root: getattr error = %d\n", -error); ret = ERR_PTR(error); goto out; } inode = nfs_fhget(sb, mntfh, fsinfo.fattr, NULL); if (IS_ERR(inode)) { dprintk("nfs_get_root: get root inode failed\n"); ret = ERR_CAST(inode); goto out; } error = nfs_superblock_set_dummy_root(sb, inode); if (error != 0) { ret = ERR_PTR(error); goto out; } /* root dentries normally start off anonymous and get spliced in later * if the dentry tree reaches them; however if the dentry already * exists, we'll pick it up at this point and use it as the root */ ret = d_obtain_root(inode); if (IS_ERR(ret)) { dprintk("nfs_get_root: get root dentry failed\n"); goto out; } security_d_instantiate(ret, inode); spin_lock(&ret->d_lock); if (IS_ROOT(ret) && !ret->d_fsdata && !(ret->d_flags & DCACHE_NFSFS_RENAMED)) { ret->d_fsdata = name; name = NULL; } spin_unlock(&ret->d_lock); out: kfree(name); nfs_free_fattr(fsinfo.fattr); return ret; }
gpl-2.0
rettigs/linux-yocto-3.14
lib/div64.c
1278
4073
/* * Copyright (C) 2003 Bernardo Innocenti <bernie@develer.com> * * Based on former do_div() implementation from asm-parisc/div64.h: * Copyright (C) 1999 Hewlett-Packard Co * Copyright (C) 1999 David Mosberger-Tang <davidm@hpl.hp.com> * * * Generic C version of 64bit/32bit division and modulo, with * 64bit result and 32bit remainder. * * The fast case for (n>>32 == 0) is handled inline by do_div(). * * Code generated for this function might be very inefficient * for some CPUs. __div64_32() can be overridden by linking arch-specific * assembly versions such as arch/ppc/lib/div64.S and arch/sh/lib/div64.S. */ #include <linux/export.h> #include <linux/kernel.h> #include <linux/math64.h> /* Not needed on 64bit architectures */ #if BITS_PER_LONG == 32 uint32_t __attribute__((weak)) __div64_32(uint64_t *n, uint32_t base) { uint64_t rem = *n; uint64_t b = base; uint64_t res, d = 1; uint32_t high = rem >> 32; /* Reduce the thing a bit first */ res = 0; if (high >= base) { high /= base; res = (uint64_t) high << 32; rem -= (uint64_t) (high*base) << 32; } while ((int64_t)b > 0 && b < rem) { b = b+b; d = d+d; } do { if (rem >= b) { rem -= b; res += d; } b >>= 1; d >>= 1; } while (d); *n = res; return rem; } EXPORT_SYMBOL(__div64_32); #ifndef div_s64_rem s64 div_s64_rem(s64 dividend, s32 divisor, s32 *remainder) { u64 quotient; if (dividend < 0) { quotient = div_u64_rem(-dividend, abs(divisor), (u32 *)remainder); *remainder = -*remainder; if (divisor > 0) quotient = -quotient; } else { quotient = div_u64_rem(dividend, abs(divisor), (u32 *)remainder); if (divisor < 0) quotient = -quotient; } return quotient; } EXPORT_SYMBOL(div_s64_rem); #endif /** * div64_u64_rem - unsigned 64bit divide with 64bit divisor and remainder * @dividend: 64bit dividend * @divisor: 64bit divisor * @remainder: 64bit remainder * * This implementation is a comparable to algorithm used by div64_u64. * But this operation, which includes math for calculating the remainder, * is kept distinct to avoid slowing down the div64_u64 operation on 32bit * systems. */ #ifndef div64_u64_rem u64 div64_u64_rem(u64 dividend, u64 divisor, u64 *remainder) { u32 high = divisor >> 32; u64 quot; if (high == 0) { u32 rem32; quot = div_u64_rem(dividend, divisor, &rem32); *remainder = rem32; } else { int n = 1 + fls(high); quot = div_u64(dividend >> n, divisor >> n); if (quot != 0) quot--; *remainder = dividend - quot * divisor; if (*remainder >= divisor) { quot++; *remainder -= divisor; } } return quot; } EXPORT_SYMBOL(div64_u64_rem); #endif /** * div64_u64 - unsigned 64bit divide with 64bit divisor * @dividend: 64bit dividend * @divisor: 64bit divisor * * This implementation is a modified version of the algorithm proposed * by the book 'Hacker's Delight'. The original source and full proof * can be found here and is available for use without restriction. * * 'http://www.hackersdelight.org/HDcode/newCode/divDouble.c.txt' */ #ifndef div64_u64 u64 div64_u64(u64 dividend, u64 divisor) { u32 high = divisor >> 32; u64 quot; if (high == 0) { quot = div_u64(dividend, divisor); } else { int n = 1 + fls(high); quot = div_u64(dividend >> n, divisor >> n); if (quot != 0) quot--; if ((dividend - quot * divisor) >= divisor) quot++; } return quot; } EXPORT_SYMBOL(div64_u64); #endif /** * div64_s64 - signed 64bit divide with 64bit divisor * @dividend: 64bit dividend * @divisor: 64bit divisor */ #ifndef div64_s64 s64 div64_s64(s64 dividend, s64 divisor) { s64 quot, t; quot = div64_u64(abs64(dividend), abs64(divisor)); t = (dividend ^ divisor) >> 63; return (quot ^ t) - t; } EXPORT_SYMBOL(div64_s64); #endif #endif /* BITS_PER_LONG == 32 */ /* * Iterative div/mod for use when dividend is not expected to be much * bigger than divisor. */ u32 iter_div_u64_rem(u64 dividend, u32 divisor, u64 *remainder) { return __iter_div_u64_rem(dividend, divisor, remainder); } EXPORT_SYMBOL(iter_div_u64_rem);
gpl-2.0
caplio/android_kernel_samsung_hltedcm
net/mac80211/util.c
1534
44808
/* * Copyright 2002-2005, Instant802 Networks, Inc. * Copyright 2005-2006, Devicescape Software, Inc. * Copyright 2006-2007 Jiri Benc <jbenc@suse.cz> * Copyright 2007 Johannes Berg <johannes@sipsolutions.net> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * utilities for mac80211 */ #include <net/mac80211.h> #include <linux/netdevice.h> #include <linux/export.h> #include <linux/types.h> #include <linux/slab.h> #include <linux/skbuff.h> #include <linux/etherdevice.h> #include <linux/if_arp.h> #include <linux/bitmap.h> #include <linux/crc32.h> #include <net/net_namespace.h> #include <net/cfg80211.h> #include <net/rtnetlink.h> #include "ieee80211_i.h" #include "driver-ops.h" #include "rate.h" #include "mesh.h" #include "wme.h" #include "led.h" #include "wep.h" /* privid for wiphys to determine whether they belong to us or not */ void *mac80211_wiphy_privid = &mac80211_wiphy_privid; struct ieee80211_hw *wiphy_to_ieee80211_hw(struct wiphy *wiphy) { struct ieee80211_local *local; BUG_ON(!wiphy); local = wiphy_priv(wiphy); return &local->hw; } EXPORT_SYMBOL(wiphy_to_ieee80211_hw); u8 *ieee80211_get_bssid(struct ieee80211_hdr *hdr, size_t len, enum nl80211_iftype type) { __le16 fc = hdr->frame_control; /* drop ACK/CTS frames and incorrect hdr len (ctrl) */ if (len < 16) return NULL; if (ieee80211_is_data(fc)) { if (len < 24) /* drop incorrect hdr len (data) */ return NULL; if (ieee80211_has_a4(fc)) return NULL; if (ieee80211_has_tods(fc)) return hdr->addr1; if (ieee80211_has_fromds(fc)) return hdr->addr2; return hdr->addr3; } if (ieee80211_is_mgmt(fc)) { if (len < 24) /* drop incorrect hdr len (mgmt) */ return NULL; return hdr->addr3; } if (ieee80211_is_ctl(fc)) { if(ieee80211_is_pspoll(fc)) return hdr->addr1; if (ieee80211_is_back_req(fc)) { switch (type) { case NL80211_IFTYPE_STATION: return hdr->addr2; case NL80211_IFTYPE_AP: case NL80211_IFTYPE_AP_VLAN: return hdr->addr1; default: break; /* fall through to the return */ } } } return NULL; } void ieee80211_tx_set_protected(struct ieee80211_tx_data *tx) { struct sk_buff *skb; struct ieee80211_hdr *hdr; skb_queue_walk(&tx->skbs, skb) { hdr = (struct ieee80211_hdr *) skb->data; hdr->frame_control |= cpu_to_le16(IEEE80211_FCTL_PROTECTED); } } int ieee80211_frame_duration(struct ieee80211_local *local, size_t len, int rate, int erp, int short_preamble) { int dur; /* calculate duration (in microseconds, rounded up to next higher * integer if it includes a fractional microsecond) to send frame of * len bytes (does not include FCS) at the given rate. Duration will * also include SIFS. * * rate is in 100 kbps, so divident is multiplied by 10 in the * DIV_ROUND_UP() operations. */ if (local->hw.conf.channel->band == IEEE80211_BAND_5GHZ || erp) { /* * OFDM: * * N_DBPS = DATARATE x 4 * N_SYM = Ceiling((16+8xLENGTH+6) / N_DBPS) * (16 = SIGNAL time, 6 = tail bits) * TXTIME = T_PREAMBLE + T_SIGNAL + T_SYM x N_SYM + Signal Ext * * T_SYM = 4 usec * 802.11a - 17.5.2: aSIFSTime = 16 usec * 802.11g - 19.8.4: aSIFSTime = 10 usec + * signal ext = 6 usec */ dur = 16; /* SIFS + signal ext */ dur += 16; /* 17.3.2.3: T_PREAMBLE = 16 usec */ dur += 4; /* 17.3.2.3: T_SIGNAL = 4 usec */ dur += 4 * DIV_ROUND_UP((16 + 8 * (len + 4) + 6) * 10, 4 * rate); /* T_SYM x N_SYM */ } else { /* * 802.11b or 802.11g with 802.11b compatibility: * 18.3.4: TXTIME = PreambleLength + PLCPHeaderTime + * Ceiling(((LENGTH+PBCC)x8)/DATARATE). PBCC=0. * * 802.11 (DS): 15.3.3, 802.11b: 18.3.4 * aSIFSTime = 10 usec * aPreambleLength = 144 usec or 72 usec with short preamble * aPLCPHeaderLength = 48 usec or 24 usec with short preamble */ dur = 10; /* aSIFSTime = 10 usec */ dur += short_preamble ? (72 + 24) : (144 + 48); dur += DIV_ROUND_UP(8 * (len + 4) * 10, rate); } return dur; } /* Exported duration function for driver use */ __le16 ieee80211_generic_frame_duration(struct ieee80211_hw *hw, struct ieee80211_vif *vif, size_t frame_len, struct ieee80211_rate *rate) { struct ieee80211_local *local = hw_to_local(hw); struct ieee80211_sub_if_data *sdata; u16 dur; int erp; bool short_preamble = false; erp = 0; if (vif) { sdata = vif_to_sdata(vif); short_preamble = sdata->vif.bss_conf.use_short_preamble; if (sdata->flags & IEEE80211_SDATA_OPERATING_GMODE) erp = rate->flags & IEEE80211_RATE_ERP_G; } dur = ieee80211_frame_duration(local, frame_len, rate->bitrate, erp, short_preamble); return cpu_to_le16(dur); } EXPORT_SYMBOL(ieee80211_generic_frame_duration); __le16 ieee80211_rts_duration(struct ieee80211_hw *hw, struct ieee80211_vif *vif, size_t frame_len, const struct ieee80211_tx_info *frame_txctl) { struct ieee80211_local *local = hw_to_local(hw); struct ieee80211_rate *rate; struct ieee80211_sub_if_data *sdata; bool short_preamble; int erp; u16 dur; struct ieee80211_supported_band *sband; sband = local->hw.wiphy->bands[local->hw.conf.channel->band]; short_preamble = false; rate = &sband->bitrates[frame_txctl->control.rts_cts_rate_idx]; erp = 0; if (vif) { sdata = vif_to_sdata(vif); short_preamble = sdata->vif.bss_conf.use_short_preamble; if (sdata->flags & IEEE80211_SDATA_OPERATING_GMODE) erp = rate->flags & IEEE80211_RATE_ERP_G; } /* CTS duration */ dur = ieee80211_frame_duration(local, 10, rate->bitrate, erp, short_preamble); /* Data frame duration */ dur += ieee80211_frame_duration(local, frame_len, rate->bitrate, erp, short_preamble); /* ACK duration */ dur += ieee80211_frame_duration(local, 10, rate->bitrate, erp, short_preamble); return cpu_to_le16(dur); } EXPORT_SYMBOL(ieee80211_rts_duration); __le16 ieee80211_ctstoself_duration(struct ieee80211_hw *hw, struct ieee80211_vif *vif, size_t frame_len, const struct ieee80211_tx_info *frame_txctl) { struct ieee80211_local *local = hw_to_local(hw); struct ieee80211_rate *rate; struct ieee80211_sub_if_data *sdata; bool short_preamble; int erp; u16 dur; struct ieee80211_supported_band *sband; sband = local->hw.wiphy->bands[local->hw.conf.channel->band]; short_preamble = false; rate = &sband->bitrates[frame_txctl->control.rts_cts_rate_idx]; erp = 0; if (vif) { sdata = vif_to_sdata(vif); short_preamble = sdata->vif.bss_conf.use_short_preamble; if (sdata->flags & IEEE80211_SDATA_OPERATING_GMODE) erp = rate->flags & IEEE80211_RATE_ERP_G; } /* Data frame duration */ dur = ieee80211_frame_duration(local, frame_len, rate->bitrate, erp, short_preamble); if (!(frame_txctl->flags & IEEE80211_TX_CTL_NO_ACK)) { /* ACK duration */ dur += ieee80211_frame_duration(local, 10, rate->bitrate, erp, short_preamble); } return cpu_to_le16(dur); } EXPORT_SYMBOL(ieee80211_ctstoself_duration); static void __ieee80211_wake_queue(struct ieee80211_hw *hw, int queue, enum queue_stop_reason reason) { struct ieee80211_local *local = hw_to_local(hw); struct ieee80211_sub_if_data *sdata; trace_wake_queue(local, queue, reason); if (WARN_ON(queue >= hw->queues)) return; __clear_bit(reason, &local->queue_stop_reasons[queue]); if (local->queue_stop_reasons[queue] != 0) /* someone still has this queue stopped */ return; if (skb_queue_empty(&local->pending[queue])) { rcu_read_lock(); list_for_each_entry_rcu(sdata, &local->interfaces, list) { if (test_bit(SDATA_STATE_OFFCHANNEL, &sdata->state)) continue; netif_wake_subqueue(sdata->dev, queue); } rcu_read_unlock(); } else tasklet_schedule(&local->tx_pending_tasklet); } void ieee80211_wake_queue_by_reason(struct ieee80211_hw *hw, int queue, enum queue_stop_reason reason) { struct ieee80211_local *local = hw_to_local(hw); unsigned long flags; spin_lock_irqsave(&local->queue_stop_reason_lock, flags); __ieee80211_wake_queue(hw, queue, reason); spin_unlock_irqrestore(&local->queue_stop_reason_lock, flags); } void ieee80211_wake_queue(struct ieee80211_hw *hw, int queue) { ieee80211_wake_queue_by_reason(hw, queue, IEEE80211_QUEUE_STOP_REASON_DRIVER); } EXPORT_SYMBOL(ieee80211_wake_queue); static void __ieee80211_stop_queue(struct ieee80211_hw *hw, int queue, enum queue_stop_reason reason) { struct ieee80211_local *local = hw_to_local(hw); struct ieee80211_sub_if_data *sdata; trace_stop_queue(local, queue, reason); if (WARN_ON(queue >= hw->queues)) return; __set_bit(reason, &local->queue_stop_reasons[queue]); rcu_read_lock(); list_for_each_entry_rcu(sdata, &local->interfaces, list) netif_stop_subqueue(sdata->dev, queue); rcu_read_unlock(); } void ieee80211_stop_queue_by_reason(struct ieee80211_hw *hw, int queue, enum queue_stop_reason reason) { struct ieee80211_local *local = hw_to_local(hw); unsigned long flags; spin_lock_irqsave(&local->queue_stop_reason_lock, flags); __ieee80211_stop_queue(hw, queue, reason); spin_unlock_irqrestore(&local->queue_stop_reason_lock, flags); } void ieee80211_stop_queue(struct ieee80211_hw *hw, int queue) { ieee80211_stop_queue_by_reason(hw, queue, IEEE80211_QUEUE_STOP_REASON_DRIVER); } EXPORT_SYMBOL(ieee80211_stop_queue); void ieee80211_add_pending_skb(struct ieee80211_local *local, struct sk_buff *skb) { struct ieee80211_hw *hw = &local->hw; unsigned long flags; int queue = skb_get_queue_mapping(skb); struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb); if (WARN_ON(!info->control.vif)) { kfree_skb(skb); return; } spin_lock_irqsave(&local->queue_stop_reason_lock, flags); __ieee80211_stop_queue(hw, queue, IEEE80211_QUEUE_STOP_REASON_SKB_ADD); __skb_queue_tail(&local->pending[queue], skb); __ieee80211_wake_queue(hw, queue, IEEE80211_QUEUE_STOP_REASON_SKB_ADD); spin_unlock_irqrestore(&local->queue_stop_reason_lock, flags); } void ieee80211_add_pending_skbs_fn(struct ieee80211_local *local, struct sk_buff_head *skbs, void (*fn)(void *data), void *data) { struct ieee80211_hw *hw = &local->hw; struct sk_buff *skb; unsigned long flags; int queue, i; spin_lock_irqsave(&local->queue_stop_reason_lock, flags); for (i = 0; i < hw->queues; i++) __ieee80211_stop_queue(hw, i, IEEE80211_QUEUE_STOP_REASON_SKB_ADD); while ((skb = skb_dequeue(skbs))) { struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb); if (WARN_ON(!info->control.vif)) { kfree_skb(skb); continue; } queue = skb_get_queue_mapping(skb); __skb_queue_tail(&local->pending[queue], skb); } if (fn) fn(data); for (i = 0; i < hw->queues; i++) __ieee80211_wake_queue(hw, i, IEEE80211_QUEUE_STOP_REASON_SKB_ADD); spin_unlock_irqrestore(&local->queue_stop_reason_lock, flags); } void ieee80211_add_pending_skbs(struct ieee80211_local *local, struct sk_buff_head *skbs) { ieee80211_add_pending_skbs_fn(local, skbs, NULL, NULL); } void ieee80211_stop_queues_by_reason(struct ieee80211_hw *hw, enum queue_stop_reason reason) { struct ieee80211_local *local = hw_to_local(hw); unsigned long flags; int i; spin_lock_irqsave(&local->queue_stop_reason_lock, flags); for (i = 0; i < hw->queues; i++) __ieee80211_stop_queue(hw, i, reason); spin_unlock_irqrestore(&local->queue_stop_reason_lock, flags); } void ieee80211_stop_queues(struct ieee80211_hw *hw) { ieee80211_stop_queues_by_reason(hw, IEEE80211_QUEUE_STOP_REASON_DRIVER); } EXPORT_SYMBOL(ieee80211_stop_queues); int ieee80211_queue_stopped(struct ieee80211_hw *hw, int queue) { struct ieee80211_local *local = hw_to_local(hw); unsigned long flags; int ret; if (WARN_ON(queue >= hw->queues)) return true; spin_lock_irqsave(&local->queue_stop_reason_lock, flags); ret = !!local->queue_stop_reasons[queue]; spin_unlock_irqrestore(&local->queue_stop_reason_lock, flags); return ret; } EXPORT_SYMBOL(ieee80211_queue_stopped); void ieee80211_wake_queues_by_reason(struct ieee80211_hw *hw, enum queue_stop_reason reason) { struct ieee80211_local *local = hw_to_local(hw); unsigned long flags; int i; spin_lock_irqsave(&local->queue_stop_reason_lock, flags); for (i = 0; i < hw->queues; i++) __ieee80211_wake_queue(hw, i, reason); spin_unlock_irqrestore(&local->queue_stop_reason_lock, flags); } void ieee80211_wake_queues(struct ieee80211_hw *hw) { ieee80211_wake_queues_by_reason(hw, IEEE80211_QUEUE_STOP_REASON_DRIVER); } EXPORT_SYMBOL(ieee80211_wake_queues); void ieee80211_iterate_active_interfaces( struct ieee80211_hw *hw, void (*iterator)(void *data, u8 *mac, struct ieee80211_vif *vif), void *data) { struct ieee80211_local *local = hw_to_local(hw); struct ieee80211_sub_if_data *sdata; mutex_lock(&local->iflist_mtx); list_for_each_entry(sdata, &local->interfaces, list) { switch (sdata->vif.type) { case NL80211_IFTYPE_MONITOR: case NL80211_IFTYPE_AP_VLAN: continue; default: break; } if (ieee80211_sdata_running(sdata)) iterator(data, sdata->vif.addr, &sdata->vif); } mutex_unlock(&local->iflist_mtx); } EXPORT_SYMBOL_GPL(ieee80211_iterate_active_interfaces); void ieee80211_iterate_active_interfaces_atomic( struct ieee80211_hw *hw, void (*iterator)(void *data, u8 *mac, struct ieee80211_vif *vif), void *data) { struct ieee80211_local *local = hw_to_local(hw); struct ieee80211_sub_if_data *sdata; rcu_read_lock(); list_for_each_entry_rcu(sdata, &local->interfaces, list) { switch (sdata->vif.type) { case NL80211_IFTYPE_MONITOR: case NL80211_IFTYPE_AP_VLAN: continue; default: break; } if (ieee80211_sdata_running(sdata)) iterator(data, sdata->vif.addr, &sdata->vif); } rcu_read_unlock(); } EXPORT_SYMBOL_GPL(ieee80211_iterate_active_interfaces_atomic); /* * Nothing should have been stuffed into the workqueue during * the suspend->resume cycle. If this WARN is seen then there * is a bug with either the driver suspend or something in * mac80211 stuffing into the workqueue which we haven't yet * cleared during mac80211's suspend cycle. */ static bool ieee80211_can_queue_work(struct ieee80211_local *local) { if (WARN(local->suspended && !local->resuming, "queueing ieee80211 work while going to suspend\n")) return false; return true; } void ieee80211_queue_work(struct ieee80211_hw *hw, struct work_struct *work) { struct ieee80211_local *local = hw_to_local(hw); if (!ieee80211_can_queue_work(local)) return; queue_work(local->workqueue, work); } EXPORT_SYMBOL(ieee80211_queue_work); void ieee80211_queue_delayed_work(struct ieee80211_hw *hw, struct delayed_work *dwork, unsigned long delay) { struct ieee80211_local *local = hw_to_local(hw); if (!ieee80211_can_queue_work(local)) return; queue_delayed_work(local->workqueue, dwork, delay); } EXPORT_SYMBOL(ieee80211_queue_delayed_work); u32 ieee802_11_parse_elems_crc(u8 *start, size_t len, struct ieee802_11_elems *elems, u64 filter, u32 crc) { size_t left = len; u8 *pos = start; bool calc_crc = filter != 0; DECLARE_BITMAP(seen_elems, 256); bitmap_zero(seen_elems, 256); memset(elems, 0, sizeof(*elems)); elems->ie_start = start; elems->total_len = len; while (left >= 2) { u8 id, elen; bool elem_parse_failed; id = *pos++; elen = *pos++; left -= 2; if (elen > left) { elems->parse_error = true; break; } if (id != WLAN_EID_VENDOR_SPECIFIC && id != WLAN_EID_QUIET && test_bit(id, seen_elems)) { elems->parse_error = true; left -= elen; pos += elen; continue; } if (calc_crc && id < 64 && (filter & (1ULL << id))) crc = crc32_be(crc, pos - 2, elen + 2); elem_parse_failed = false; switch (id) { case WLAN_EID_SSID: elems->ssid = pos; elems->ssid_len = elen; break; case WLAN_EID_SUPP_RATES: elems->supp_rates = pos; elems->supp_rates_len = elen; break; case WLAN_EID_FH_PARAMS: elems->fh_params = pos; elems->fh_params_len = elen; break; case WLAN_EID_DS_PARAMS: elems->ds_params = pos; elems->ds_params_len = elen; break; case WLAN_EID_CF_PARAMS: elems->cf_params = pos; elems->cf_params_len = elen; break; case WLAN_EID_TIM: if (elen >= sizeof(struct ieee80211_tim_ie)) { elems->tim = (void *)pos; elems->tim_len = elen; } else elem_parse_failed = true; break; case WLAN_EID_IBSS_PARAMS: elems->ibss_params = pos; elems->ibss_params_len = elen; break; case WLAN_EID_CHALLENGE: elems->challenge = pos; elems->challenge_len = elen; break; case WLAN_EID_VENDOR_SPECIFIC: if (elen >= 4 && pos[0] == 0x00 && pos[1] == 0x50 && pos[2] == 0xf2) { /* Microsoft OUI (00:50:F2) */ if (calc_crc) crc = crc32_be(crc, pos - 2, elen + 2); if (pos[3] == 1) { /* OUI Type 1 - WPA IE */ elems->wpa = pos; elems->wpa_len = elen; } else if (elen >= 5 && pos[3] == 2) { /* OUI Type 2 - WMM IE */ if (pos[4] == 0) { elems->wmm_info = pos; elems->wmm_info_len = elen; } else if (pos[4] == 1) { elems->wmm_param = pos; elems->wmm_param_len = elen; } } } break; case WLAN_EID_RSN: elems->rsn = pos; elems->rsn_len = elen; break; case WLAN_EID_ERP_INFO: elems->erp_info = pos; elems->erp_info_len = elen; break; case WLAN_EID_EXT_SUPP_RATES: elems->ext_supp_rates = pos; elems->ext_supp_rates_len = elen; break; case WLAN_EID_HT_CAPABILITY: if (elen >= sizeof(struct ieee80211_ht_cap)) elems->ht_cap_elem = (void *)pos; else elem_parse_failed = true; break; case WLAN_EID_HT_INFORMATION: if (elen >= sizeof(struct ieee80211_ht_info)) elems->ht_info_elem = (void *)pos; else elem_parse_failed = true; break; case WLAN_EID_MESH_ID: elems->mesh_id = pos; elems->mesh_id_len = elen; break; case WLAN_EID_MESH_CONFIG: if (elen >= sizeof(struct ieee80211_meshconf_ie)) elems->mesh_config = (void *)pos; else elem_parse_failed = true; break; case WLAN_EID_PEER_MGMT: elems->peering = pos; elems->peering_len = elen; break; case WLAN_EID_PREQ: elems->preq = pos; elems->preq_len = elen; break; case WLAN_EID_PREP: elems->prep = pos; elems->prep_len = elen; break; case WLAN_EID_PERR: elems->perr = pos; elems->perr_len = elen; break; case WLAN_EID_RANN: if (elen >= sizeof(struct ieee80211_rann_ie)) elems->rann = (void *)pos; else elem_parse_failed = true; break; case WLAN_EID_CHANNEL_SWITCH: elems->ch_switch_elem = pos; elems->ch_switch_elem_len = elen; break; case WLAN_EID_QUIET: if (!elems->quiet_elem) { elems->quiet_elem = pos; elems->quiet_elem_len = elen; } elems->num_of_quiet_elem++; break; case WLAN_EID_COUNTRY: elems->country_elem = pos; elems->country_elem_len = elen; break; case WLAN_EID_PWR_CONSTRAINT: elems->pwr_constr_elem = pos; elems->pwr_constr_elem_len = elen; break; case WLAN_EID_TIMEOUT_INTERVAL: elems->timeout_int = pos; elems->timeout_int_len = elen; break; default: break; } if (elem_parse_failed) elems->parse_error = true; else set_bit(id, seen_elems); left -= elen; pos += elen; } if (left != 0) elems->parse_error = true; return crc; } void ieee802_11_parse_elems(u8 *start, size_t len, struct ieee802_11_elems *elems) { ieee802_11_parse_elems_crc(start, len, elems, 0, 0); } void ieee80211_set_wmm_default(struct ieee80211_sub_if_data *sdata, bool bss_notify) { struct ieee80211_local *local = sdata->local; struct ieee80211_tx_queue_params qparam; int queue; bool use_11b; int aCWmin, aCWmax; if (!local->ops->conf_tx) return; memset(&qparam, 0, sizeof(qparam)); use_11b = (local->hw.conf.channel->band == IEEE80211_BAND_2GHZ) && !(sdata->flags & IEEE80211_SDATA_OPERATING_GMODE); for (queue = 0; queue < local->hw.queues; queue++) { /* Set defaults according to 802.11-2007 Table 7-37 */ aCWmax = 1023; if (use_11b) aCWmin = 31; else aCWmin = 15; switch (queue) { case 3: /* AC_BK */ qparam.cw_max = aCWmax; qparam.cw_min = aCWmin; qparam.txop = 0; qparam.aifs = 7; break; default: /* never happens but let's not leave undefined */ case 2: /* AC_BE */ qparam.cw_max = aCWmax; qparam.cw_min = aCWmin; qparam.txop = 0; qparam.aifs = 3; break; case 1: /* AC_VI */ qparam.cw_max = aCWmin; qparam.cw_min = (aCWmin + 1) / 2 - 1; if (use_11b) qparam.txop = 6016/32; else qparam.txop = 3008/32; qparam.aifs = 2; break; case 0: /* AC_VO */ qparam.cw_max = (aCWmin + 1) / 2 - 1; qparam.cw_min = (aCWmin + 1) / 4 - 1; if (use_11b) qparam.txop = 3264/32; else qparam.txop = 1504/32; qparam.aifs = 2; break; } qparam.uapsd = false; sdata->tx_conf[queue] = qparam; drv_conf_tx(local, sdata, queue, &qparam); } /* after reinitialize QoS TX queues setting to default, * disable QoS at all */ if (sdata->vif.type != NL80211_IFTYPE_MONITOR) { sdata->vif.bss_conf.qos = sdata->vif.type != NL80211_IFTYPE_STATION; if (bss_notify) ieee80211_bss_info_change_notify(sdata, BSS_CHANGED_QOS); } } void ieee80211_sta_def_wmm_params(struct ieee80211_sub_if_data *sdata, const size_t supp_rates_len, const u8 *supp_rates) { struct ieee80211_local *local = sdata->local; int i, have_higher_than_11mbit = 0; /* cf. IEEE 802.11 9.2.12 */ for (i = 0; i < supp_rates_len; i++) if ((supp_rates[i] & 0x7f) * 5 > 110) have_higher_than_11mbit = 1; if (local->hw.conf.channel->band == IEEE80211_BAND_2GHZ && have_higher_than_11mbit) sdata->flags |= IEEE80211_SDATA_OPERATING_GMODE; else sdata->flags &= ~IEEE80211_SDATA_OPERATING_GMODE; ieee80211_set_wmm_default(sdata, true); } u32 ieee80211_mandatory_rates(struct ieee80211_local *local, enum ieee80211_band band) { struct ieee80211_supported_band *sband; struct ieee80211_rate *bitrates; u32 mandatory_rates; enum ieee80211_rate_flags mandatory_flag; int i; sband = local->hw.wiphy->bands[band]; if (!sband) { WARN_ON(1); sband = local->hw.wiphy->bands[local->hw.conf.channel->band]; } if (band == IEEE80211_BAND_2GHZ) mandatory_flag = IEEE80211_RATE_MANDATORY_B; else mandatory_flag = IEEE80211_RATE_MANDATORY_A; bitrates = sband->bitrates; mandatory_rates = 0; for (i = 0; i < sband->n_bitrates; i++) if (bitrates[i].flags & mandatory_flag) mandatory_rates |= BIT(i); return mandatory_rates; } void ieee80211_send_auth(struct ieee80211_sub_if_data *sdata, u16 transaction, u16 auth_alg, u8 *extra, size_t extra_len, const u8 *da, const u8 *bssid, const u8 *key, u8 key_len, u8 key_idx) { struct ieee80211_local *local = sdata->local; struct sk_buff *skb; struct ieee80211_mgmt *mgmt; int err; skb = dev_alloc_skb(local->hw.extra_tx_headroom + sizeof(*mgmt) + 6 + extra_len); if (!skb) return; skb_reserve(skb, local->hw.extra_tx_headroom); mgmt = (struct ieee80211_mgmt *) skb_put(skb, 24 + 6); memset(mgmt, 0, 24 + 6); mgmt->frame_control = cpu_to_le16(IEEE80211_FTYPE_MGMT | IEEE80211_STYPE_AUTH); memcpy(mgmt->da, da, ETH_ALEN); memcpy(mgmt->sa, sdata->vif.addr, ETH_ALEN); memcpy(mgmt->bssid, bssid, ETH_ALEN); mgmt->u.auth.auth_alg = cpu_to_le16(auth_alg); mgmt->u.auth.auth_transaction = cpu_to_le16(transaction); mgmt->u.auth.status_code = cpu_to_le16(0); if (extra) memcpy(skb_put(skb, extra_len), extra, extra_len); if (auth_alg == WLAN_AUTH_SHARED_KEY && transaction == 3) { mgmt->frame_control |= cpu_to_le16(IEEE80211_FCTL_PROTECTED); err = ieee80211_wep_encrypt(local, skb, key, key_len, key_idx); WARN_ON(err); } IEEE80211_SKB_CB(skb)->flags |= IEEE80211_TX_INTFL_DONT_ENCRYPT; ieee80211_tx_skb(sdata, skb); } int ieee80211_build_preq_ies(struct ieee80211_local *local, u8 *buffer, const u8 *ie, size_t ie_len, enum ieee80211_band band, u32 rate_mask, u8 channel) { struct ieee80211_supported_band *sband; u8 *pos; size_t offset = 0, noffset; int supp_rates_len, i; u8 rates[32]; int num_rates; int ext_rates_len; sband = local->hw.wiphy->bands[band]; pos = buffer; num_rates = 0; for (i = 0; i < sband->n_bitrates; i++) { if ((BIT(i) & rate_mask) == 0) continue; /* skip rate */ rates[num_rates++] = (u8) (sband->bitrates[i].bitrate / 5); } supp_rates_len = min_t(int, num_rates, 8); *pos++ = WLAN_EID_SUPP_RATES; *pos++ = supp_rates_len; memcpy(pos, rates, supp_rates_len); pos += supp_rates_len; /* insert "request information" if in custom IEs */ if (ie && ie_len) { static const u8 before_extrates[] = { WLAN_EID_SSID, WLAN_EID_SUPP_RATES, WLAN_EID_REQUEST, }; noffset = ieee80211_ie_split(ie, ie_len, before_extrates, ARRAY_SIZE(before_extrates), offset); memcpy(pos, ie + offset, noffset - offset); pos += noffset - offset; offset = noffset; } ext_rates_len = num_rates - supp_rates_len; if (ext_rates_len > 0) { *pos++ = WLAN_EID_EXT_SUPP_RATES; *pos++ = ext_rates_len; memcpy(pos, rates + supp_rates_len, ext_rates_len); pos += ext_rates_len; } if (channel && sband->band == IEEE80211_BAND_2GHZ) { *pos++ = WLAN_EID_DS_PARAMS; *pos++ = 1; *pos++ = channel; } /* insert custom IEs that go before HT */ if (ie && ie_len) { static const u8 before_ht[] = { WLAN_EID_SSID, WLAN_EID_SUPP_RATES, WLAN_EID_REQUEST, WLAN_EID_EXT_SUPP_RATES, WLAN_EID_DS_PARAMS, WLAN_EID_SUPPORTED_REGULATORY_CLASSES, }; noffset = ieee80211_ie_split(ie, ie_len, before_ht, ARRAY_SIZE(before_ht), offset); memcpy(pos, ie + offset, noffset - offset); pos += noffset - offset; offset = noffset; } if (sband->ht_cap.ht_supported) pos = ieee80211_ie_build_ht_cap(pos, &sband->ht_cap, sband->ht_cap.cap); /* * If adding more here, adjust code in main.c * that calculates local->scan_ies_len. */ /* add any remaining custom IEs */ if (ie && ie_len) { noffset = ie_len; memcpy(pos, ie + offset, noffset - offset); pos += noffset - offset; } if (sband->vht_cap.vht_supported) pos = ieee80211_ie_build_vht_cap(pos, &sband->vht_cap, sband->vht_cap.cap); return pos - buffer; } struct sk_buff *ieee80211_build_probe_req(struct ieee80211_sub_if_data *sdata, u8 *dst, u32 ratemask, const u8 *ssid, size_t ssid_len, const u8 *ie, size_t ie_len, bool directed) { struct ieee80211_local *local = sdata->local; struct sk_buff *skb; struct ieee80211_mgmt *mgmt; size_t buf_len; u8 *buf; u8 chan; /* FIXME: come up with a proper value */ buf = kmalloc(200 + ie_len, GFP_KERNEL); if (!buf) return NULL; /* * Do not send DS Channel parameter for directed probe requests * in order to maximize the chance that we get a response. Some * badly-behaved APs don't respond when this parameter is included. */ if (directed) chan = 0; else chan = ieee80211_frequency_to_channel( local->hw.conf.channel->center_freq); buf_len = ieee80211_build_preq_ies(local, buf, ie, ie_len, local->hw.conf.channel->band, ratemask, chan); skb = ieee80211_probereq_get(&local->hw, &sdata->vif, ssid, ssid_len, buf, buf_len); if (!skb) goto out; if (dst) { mgmt = (struct ieee80211_mgmt *) skb->data; memcpy(mgmt->da, dst, ETH_ALEN); memcpy(mgmt->bssid, dst, ETH_ALEN); } IEEE80211_SKB_CB(skb)->flags |= IEEE80211_TX_INTFL_DONT_ENCRYPT; out: kfree(buf); return skb; } void ieee80211_send_probe_req(struct ieee80211_sub_if_data *sdata, u8 *dst, const u8 *ssid, size_t ssid_len, const u8 *ie, size_t ie_len, u32 ratemask, bool directed, bool no_cck) { struct sk_buff *skb; skb = ieee80211_build_probe_req(sdata, dst, ratemask, ssid, ssid_len, ie, ie_len, directed); if (skb) { if (no_cck) IEEE80211_SKB_CB(skb)->flags |= IEEE80211_TX_CTL_NO_CCK_RATE; ieee80211_tx_skb(sdata, skb); } } u32 ieee80211_sta_get_rates(struct ieee80211_local *local, struct ieee802_11_elems *elems, enum ieee80211_band band) { struct ieee80211_supported_band *sband; struct ieee80211_rate *bitrates; size_t num_rates; u32 supp_rates; int i, j; sband = local->hw.wiphy->bands[band]; if (!sband) { WARN_ON(1); sband = local->hw.wiphy->bands[local->hw.conf.channel->band]; } bitrates = sband->bitrates; num_rates = sband->n_bitrates; supp_rates = 0; for (i = 0; i < elems->supp_rates_len + elems->ext_supp_rates_len; i++) { u8 rate = 0; int own_rate; if (i < elems->supp_rates_len) rate = elems->supp_rates[i]; else if (elems->ext_supp_rates) rate = elems->ext_supp_rates [i - elems->supp_rates_len]; own_rate = 5 * (rate & 0x7f); for (j = 0; j < num_rates; j++) if (bitrates[j].bitrate == own_rate) supp_rates |= BIT(j); } return supp_rates; } void ieee80211_stop_device(struct ieee80211_local *local) { ieee80211_led_radio(local, false); ieee80211_mod_tpt_led_trig(local, 0, IEEE80211_TPT_LEDTRIG_FL_RADIO); cancel_work_sync(&local->reconfig_filter); flush_workqueue(local->workqueue); drv_stop(local); } int ieee80211_reconfig(struct ieee80211_local *local) { struct ieee80211_hw *hw = &local->hw; struct ieee80211_sub_if_data *sdata; struct sta_info *sta; int res, i; #ifdef CONFIG_PM if (local->suspended) local->resuming = true; if (local->wowlan) { local->wowlan = false; res = drv_resume(local); if (res < 0) { local->resuming = false; return res; } if (res == 0) goto wake_up; WARN_ON(res > 1); /* * res is 1, which means the driver requested * to go through a regular reset on wakeup. */ } #endif /* everything else happens only if HW was up & running */ if (!local->open_count) goto wake_up; /* * Upon resume hardware can sometimes be goofy due to * various platform / driver / bus issues, so restarting * the device may at times not work immediately. Propagate * the error. */ res = drv_start(local); if (res) { WARN(local->suspended, "Hardware became unavailable " "upon resume. This could be a software issue " "prior to suspend or a hardware issue.\n"); return res; } /* setup fragmentation threshold */ drv_set_frag_threshold(local, hw->wiphy->frag_threshold); /* setup RTS threshold */ drv_set_rts_threshold(local, hw->wiphy->rts_threshold); /* reset coverage class */ drv_set_coverage_class(local, hw->wiphy->coverage_class); ieee80211_led_radio(local, true); ieee80211_mod_tpt_led_trig(local, IEEE80211_TPT_LEDTRIG_FL_RADIO, 0); /* add interfaces */ list_for_each_entry(sdata, &local->interfaces, list) { if (sdata->vif.type != NL80211_IFTYPE_AP_VLAN && sdata->vif.type != NL80211_IFTYPE_MONITOR && ieee80211_sdata_running(sdata)) res = drv_add_interface(local, sdata); } /* add STAs back */ mutex_lock(&local->sta_mtx); list_for_each_entry(sta, &local->sta_list, list) { if (sta->uploaded) { enum ieee80211_sta_state state; for (state = IEEE80211_STA_NOTEXIST; state < sta->sta_state - 1; state++) WARN_ON(drv_sta_state(local, sta->sdata, sta, state, state + 1)); } } mutex_unlock(&local->sta_mtx); /* reconfigure tx conf */ list_for_each_entry(sdata, &local->interfaces, list) { if (sdata->vif.type == NL80211_IFTYPE_AP_VLAN || sdata->vif.type == NL80211_IFTYPE_MONITOR || !ieee80211_sdata_running(sdata)) continue; for (i = 0; i < hw->queues; i++) drv_conf_tx(local, sdata, i, &sdata->tx_conf[i]); } /* reconfigure hardware */ ieee80211_hw_config(local, ~0); ieee80211_configure_filter(local); /* Finally also reconfigure all the BSS information */ list_for_each_entry(sdata, &local->interfaces, list) { u32 changed; if (!ieee80211_sdata_running(sdata)) continue; /* common change flags for all interface types */ changed = BSS_CHANGED_ERP_CTS_PROT | BSS_CHANGED_ERP_PREAMBLE | BSS_CHANGED_ERP_SLOT | BSS_CHANGED_HT | BSS_CHANGED_BASIC_RATES | BSS_CHANGED_BEACON_INT | BSS_CHANGED_BSSID | BSS_CHANGED_CQM | BSS_CHANGED_QOS | BSS_CHANGED_IDLE; switch (sdata->vif.type) { case NL80211_IFTYPE_STATION: changed |= BSS_CHANGED_ASSOC | BSS_CHANGED_ARP_FILTER; mutex_lock(&sdata->u.mgd.mtx); ieee80211_bss_info_change_notify(sdata, changed); mutex_unlock(&sdata->u.mgd.mtx); break; case NL80211_IFTYPE_ADHOC: changed |= BSS_CHANGED_IBSS; /* fall through */ case NL80211_IFTYPE_AP: changed |= BSS_CHANGED_SSID; if (sdata->vif.type == NL80211_IFTYPE_AP) changed |= BSS_CHANGED_AP_PROBE_RESP; /* fall through */ case NL80211_IFTYPE_MESH_POINT: changed |= BSS_CHANGED_BEACON | BSS_CHANGED_BEACON_ENABLED; ieee80211_bss_info_change_notify(sdata, changed); break; case NL80211_IFTYPE_WDS: break; case NL80211_IFTYPE_AP_VLAN: case NL80211_IFTYPE_MONITOR: /* ignore virtual */ break; case NL80211_IFTYPE_UNSPECIFIED: case NUM_NL80211_IFTYPES: case NL80211_IFTYPE_P2P_CLIENT: case NL80211_IFTYPE_P2P_GO: WARN_ON(1); break; } } ieee80211_recalc_ps(local, -1); /* * The sta might be in psm against the ap (e.g. because * this was the state before a hw restart), so we * explicitly send a null packet in order to make sure * it'll sync against the ap (and get out of psm). */ if (!(local->hw.conf.flags & IEEE80211_CONF_PS)) { list_for_each_entry(sdata, &local->interfaces, list) { if (sdata->vif.type != NL80211_IFTYPE_STATION) continue; ieee80211_send_nullfunc(local, sdata, 0); } } /* * Clear the WLAN_STA_BLOCK_BA flag so new aggregation * sessions can be established after a resume. * * Also tear down aggregation sessions since reconfiguring * them in a hardware restart scenario is not easily done * right now, and the hardware will have lost information * about the sessions, but we and the AP still think they * are active. This is really a workaround though. */ if (hw->flags & IEEE80211_HW_AMPDU_AGGREGATION) { mutex_lock(&local->sta_mtx); list_for_each_entry(sta, &local->sta_list, list) { ieee80211_sta_tear_down_BA_sessions(sta, true); clear_sta_flag(sta, WLAN_STA_BLOCK_BA); } mutex_unlock(&local->sta_mtx); } /* add back keys */ list_for_each_entry(sdata, &local->interfaces, list) if (ieee80211_sdata_running(sdata)) ieee80211_enable_keys(sdata); wake_up: ieee80211_wake_queues_by_reason(hw, IEEE80211_QUEUE_STOP_REASON_SUSPEND); /* * If this is for hw restart things are still running. * We may want to change that later, however. */ if (!local->suspended) return 0; #ifdef CONFIG_PM /* first set suspended false, then resuming */ local->suspended = false; mb(); local->resuming = false; list_for_each_entry(sdata, &local->interfaces, list) { switch(sdata->vif.type) { case NL80211_IFTYPE_STATION: ieee80211_sta_restart(sdata); break; case NL80211_IFTYPE_ADHOC: ieee80211_ibss_restart(sdata); break; case NL80211_IFTYPE_MESH_POINT: ieee80211_mesh_restart(sdata); break; default: break; } } mod_timer(&local->sta_cleanup, jiffies + 1); mutex_lock(&local->sta_mtx); list_for_each_entry(sta, &local->sta_list, list) mesh_plink_restart(sta); mutex_unlock(&local->sta_mtx); #else WARN_ON(1); #endif return 0; } void ieee80211_resume_disconnect(struct ieee80211_vif *vif) { struct ieee80211_sub_if_data *sdata; struct ieee80211_local *local; struct ieee80211_key *key; if (WARN_ON(!vif)) return; sdata = vif_to_sdata(vif); local = sdata->local; if (WARN_ON(!local->resuming)) return; if (WARN_ON(vif->type != NL80211_IFTYPE_STATION)) return; sdata->flags |= IEEE80211_SDATA_DISCONNECT_RESUME; mutex_lock(&local->key_mtx); list_for_each_entry(key, &sdata->key_list, list) key->flags |= KEY_FLAG_TAINTED; mutex_unlock(&local->key_mtx); } EXPORT_SYMBOL_GPL(ieee80211_resume_disconnect); static int check_mgd_smps(struct ieee80211_if_managed *ifmgd, enum ieee80211_smps_mode *smps_mode) { if (ifmgd->associated) { *smps_mode = ifmgd->ap_smps; if (*smps_mode == IEEE80211_SMPS_AUTOMATIC) { if (ifmgd->powersave) *smps_mode = IEEE80211_SMPS_DYNAMIC; else *smps_mode = IEEE80211_SMPS_OFF; } return 1; } return 0; } /* must hold iflist_mtx */ void ieee80211_recalc_smps(struct ieee80211_local *local) { struct ieee80211_sub_if_data *sdata; enum ieee80211_smps_mode smps_mode = IEEE80211_SMPS_OFF; int count = 0; lockdep_assert_held(&local->iflist_mtx); /* * This function could be improved to handle multiple * interfaces better, but right now it makes any * non-station interfaces force SM PS to be turned * off. If there are multiple station interfaces it * could also use the best possible mode, e.g. if * one is in static and the other in dynamic then * dynamic is ok. */ list_for_each_entry(sdata, &local->interfaces, list) { if (!ieee80211_sdata_running(sdata)) continue; if (sdata->vif.type != NL80211_IFTYPE_STATION) goto set; count += check_mgd_smps(&sdata->u.mgd, &smps_mode); if (count > 1) { smps_mode = IEEE80211_SMPS_OFF; break; } } if (smps_mode == local->smps_mode) return; set: local->smps_mode = smps_mode; /* changed flag is auto-detected for this */ ieee80211_hw_config(local, 0); } static bool ieee80211_id_in_list(const u8 *ids, int n_ids, u8 id) { int i; for (i = 0; i < n_ids; i++) if (ids[i] == id) return true; return false; } /** * ieee80211_ie_split - split an IE buffer according to ordering * * @ies: the IE buffer * @ielen: the length of the IE buffer * @ids: an array with element IDs that are allowed before * the split * @n_ids: the size of the element ID array * @offset: offset where to start splitting in the buffer * * This function splits an IE buffer by updating the @offset * variable to point to the location where the buffer should be * split. * * It assumes that the given IE buffer is well-formed, this * has to be guaranteed by the caller! * * It also assumes that the IEs in the buffer are ordered * correctly, if not the result of using this function will not * be ordered correctly either, i.e. it does no reordering. * * The function returns the offset where the next part of the * buffer starts, which may be @ielen if the entire (remainder) * of the buffer should be used. */ size_t ieee80211_ie_split(const u8 *ies, size_t ielen, const u8 *ids, int n_ids, size_t offset) { size_t pos = offset; while (pos < ielen && ieee80211_id_in_list(ids, n_ids, ies[pos])) pos += 2 + ies[pos + 1]; return pos; } size_t ieee80211_ie_split_vendor(const u8 *ies, size_t ielen, size_t offset) { size_t pos = offset; while (pos < ielen && ies[pos] != WLAN_EID_VENDOR_SPECIFIC) pos += 2 + ies[pos + 1]; return pos; } static void _ieee80211_enable_rssi_reports(struct ieee80211_sub_if_data *sdata, int rssi_min_thold, int rssi_max_thold) { trace_api_enable_rssi_reports(sdata, rssi_min_thold, rssi_max_thold); if (WARN_ON(sdata->vif.type != NL80211_IFTYPE_STATION)) return; /* * Scale up threshold values before storing it, as the RSSI averaging * algorithm uses a scaled up value as well. Change this scaling * factor if the RSSI averaging algorithm changes. */ sdata->u.mgd.rssi_min_thold = rssi_min_thold*16; sdata->u.mgd.rssi_max_thold = rssi_max_thold*16; } void ieee80211_enable_rssi_reports(struct ieee80211_vif *vif, int rssi_min_thold, int rssi_max_thold) { struct ieee80211_sub_if_data *sdata = vif_to_sdata(vif); WARN_ON(rssi_min_thold == rssi_max_thold || rssi_min_thold > rssi_max_thold); _ieee80211_enable_rssi_reports(sdata, rssi_min_thold, rssi_max_thold); } EXPORT_SYMBOL(ieee80211_enable_rssi_reports); void ieee80211_disable_rssi_reports(struct ieee80211_vif *vif) { struct ieee80211_sub_if_data *sdata = vif_to_sdata(vif); _ieee80211_enable_rssi_reports(sdata, 0, 0); } EXPORT_SYMBOL(ieee80211_disable_rssi_reports); u8 *ieee80211_ie_build_ht_cap(u8 *pos, struct ieee80211_sta_ht_cap *ht_cap, u16 cap) { __le16 tmp; *pos++ = WLAN_EID_HT_CAPABILITY; *pos++ = sizeof(struct ieee80211_ht_cap); memset(pos, 0, sizeof(struct ieee80211_ht_cap)); /* capability flags */ tmp = cpu_to_le16(cap); memcpy(pos, &tmp, sizeof(u16)); pos += sizeof(u16); /* AMPDU parameters */ *pos++ = ht_cap->ampdu_factor | (ht_cap->ampdu_density << IEEE80211_HT_AMPDU_PARM_DENSITY_SHIFT); /* MCS set */ memcpy(pos, &ht_cap->mcs, sizeof(ht_cap->mcs)); pos += sizeof(ht_cap->mcs); /* extended capabilities */ pos += sizeof(__le16); /* BF capabilities */ pos += sizeof(__le32); /* antenna selection */ pos += sizeof(u8); return pos; } u8 *ieee80211_ie_build_vht_cap(u8 *pos, struct ieee80211_sta_vht_cap *vht_cap, u32 cap) { __le32 tmp; *pos++ = WLAN_EID_VHT_CAPABILITY; *pos++ = sizeof(struct ieee80211_vht_cap); memset(pos, 0, sizeof(struct ieee80211_vht_cap)); /* capability flags */ tmp = cpu_to_le32(cap); memcpy(pos, &tmp, sizeof(u32)); pos += sizeof(u32); /* VHT MCS set */ memcpy(pos, &vht_cap->vht_mcs, sizeof(vht_cap->vht_mcs)); pos += sizeof(vht_cap->vht_mcs); return pos; } u8 *ieee80211_ie_build_ht_info(u8 *pos, struct ieee80211_sta_ht_cap *ht_cap, struct ieee80211_channel *channel, enum nl80211_channel_type channel_type) { struct ieee80211_ht_info *ht_info; /* Build HT Information */ *pos++ = WLAN_EID_HT_INFORMATION; *pos++ = sizeof(struct ieee80211_ht_info); ht_info = (struct ieee80211_ht_info *)pos; ht_info->control_chan = ieee80211_frequency_to_channel(channel->center_freq); switch (channel_type) { case NL80211_CHAN_HT40MINUS: ht_info->ht_param = IEEE80211_HT_PARAM_CHA_SEC_BELOW; break; case NL80211_CHAN_HT40PLUS: ht_info->ht_param = IEEE80211_HT_PARAM_CHA_SEC_ABOVE; break; case NL80211_CHAN_HT20: default: ht_info->ht_param = IEEE80211_HT_PARAM_CHA_SEC_NONE; break; } if (ht_cap->cap & IEEE80211_HT_CAP_SUP_WIDTH_20_40) ht_info->ht_param |= IEEE80211_HT_PARAM_CHAN_WIDTH_ANY; /* * Note: According to 802.11n-2009 9.13.3.1, HT Protection field and * RIFS Mode are reserved in IBSS mode, therefore keep them at 0 */ ht_info->operation_mode = 0x0000; ht_info->stbc_param = 0x0000; /* It seems that Basic MCS set and Supported MCS set are identical for the first 10 bytes */ memset(&ht_info->basic_set, 0, 16); memcpy(&ht_info->basic_set, &ht_cap->mcs, 10); return pos + sizeof(struct ieee80211_ht_info); } enum nl80211_channel_type ieee80211_ht_info_to_channel_type(struct ieee80211_ht_info *ht_info) { enum nl80211_channel_type channel_type; if (!ht_info) return NL80211_CHAN_NO_HT; switch (ht_info->ht_param & IEEE80211_HT_PARAM_CHA_SEC_OFFSET) { case IEEE80211_HT_PARAM_CHA_SEC_NONE: channel_type = NL80211_CHAN_HT20; break; case IEEE80211_HT_PARAM_CHA_SEC_ABOVE: channel_type = NL80211_CHAN_HT40PLUS; break; case IEEE80211_HT_PARAM_CHA_SEC_BELOW: channel_type = NL80211_CHAN_HT40MINUS; break; default: channel_type = NL80211_CHAN_NO_HT; } return channel_type; } int ieee80211_add_srates_ie(struct ieee80211_vif *vif, struct sk_buff *skb) { struct ieee80211_sub_if_data *sdata = vif_to_sdata(vif); struct ieee80211_local *local = sdata->local; struct ieee80211_supported_band *sband; int rate; u8 i, rates, *pos; sband = local->hw.wiphy->bands[local->hw.conf.channel->band]; rates = sband->n_bitrates; if (rates > 8) rates = 8; if (skb_tailroom(skb) < rates + 2) return -ENOMEM; pos = skb_put(skb, rates + 2); *pos++ = WLAN_EID_SUPP_RATES; *pos++ = rates; for (i = 0; i < rates; i++) { rate = sband->bitrates[i].bitrate; *pos++ = (u8) (rate / 5); } return 0; } int ieee80211_add_ext_srates_ie(struct ieee80211_vif *vif, struct sk_buff *skb) { struct ieee80211_sub_if_data *sdata = vif_to_sdata(vif); struct ieee80211_local *local = sdata->local; struct ieee80211_supported_band *sband; int rate; u8 i, exrates, *pos; sband = local->hw.wiphy->bands[local->hw.conf.channel->band]; exrates = sband->n_bitrates; if (exrates > 8) exrates -= 8; else exrates = 0; if (skb_tailroom(skb) < exrates + 2) return -ENOMEM; if (exrates) { pos = skb_put(skb, exrates + 2); *pos++ = WLAN_EID_EXT_SUPP_RATES; *pos++ = exrates; for (i = 8; i < sband->n_bitrates; i++) { rate = sband->bitrates[i].bitrate; *pos++ = (u8) (rate / 5); } } return 0; }
gpl-2.0
bassface13/android_kernel_lenovo_a6000
sound/soc/fsl/imx-pcm.c
2046
3645
/* * Copyright 2009 Sascha Hauer <s.hauer@pengutronix.de> * * This code is based on code copyrighted by Freescale, * Liam Girdwood, Javier Martin and probably others. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. */ #include <linux/dma-mapping.h> #include <linux/module.h> #include <sound/pcm.h> #include <sound/soc.h> #include "imx-pcm.h" int snd_imx_pcm_mmap(struct snd_pcm_substream *substream, struct vm_area_struct *vma) { struct snd_pcm_runtime *runtime = substream->runtime; int ret; ret = dma_mmap_writecombine(substream->pcm->card->dev, vma, runtime->dma_area, runtime->dma_addr, runtime->dma_bytes); pr_debug("%s: ret: %d %p 0x%08x 0x%08x\n", __func__, ret, runtime->dma_area, runtime->dma_addr, runtime->dma_bytes); return ret; } EXPORT_SYMBOL_GPL(snd_imx_pcm_mmap); static int imx_pcm_preallocate_dma_buffer(struct snd_pcm *pcm, int stream) { struct snd_pcm_substream *substream = pcm->streams[stream].substream; struct snd_dma_buffer *buf = &substream->dma_buffer; size_t size = IMX_SSI_DMABUF_SIZE; buf->dev.type = SNDRV_DMA_TYPE_DEV; buf->dev.dev = pcm->card->dev; buf->private_data = NULL; buf->area = dma_alloc_writecombine(pcm->card->dev, size, &buf->addr, GFP_KERNEL); if (!buf->area) return -ENOMEM; buf->bytes = size; return 0; } static u64 imx_pcm_dmamask = DMA_BIT_MASK(32); int imx_pcm_new(struct snd_soc_pcm_runtime *rtd) { struct snd_card *card = rtd->card->snd_card; struct snd_pcm *pcm = rtd->pcm; int ret = 0; if (!card->dev->dma_mask) card->dev->dma_mask = &imx_pcm_dmamask; if (!card->dev->coherent_dma_mask) card->dev->coherent_dma_mask = DMA_BIT_MASK(32); if (pcm->streams[SNDRV_PCM_STREAM_PLAYBACK].substream) { ret = imx_pcm_preallocate_dma_buffer(pcm, SNDRV_PCM_STREAM_PLAYBACK); if (ret) goto out; } if (pcm->streams[SNDRV_PCM_STREAM_CAPTURE].substream) { ret = imx_pcm_preallocate_dma_buffer(pcm, SNDRV_PCM_STREAM_CAPTURE); if (ret) goto out; } out: return ret; } EXPORT_SYMBOL_GPL(imx_pcm_new); void imx_pcm_free(struct snd_pcm *pcm) { struct snd_pcm_substream *substream; struct snd_dma_buffer *buf; int stream; for (stream = 0; stream < 2; stream++) { substream = pcm->streams[stream].substream; if (!substream) continue; buf = &substream->dma_buffer; if (!buf->area) continue; dma_free_writecombine(pcm->card->dev, buf->bytes, buf->area, buf->addr); buf->area = NULL; } } EXPORT_SYMBOL_GPL(imx_pcm_free); static int imx_pcm_probe(struct platform_device *pdev) { if (strcmp(pdev->id_entry->name, "imx-fiq-pcm-audio") == 0) return imx_pcm_fiq_init(pdev); return imx_pcm_dma_init(pdev); } static int imx_pcm_remove(struct platform_device *pdev) { if (strcmp(pdev->id_entry->name, "imx-fiq-pcm-audio") == 0) snd_soc_unregister_platform(&pdev->dev); else imx_pcm_dma_exit(pdev); return 0; } static struct platform_device_id imx_pcm_devtype[] = { { .name = "imx-pcm-audio", }, { .name = "imx-fiq-pcm-audio", }, { /* sentinel */ } }; MODULE_DEVICE_TABLE(platform, imx_pcm_devtype); static struct platform_driver imx_pcm_driver = { .driver = { .name = "imx-pcm", .owner = THIS_MODULE, }, .id_table = imx_pcm_devtype, .probe = imx_pcm_probe, .remove = imx_pcm_remove, }; module_platform_driver(imx_pcm_driver); MODULE_DESCRIPTION("Freescale i.MX PCM driver"); MODULE_AUTHOR("Sascha Hauer <s.hauer@pengutronix.de>"); MODULE_LICENSE("GPL");
gpl-2.0
BlackBox-Kernel/blackbox_sprout_lp
arch/arm/mach-ux500/cache-l2x0.c
2046
1855
/* * Copyright (C) ST-Ericsson SA 2011 * * License terms: GNU General Public License (GPL) version 2 */ #include <linux/io.h> #include <linux/of.h> #include <asm/cacheflush.h> #include <asm/hardware/cache-l2x0.h> #include "db8500-regs.h" #include "id.h" static void __iomem *l2x0_base; static int __init ux500_l2x0_unlock(void) { int i; /* * Unlock Data and Instruction Lock if locked. Ux500 U-Boot versions * apparently locks both caches before jumping to the kernel. The * l2x0 core will not touch the unlock registers if the l2x0 is * already enabled, so we do it right here instead. The PL310 has * 8 sets of registers, one per possible CPU. */ for (i = 0; i < 8; i++) { writel_relaxed(0x0, l2x0_base + L2X0_LOCKDOWN_WAY_D_BASE + i * L2X0_LOCKDOWN_STRIDE); writel_relaxed(0x0, l2x0_base + L2X0_LOCKDOWN_WAY_I_BASE + i * L2X0_LOCKDOWN_STRIDE); } return 0; } static int __init ux500_l2x0_init(void) { u32 aux_val = 0x3e000000; if (cpu_is_u8500_family() || cpu_is_ux540_family()) l2x0_base = __io_address(U8500_L2CC_BASE); else ux500_unknown_soc(); /* Unlock before init */ ux500_l2x0_unlock(); /* DBx540's L2 has 128KB way size */ if (cpu_is_ux540_family()) /* 128KB way size */ aux_val |= (0x4 << L2X0_AUX_CTRL_WAY_SIZE_SHIFT); else /* 64KB way size */ aux_val |= (0x3 << L2X0_AUX_CTRL_WAY_SIZE_SHIFT); /* 64KB way size, 8 way associativity, force WA */ if (of_have_populated_dt()) l2x0_of_init(aux_val, 0xc0000fff); else l2x0_init(l2x0_base, aux_val, 0xc0000fff); /* * We can't disable l2 as we are in non secure mode, currently * this seems be called only during kexec path. So let's * override outer.disable with nasty assignment until we have * some SMI service available. */ outer_cache.disable = NULL; return 0; } early_initcall(ux500_l2x0_init);
gpl-2.0
skinzor/henkate_kernel_j5-stock
fs/hfsplus/extents.c
2558
15247
/* * linux/fs/hfsplus/extents.c * * Copyright (C) 2001 * Brad Boyer (flar@allandria.com) * (C) 2003 Ardis Technologies <roman@ardistech.com> * * Handling of Extents both in catalog and extents overflow trees */ #include <linux/errno.h> #include <linux/fs.h> #include <linux/pagemap.h> #include "hfsplus_fs.h" #include "hfsplus_raw.h" /* Compare two extents keys, returns 0 on same, pos/neg for difference */ int hfsplus_ext_cmp_key(const hfsplus_btree_key *k1, const hfsplus_btree_key *k2) { __be32 k1id, k2id; __be32 k1s, k2s; k1id = k1->ext.cnid; k2id = k2->ext.cnid; if (k1id != k2id) return be32_to_cpu(k1id) < be32_to_cpu(k2id) ? -1 : 1; if (k1->ext.fork_type != k2->ext.fork_type) return k1->ext.fork_type < k2->ext.fork_type ? -1 : 1; k1s = k1->ext.start_block; k2s = k2->ext.start_block; if (k1s == k2s) return 0; return be32_to_cpu(k1s) < be32_to_cpu(k2s) ? -1 : 1; } static void hfsplus_ext_build_key(hfsplus_btree_key *key, u32 cnid, u32 block, u8 type) { key->key_len = cpu_to_be16(HFSPLUS_EXT_KEYLEN - 2); key->ext.cnid = cpu_to_be32(cnid); key->ext.start_block = cpu_to_be32(block); key->ext.fork_type = type; key->ext.pad = 0; } static u32 hfsplus_ext_find_block(struct hfsplus_extent *ext, u32 off) { int i; u32 count; for (i = 0; i < 8; ext++, i++) { count = be32_to_cpu(ext->block_count); if (off < count) return be32_to_cpu(ext->start_block) + off; off -= count; } /* panic? */ return 0; } static int hfsplus_ext_block_count(struct hfsplus_extent *ext) { int i; u32 count = 0; for (i = 0; i < 8; ext++, i++) count += be32_to_cpu(ext->block_count); return count; } static u32 hfsplus_ext_lastblock(struct hfsplus_extent *ext) { int i; ext += 7; for (i = 0; i < 7; ext--, i++) if (ext->block_count) break; return be32_to_cpu(ext->start_block) + be32_to_cpu(ext->block_count); } static int __hfsplus_ext_write_extent(struct inode *inode, struct hfs_find_data *fd) { struct hfsplus_inode_info *hip = HFSPLUS_I(inode); int res; WARN_ON(!mutex_is_locked(&hip->extents_lock)); hfsplus_ext_build_key(fd->search_key, inode->i_ino, hip->cached_start, HFSPLUS_IS_RSRC(inode) ? HFSPLUS_TYPE_RSRC : HFSPLUS_TYPE_DATA); res = hfs_brec_find(fd, hfs_find_rec_by_key); if (hip->extent_state & HFSPLUS_EXT_NEW) { if (res != -ENOENT) return res; hfs_brec_insert(fd, hip->cached_extents, sizeof(hfsplus_extent_rec)); hip->extent_state &= ~(HFSPLUS_EXT_DIRTY | HFSPLUS_EXT_NEW); } else { if (res) return res; hfs_bnode_write(fd->bnode, hip->cached_extents, fd->entryoffset, fd->entrylength); hip->extent_state &= ~HFSPLUS_EXT_DIRTY; } /* * We can't just use hfsplus_mark_inode_dirty here, because we * also get called from hfsplus_write_inode, which should not * redirty the inode. Instead the callers have to be careful * to explicily mark the inode dirty, too. */ set_bit(HFSPLUS_I_EXT_DIRTY, &hip->flags); return 0; } static int hfsplus_ext_write_extent_locked(struct inode *inode) { int res = 0; if (HFSPLUS_I(inode)->extent_state & HFSPLUS_EXT_DIRTY) { struct hfs_find_data fd; res = hfs_find_init(HFSPLUS_SB(inode->i_sb)->ext_tree, &fd); if (res) return res; res = __hfsplus_ext_write_extent(inode, &fd); hfs_find_exit(&fd); } return res; } int hfsplus_ext_write_extent(struct inode *inode) { int res; mutex_lock(&HFSPLUS_I(inode)->extents_lock); res = hfsplus_ext_write_extent_locked(inode); mutex_unlock(&HFSPLUS_I(inode)->extents_lock); return res; } static inline int __hfsplus_ext_read_extent(struct hfs_find_data *fd, struct hfsplus_extent *extent, u32 cnid, u32 block, u8 type) { int res; hfsplus_ext_build_key(fd->search_key, cnid, block, type); fd->key->ext.cnid = 0; res = hfs_brec_find(fd, hfs_find_rec_by_key); if (res && res != -ENOENT) return res; if (fd->key->ext.cnid != fd->search_key->ext.cnid || fd->key->ext.fork_type != fd->search_key->ext.fork_type) return -ENOENT; if (fd->entrylength != sizeof(hfsplus_extent_rec)) return -EIO; hfs_bnode_read(fd->bnode, extent, fd->entryoffset, sizeof(hfsplus_extent_rec)); return 0; } static inline int __hfsplus_ext_cache_extent(struct hfs_find_data *fd, struct inode *inode, u32 block) { struct hfsplus_inode_info *hip = HFSPLUS_I(inode); int res; WARN_ON(!mutex_is_locked(&hip->extents_lock)); if (hip->extent_state & HFSPLUS_EXT_DIRTY) { res = __hfsplus_ext_write_extent(inode, fd); if (res) return res; } res = __hfsplus_ext_read_extent(fd, hip->cached_extents, inode->i_ino, block, HFSPLUS_IS_RSRC(inode) ? HFSPLUS_TYPE_RSRC : HFSPLUS_TYPE_DATA); if (!res) { hip->cached_start = be32_to_cpu(fd->key->ext.start_block); hip->cached_blocks = hfsplus_ext_block_count(hip->cached_extents); } else { hip->cached_start = hip->cached_blocks = 0; hip->extent_state &= ~(HFSPLUS_EXT_DIRTY | HFSPLUS_EXT_NEW); } return res; } static int hfsplus_ext_read_extent(struct inode *inode, u32 block) { struct hfsplus_inode_info *hip = HFSPLUS_I(inode); struct hfs_find_data fd; int res; if (block >= hip->cached_start && block < hip->cached_start + hip->cached_blocks) return 0; res = hfs_find_init(HFSPLUS_SB(inode->i_sb)->ext_tree, &fd); if (!res) { res = __hfsplus_ext_cache_extent(&fd, inode, block); hfs_find_exit(&fd); } return res; } /* Get a block at iblock for inode, possibly allocating if create */ int hfsplus_get_block(struct inode *inode, sector_t iblock, struct buffer_head *bh_result, int create) { struct super_block *sb = inode->i_sb; struct hfsplus_sb_info *sbi = HFSPLUS_SB(sb); struct hfsplus_inode_info *hip = HFSPLUS_I(inode); int res = -EIO; u32 ablock, dblock, mask; sector_t sector; int was_dirty = 0; int shift; /* Convert inode block to disk allocation block */ shift = sbi->alloc_blksz_shift - sb->s_blocksize_bits; ablock = iblock >> sbi->fs_shift; if (iblock >= hip->fs_blocks) { if (iblock > hip->fs_blocks || !create) return -EIO; if (ablock >= hip->alloc_blocks) { res = hfsplus_file_extend(inode); if (res) return res; } } else create = 0; if (ablock < hip->first_blocks) { dblock = hfsplus_ext_find_block(hip->first_extents, ablock); goto done; } if (inode->i_ino == HFSPLUS_EXT_CNID) return -EIO; mutex_lock(&hip->extents_lock); /* * hfsplus_ext_read_extent will write out a cached extent into * the extents btree. In that case we may have to mark the inode * dirty even for a pure read of an extent here. */ was_dirty = (hip->extent_state & HFSPLUS_EXT_DIRTY); res = hfsplus_ext_read_extent(inode, ablock); if (res) { mutex_unlock(&hip->extents_lock); return -EIO; } dblock = hfsplus_ext_find_block(hip->cached_extents, ablock - hip->cached_start); mutex_unlock(&hip->extents_lock); done: hfs_dbg(EXTENT, "get_block(%lu): %llu - %u\n", inode->i_ino, (long long)iblock, dblock); mask = (1 << sbi->fs_shift) - 1; sector = ((sector_t)dblock << sbi->fs_shift) + sbi->blockoffset + (iblock & mask); map_bh(bh_result, sb, sector); if (create) { set_buffer_new(bh_result); hip->phys_size += sb->s_blocksize; hip->fs_blocks++; inode_add_bytes(inode, sb->s_blocksize); } if (create || was_dirty) mark_inode_dirty(inode); return 0; } static void hfsplus_dump_extent(struct hfsplus_extent *extent) { int i; hfs_dbg(EXTENT, " "); for (i = 0; i < 8; i++) hfs_dbg_cont(EXTENT, " %u:%u", be32_to_cpu(extent[i].start_block), be32_to_cpu(extent[i].block_count)); hfs_dbg_cont(EXTENT, "\n"); } static int hfsplus_add_extent(struct hfsplus_extent *extent, u32 offset, u32 alloc_block, u32 block_count) { u32 count, start; int i; hfsplus_dump_extent(extent); for (i = 0; i < 8; extent++, i++) { count = be32_to_cpu(extent->block_count); if (offset == count) { start = be32_to_cpu(extent->start_block); if (alloc_block != start + count) { if (++i >= 8) return -ENOSPC; extent++; extent->start_block = cpu_to_be32(alloc_block); } else block_count += count; extent->block_count = cpu_to_be32(block_count); return 0; } else if (offset < count) break; offset -= count; } /* panic? */ return -EIO; } static int hfsplus_free_extents(struct super_block *sb, struct hfsplus_extent *extent, u32 offset, u32 block_nr) { u32 count, start; int i; int err = 0; hfsplus_dump_extent(extent); for (i = 0; i < 8; extent++, i++) { count = be32_to_cpu(extent->block_count); if (offset == count) goto found; else if (offset < count) break; offset -= count; } /* panic? */ return -EIO; found: for (;;) { start = be32_to_cpu(extent->start_block); if (count <= block_nr) { err = hfsplus_block_free(sb, start, count); if (err) { pr_err("can't free extent\n"); hfs_dbg(EXTENT, " start: %u count: %u\n", start, count); } extent->block_count = 0; extent->start_block = 0; block_nr -= count; } else { count -= block_nr; err = hfsplus_block_free(sb, start + count, block_nr); if (err) { pr_err("can't free extent\n"); hfs_dbg(EXTENT, " start: %u count: %u\n", start, count); } extent->block_count = cpu_to_be32(count); block_nr = 0; } if (!block_nr || !i) { /* * Try to free all extents and * return only last error */ return err; } i--; extent--; count = be32_to_cpu(extent->block_count); } } int hfsplus_free_fork(struct super_block *sb, u32 cnid, struct hfsplus_fork_raw *fork, int type) { struct hfs_find_data fd; hfsplus_extent_rec ext_entry; u32 total_blocks, blocks, start; int res, i; total_blocks = be32_to_cpu(fork->total_blocks); if (!total_blocks) return 0; blocks = 0; for (i = 0; i < 8; i++) blocks += be32_to_cpu(fork->extents[i].block_count); res = hfsplus_free_extents(sb, fork->extents, blocks, blocks); if (res) return res; if (total_blocks == blocks) return 0; res = hfs_find_init(HFSPLUS_SB(sb)->ext_tree, &fd); if (res) return res; do { res = __hfsplus_ext_read_extent(&fd, ext_entry, cnid, total_blocks, type); if (res) break; start = be32_to_cpu(fd.key->ext.start_block); hfsplus_free_extents(sb, ext_entry, total_blocks - start, total_blocks); hfs_brec_remove(&fd); total_blocks = start; } while (total_blocks > blocks); hfs_find_exit(&fd); return res; } int hfsplus_file_extend(struct inode *inode) { struct super_block *sb = inode->i_sb; struct hfsplus_sb_info *sbi = HFSPLUS_SB(sb); struct hfsplus_inode_info *hip = HFSPLUS_I(inode); u32 start, len, goal; int res; if (sbi->alloc_file->i_size * 8 < sbi->total_blocks - sbi->free_blocks + 8) { /* extend alloc file */ pr_err("extend alloc file! " "(%llu,%u,%u)\n", sbi->alloc_file->i_size * 8, sbi->total_blocks, sbi->free_blocks); return -ENOSPC; } mutex_lock(&hip->extents_lock); if (hip->alloc_blocks == hip->first_blocks) goal = hfsplus_ext_lastblock(hip->first_extents); else { res = hfsplus_ext_read_extent(inode, hip->alloc_blocks); if (res) goto out; goal = hfsplus_ext_lastblock(hip->cached_extents); } len = hip->clump_blocks; start = hfsplus_block_allocate(sb, sbi->total_blocks, goal, &len); if (start >= sbi->total_blocks) { start = hfsplus_block_allocate(sb, goal, 0, &len); if (start >= goal) { res = -ENOSPC; goto out; } } hfs_dbg(EXTENT, "extend %lu: %u,%u\n", inode->i_ino, start, len); if (hip->alloc_blocks <= hip->first_blocks) { if (!hip->first_blocks) { hfs_dbg(EXTENT, "first extents\n"); /* no extents yet */ hip->first_extents[0].start_block = cpu_to_be32(start); hip->first_extents[0].block_count = cpu_to_be32(len); res = 0; } else { /* try to append to extents in inode */ res = hfsplus_add_extent(hip->first_extents, hip->alloc_blocks, start, len); if (res == -ENOSPC) goto insert_extent; } if (!res) { hfsplus_dump_extent(hip->first_extents); hip->first_blocks += len; } } else { res = hfsplus_add_extent(hip->cached_extents, hip->alloc_blocks - hip->cached_start, start, len); if (!res) { hfsplus_dump_extent(hip->cached_extents); hip->extent_state |= HFSPLUS_EXT_DIRTY; hip->cached_blocks += len; } else if (res == -ENOSPC) goto insert_extent; } out: mutex_unlock(&hip->extents_lock); if (!res) { hip->alloc_blocks += len; hfsplus_mark_inode_dirty(inode, HFSPLUS_I_ALLOC_DIRTY); } return res; insert_extent: hfs_dbg(EXTENT, "insert new extent\n"); res = hfsplus_ext_write_extent_locked(inode); if (res) goto out; memset(hip->cached_extents, 0, sizeof(hfsplus_extent_rec)); hip->cached_extents[0].start_block = cpu_to_be32(start); hip->cached_extents[0].block_count = cpu_to_be32(len); hfsplus_dump_extent(hip->cached_extents); hip->extent_state |= HFSPLUS_EXT_DIRTY | HFSPLUS_EXT_NEW; hip->cached_start = hip->alloc_blocks; hip->cached_blocks = len; res = 0; goto out; } void hfsplus_file_truncate(struct inode *inode) { struct super_block *sb = inode->i_sb; struct hfsplus_inode_info *hip = HFSPLUS_I(inode); struct hfs_find_data fd; u32 alloc_cnt, blk_cnt, start; int res; hfs_dbg(INODE, "truncate: %lu, %llu -> %llu\n", inode->i_ino, (long long)hip->phys_size, inode->i_size); if (inode->i_size > hip->phys_size) { struct address_space *mapping = inode->i_mapping; struct page *page; void *fsdata; loff_t size = inode->i_size; res = pagecache_write_begin(NULL, mapping, size, 0, AOP_FLAG_UNINTERRUPTIBLE, &page, &fsdata); if (res) return; res = pagecache_write_end(NULL, mapping, size, 0, 0, page, fsdata); if (res < 0) return; mark_inode_dirty(inode); return; } else if (inode->i_size == hip->phys_size) return; blk_cnt = (inode->i_size + HFSPLUS_SB(sb)->alloc_blksz - 1) >> HFSPLUS_SB(sb)->alloc_blksz_shift; alloc_cnt = hip->alloc_blocks; if (blk_cnt == alloc_cnt) goto out; mutex_lock(&hip->extents_lock); res = hfs_find_init(HFSPLUS_SB(sb)->ext_tree, &fd); if (res) { mutex_unlock(&hip->extents_lock); /* XXX: We lack error handling of hfsplus_file_truncate() */ return; } while (1) { if (alloc_cnt == hip->first_blocks) { hfsplus_free_extents(sb, hip->first_extents, alloc_cnt, alloc_cnt - blk_cnt); hfsplus_dump_extent(hip->first_extents); hip->first_blocks = blk_cnt; break; } res = __hfsplus_ext_cache_extent(&fd, inode, alloc_cnt); if (res) break; start = hip->cached_start; hfsplus_free_extents(sb, hip->cached_extents, alloc_cnt - start, alloc_cnt - blk_cnt); hfsplus_dump_extent(hip->cached_extents); if (blk_cnt > start) { hip->extent_state |= HFSPLUS_EXT_DIRTY; break; } alloc_cnt = start; hip->cached_start = hip->cached_blocks = 0; hip->extent_state &= ~(HFSPLUS_EXT_DIRTY | HFSPLUS_EXT_NEW); hfs_brec_remove(&fd); } hfs_find_exit(&fd); mutex_unlock(&hip->extents_lock); hip->alloc_blocks = blk_cnt; out: hip->phys_size = inode->i_size; hip->fs_blocks = (inode->i_size + sb->s_blocksize - 1) >> sb->s_blocksize_bits; inode_set_bytes(inode, hip->fs_blocks << sb->s_blocksize_bits); hfsplus_mark_inode_dirty(inode, HFSPLUS_I_ALLOC_DIRTY); }
gpl-2.0
ronisbr/GT-P1000LN-GB-Kernel
drivers/infiniband/hw/mthca/mthca_memfree.c
3582
18413
/* * Copyright (c) 2004, 2005 Topspin Communications. All rights reserved. * Copyright (c) 2005 Cisco Systems. All rights reserved. * Copyright (c) 2005 Mellanox Technologies. All rights reserved. * * This software is available to you under a choice of one of two * licenses. You may choose to be licensed under the terms of the GNU * General Public License (GPL) Version 2, available from the file * COPYING in the main directory of this source tree, or the * OpenIB.org BSD license below: * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * - Redistributions of source code must retain the above * copyright notice, this list of conditions and the following * disclaimer. * * - Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include <linux/mm.h> #include <linux/scatterlist.h> #include <linux/sched.h> #include <linux/slab.h> #include <asm/page.h> #include "mthca_memfree.h" #include "mthca_dev.h" #include "mthca_cmd.h" /* * We allocate in as big chunks as we can, up to a maximum of 256 KB * per chunk. */ enum { MTHCA_ICM_ALLOC_SIZE = 1 << 18, MTHCA_TABLE_CHUNK_SIZE = 1 << 18 }; struct mthca_user_db_table { struct mutex mutex; struct { u64 uvirt; struct scatterlist mem; int refcount; } page[0]; }; static void mthca_free_icm_pages(struct mthca_dev *dev, struct mthca_icm_chunk *chunk) { int i; if (chunk->nsg > 0) pci_unmap_sg(dev->pdev, chunk->mem, chunk->npages, PCI_DMA_BIDIRECTIONAL); for (i = 0; i < chunk->npages; ++i) __free_pages(sg_page(&chunk->mem[i]), get_order(chunk->mem[i].length)); } static void mthca_free_icm_coherent(struct mthca_dev *dev, struct mthca_icm_chunk *chunk) { int i; for (i = 0; i < chunk->npages; ++i) { dma_free_coherent(&dev->pdev->dev, chunk->mem[i].length, lowmem_page_address(sg_page(&chunk->mem[i])), sg_dma_address(&chunk->mem[i])); } } void mthca_free_icm(struct mthca_dev *dev, struct mthca_icm *icm, int coherent) { struct mthca_icm_chunk *chunk, *tmp; if (!icm) return; list_for_each_entry_safe(chunk, tmp, &icm->chunk_list, list) { if (coherent) mthca_free_icm_coherent(dev, chunk); else mthca_free_icm_pages(dev, chunk); kfree(chunk); } kfree(icm); } static int mthca_alloc_icm_pages(struct scatterlist *mem, int order, gfp_t gfp_mask) { struct page *page; /* * Use __GFP_ZERO because buggy firmware assumes ICM pages are * cleared, and subtle failures are seen if they aren't. */ page = alloc_pages(gfp_mask | __GFP_ZERO, order); if (!page) return -ENOMEM; sg_set_page(mem, page, PAGE_SIZE << order, 0); return 0; } static int mthca_alloc_icm_coherent(struct device *dev, struct scatterlist *mem, int order, gfp_t gfp_mask) { void *buf = dma_alloc_coherent(dev, PAGE_SIZE << order, &sg_dma_address(mem), gfp_mask); if (!buf) return -ENOMEM; sg_set_buf(mem, buf, PAGE_SIZE << order); BUG_ON(mem->offset); sg_dma_len(mem) = PAGE_SIZE << order; return 0; } struct mthca_icm *mthca_alloc_icm(struct mthca_dev *dev, int npages, gfp_t gfp_mask, int coherent) { struct mthca_icm *icm; struct mthca_icm_chunk *chunk = NULL; int cur_order; int ret; /* We use sg_set_buf for coherent allocs, which assumes low memory */ BUG_ON(coherent && (gfp_mask & __GFP_HIGHMEM)); icm = kmalloc(sizeof *icm, gfp_mask & ~(__GFP_HIGHMEM | __GFP_NOWARN)); if (!icm) return icm; icm->refcount = 0; INIT_LIST_HEAD(&icm->chunk_list); cur_order = get_order(MTHCA_ICM_ALLOC_SIZE); while (npages > 0) { if (!chunk) { chunk = kmalloc(sizeof *chunk, gfp_mask & ~(__GFP_HIGHMEM | __GFP_NOWARN)); if (!chunk) goto fail; sg_init_table(chunk->mem, MTHCA_ICM_CHUNK_LEN); chunk->npages = 0; chunk->nsg = 0; list_add_tail(&chunk->list, &icm->chunk_list); } while (1 << cur_order > npages) --cur_order; if (coherent) ret = mthca_alloc_icm_coherent(&dev->pdev->dev, &chunk->mem[chunk->npages], cur_order, gfp_mask); else ret = mthca_alloc_icm_pages(&chunk->mem[chunk->npages], cur_order, gfp_mask); if (!ret) { ++chunk->npages; if (coherent) ++chunk->nsg; else if (chunk->npages == MTHCA_ICM_CHUNK_LEN) { chunk->nsg = pci_map_sg(dev->pdev, chunk->mem, chunk->npages, PCI_DMA_BIDIRECTIONAL); if (chunk->nsg <= 0) goto fail; } if (chunk->npages == MTHCA_ICM_CHUNK_LEN) chunk = NULL; npages -= 1 << cur_order; } else { --cur_order; if (cur_order < 0) goto fail; } } if (!coherent && chunk) { chunk->nsg = pci_map_sg(dev->pdev, chunk->mem, chunk->npages, PCI_DMA_BIDIRECTIONAL); if (chunk->nsg <= 0) goto fail; } return icm; fail: mthca_free_icm(dev, icm, coherent); return NULL; } int mthca_table_get(struct mthca_dev *dev, struct mthca_icm_table *table, int obj) { int i = (obj & (table->num_obj - 1)) * table->obj_size / MTHCA_TABLE_CHUNK_SIZE; int ret = 0; u8 status; mutex_lock(&table->mutex); if (table->icm[i]) { ++table->icm[i]->refcount; goto out; } table->icm[i] = mthca_alloc_icm(dev, MTHCA_TABLE_CHUNK_SIZE >> PAGE_SHIFT, (table->lowmem ? GFP_KERNEL : GFP_HIGHUSER) | __GFP_NOWARN, table->coherent); if (!table->icm[i]) { ret = -ENOMEM; goto out; } if (mthca_MAP_ICM(dev, table->icm[i], table->virt + i * MTHCA_TABLE_CHUNK_SIZE, &status) || status) { mthca_free_icm(dev, table->icm[i], table->coherent); table->icm[i] = NULL; ret = -ENOMEM; goto out; } ++table->icm[i]->refcount; out: mutex_unlock(&table->mutex); return ret; } void mthca_table_put(struct mthca_dev *dev, struct mthca_icm_table *table, int obj) { int i; u8 status; if (!mthca_is_memfree(dev)) return; i = (obj & (table->num_obj - 1)) * table->obj_size / MTHCA_TABLE_CHUNK_SIZE; mutex_lock(&table->mutex); if (--table->icm[i]->refcount == 0) { mthca_UNMAP_ICM(dev, table->virt + i * MTHCA_TABLE_CHUNK_SIZE, MTHCA_TABLE_CHUNK_SIZE / MTHCA_ICM_PAGE_SIZE, &status); mthca_free_icm(dev, table->icm[i], table->coherent); table->icm[i] = NULL; } mutex_unlock(&table->mutex); } void *mthca_table_find(struct mthca_icm_table *table, int obj, dma_addr_t *dma_handle) { int idx, offset, dma_offset, i; struct mthca_icm_chunk *chunk; struct mthca_icm *icm; struct page *page = NULL; if (!table->lowmem) return NULL; mutex_lock(&table->mutex); idx = (obj & (table->num_obj - 1)) * table->obj_size; icm = table->icm[idx / MTHCA_TABLE_CHUNK_SIZE]; dma_offset = offset = idx % MTHCA_TABLE_CHUNK_SIZE; if (!icm) goto out; list_for_each_entry(chunk, &icm->chunk_list, list) { for (i = 0; i < chunk->npages; ++i) { if (dma_handle && dma_offset >= 0) { if (sg_dma_len(&chunk->mem[i]) > dma_offset) *dma_handle = sg_dma_address(&chunk->mem[i]) + dma_offset; dma_offset -= sg_dma_len(&chunk->mem[i]); } /* DMA mapping can merge pages but not split them, * so if we found the page, dma_handle has already * been assigned to. */ if (chunk->mem[i].length > offset) { page = sg_page(&chunk->mem[i]); goto out; } offset -= chunk->mem[i].length; } } out: mutex_unlock(&table->mutex); return page ? lowmem_page_address(page) + offset : NULL; } int mthca_table_get_range(struct mthca_dev *dev, struct mthca_icm_table *table, int start, int end) { int inc = MTHCA_TABLE_CHUNK_SIZE / table->obj_size; int i, err; for (i = start; i <= end; i += inc) { err = mthca_table_get(dev, table, i); if (err) goto fail; } return 0; fail: while (i > start) { i -= inc; mthca_table_put(dev, table, i); } return err; } void mthca_table_put_range(struct mthca_dev *dev, struct mthca_icm_table *table, int start, int end) { int i; if (!mthca_is_memfree(dev)) return; for (i = start; i <= end; i += MTHCA_TABLE_CHUNK_SIZE / table->obj_size) mthca_table_put(dev, table, i); } struct mthca_icm_table *mthca_alloc_icm_table(struct mthca_dev *dev, u64 virt, int obj_size, int nobj, int reserved, int use_lowmem, int use_coherent) { struct mthca_icm_table *table; int obj_per_chunk; int num_icm; unsigned chunk_size; int i; u8 status; obj_per_chunk = MTHCA_TABLE_CHUNK_SIZE / obj_size; num_icm = DIV_ROUND_UP(nobj, obj_per_chunk); table = kmalloc(sizeof *table + num_icm * sizeof *table->icm, GFP_KERNEL); if (!table) return NULL; table->virt = virt; table->num_icm = num_icm; table->num_obj = nobj; table->obj_size = obj_size; table->lowmem = use_lowmem; table->coherent = use_coherent; mutex_init(&table->mutex); for (i = 0; i < num_icm; ++i) table->icm[i] = NULL; for (i = 0; i * MTHCA_TABLE_CHUNK_SIZE < reserved * obj_size; ++i) { chunk_size = MTHCA_TABLE_CHUNK_SIZE; if ((i + 1) * MTHCA_TABLE_CHUNK_SIZE > nobj * obj_size) chunk_size = nobj * obj_size - i * MTHCA_TABLE_CHUNK_SIZE; table->icm[i] = mthca_alloc_icm(dev, chunk_size >> PAGE_SHIFT, (use_lowmem ? GFP_KERNEL : GFP_HIGHUSER) | __GFP_NOWARN, use_coherent); if (!table->icm[i]) goto err; if (mthca_MAP_ICM(dev, table->icm[i], virt + i * MTHCA_TABLE_CHUNK_SIZE, &status) || status) { mthca_free_icm(dev, table->icm[i], table->coherent); table->icm[i] = NULL; goto err; } /* * Add a reference to this ICM chunk so that it never * gets freed (since it contains reserved firmware objects). */ ++table->icm[i]->refcount; } return table; err: for (i = 0; i < num_icm; ++i) if (table->icm[i]) { mthca_UNMAP_ICM(dev, virt + i * MTHCA_TABLE_CHUNK_SIZE, MTHCA_TABLE_CHUNK_SIZE / MTHCA_ICM_PAGE_SIZE, &status); mthca_free_icm(dev, table->icm[i], table->coherent); } kfree(table); return NULL; } void mthca_free_icm_table(struct mthca_dev *dev, struct mthca_icm_table *table) { int i; u8 status; for (i = 0; i < table->num_icm; ++i) if (table->icm[i]) { mthca_UNMAP_ICM(dev, table->virt + i * MTHCA_TABLE_CHUNK_SIZE, MTHCA_TABLE_CHUNK_SIZE / MTHCA_ICM_PAGE_SIZE, &status); mthca_free_icm(dev, table->icm[i], table->coherent); } kfree(table); } static u64 mthca_uarc_virt(struct mthca_dev *dev, struct mthca_uar *uar, int page) { return dev->uar_table.uarc_base + uar->index * dev->uar_table.uarc_size + page * MTHCA_ICM_PAGE_SIZE; } int mthca_map_user_db(struct mthca_dev *dev, struct mthca_uar *uar, struct mthca_user_db_table *db_tab, int index, u64 uaddr) { struct page *pages[1]; int ret = 0; u8 status; int i; if (!mthca_is_memfree(dev)) return 0; if (index < 0 || index > dev->uar_table.uarc_size / 8) return -EINVAL; mutex_lock(&db_tab->mutex); i = index / MTHCA_DB_REC_PER_PAGE; if ((db_tab->page[i].refcount >= MTHCA_DB_REC_PER_PAGE) || (db_tab->page[i].uvirt && db_tab->page[i].uvirt != uaddr) || (uaddr & 4095)) { ret = -EINVAL; goto out; } if (db_tab->page[i].refcount) { ++db_tab->page[i].refcount; goto out; } ret = get_user_pages(current, current->mm, uaddr & PAGE_MASK, 1, 1, 0, pages, NULL); if (ret < 0) goto out; sg_set_page(&db_tab->page[i].mem, pages[0], MTHCA_ICM_PAGE_SIZE, uaddr & ~PAGE_MASK); ret = pci_map_sg(dev->pdev, &db_tab->page[i].mem, 1, PCI_DMA_TODEVICE); if (ret < 0) { put_page(pages[0]); goto out; } ret = mthca_MAP_ICM_page(dev, sg_dma_address(&db_tab->page[i].mem), mthca_uarc_virt(dev, uar, i), &status); if (!ret && status) ret = -EINVAL; if (ret) { pci_unmap_sg(dev->pdev, &db_tab->page[i].mem, 1, PCI_DMA_TODEVICE); put_page(sg_page(&db_tab->page[i].mem)); goto out; } db_tab->page[i].uvirt = uaddr; db_tab->page[i].refcount = 1; out: mutex_unlock(&db_tab->mutex); return ret; } void mthca_unmap_user_db(struct mthca_dev *dev, struct mthca_uar *uar, struct mthca_user_db_table *db_tab, int index) { if (!mthca_is_memfree(dev)) return; /* * To make our bookkeeping simpler, we don't unmap DB * pages until we clean up the whole db table. */ mutex_lock(&db_tab->mutex); --db_tab->page[index / MTHCA_DB_REC_PER_PAGE].refcount; mutex_unlock(&db_tab->mutex); } struct mthca_user_db_table *mthca_init_user_db_tab(struct mthca_dev *dev) { struct mthca_user_db_table *db_tab; int npages; int i; if (!mthca_is_memfree(dev)) return NULL; npages = dev->uar_table.uarc_size / MTHCA_ICM_PAGE_SIZE; db_tab = kmalloc(sizeof *db_tab + npages * sizeof *db_tab->page, GFP_KERNEL); if (!db_tab) return ERR_PTR(-ENOMEM); mutex_init(&db_tab->mutex); for (i = 0; i < npages; ++i) { db_tab->page[i].refcount = 0; db_tab->page[i].uvirt = 0; sg_init_table(&db_tab->page[i].mem, 1); } return db_tab; } void mthca_cleanup_user_db_tab(struct mthca_dev *dev, struct mthca_uar *uar, struct mthca_user_db_table *db_tab) { int i; u8 status; if (!mthca_is_memfree(dev)) return; for (i = 0; i < dev->uar_table.uarc_size / MTHCA_ICM_PAGE_SIZE; ++i) { if (db_tab->page[i].uvirt) { mthca_UNMAP_ICM(dev, mthca_uarc_virt(dev, uar, i), 1, &status); pci_unmap_sg(dev->pdev, &db_tab->page[i].mem, 1, PCI_DMA_TODEVICE); put_page(sg_page(&db_tab->page[i].mem)); } } kfree(db_tab); } int mthca_alloc_db(struct mthca_dev *dev, enum mthca_db_type type, u32 qn, __be32 **db) { int group; int start, end, dir; int i, j; struct mthca_db_page *page; int ret = 0; u8 status; mutex_lock(&dev->db_tab->mutex); switch (type) { case MTHCA_DB_TYPE_CQ_ARM: case MTHCA_DB_TYPE_SQ: group = 0; start = 0; end = dev->db_tab->max_group1; dir = 1; break; case MTHCA_DB_TYPE_CQ_SET_CI: case MTHCA_DB_TYPE_RQ: case MTHCA_DB_TYPE_SRQ: group = 1; start = dev->db_tab->npages - 1; end = dev->db_tab->min_group2; dir = -1; break; default: ret = -EINVAL; goto out; } for (i = start; i != end; i += dir) if (dev->db_tab->page[i].db_rec && !bitmap_full(dev->db_tab->page[i].used, MTHCA_DB_REC_PER_PAGE)) { page = dev->db_tab->page + i; goto found; } for (i = start; i != end; i += dir) if (!dev->db_tab->page[i].db_rec) { page = dev->db_tab->page + i; goto alloc; } if (dev->db_tab->max_group1 >= dev->db_tab->min_group2 - 1) { ret = -ENOMEM; goto out; } if (group == 0) ++dev->db_tab->max_group1; else --dev->db_tab->min_group2; page = dev->db_tab->page + end; alloc: page->db_rec = dma_alloc_coherent(&dev->pdev->dev, MTHCA_ICM_PAGE_SIZE, &page->mapping, GFP_KERNEL); if (!page->db_rec) { ret = -ENOMEM; goto out; } memset(page->db_rec, 0, MTHCA_ICM_PAGE_SIZE); ret = mthca_MAP_ICM_page(dev, page->mapping, mthca_uarc_virt(dev, &dev->driver_uar, i), &status); if (!ret && status) ret = -EINVAL; if (ret) { dma_free_coherent(&dev->pdev->dev, MTHCA_ICM_PAGE_SIZE, page->db_rec, page->mapping); goto out; } bitmap_zero(page->used, MTHCA_DB_REC_PER_PAGE); found: j = find_first_zero_bit(page->used, MTHCA_DB_REC_PER_PAGE); set_bit(j, page->used); if (group == 1) j = MTHCA_DB_REC_PER_PAGE - 1 - j; ret = i * MTHCA_DB_REC_PER_PAGE + j; page->db_rec[j] = cpu_to_be64((qn << 8) | (type << 5)); *db = (__be32 *) &page->db_rec[j]; out: mutex_unlock(&dev->db_tab->mutex); return ret; } void mthca_free_db(struct mthca_dev *dev, int type, int db_index) { int i, j; struct mthca_db_page *page; u8 status; i = db_index / MTHCA_DB_REC_PER_PAGE; j = db_index % MTHCA_DB_REC_PER_PAGE; page = dev->db_tab->page + i; mutex_lock(&dev->db_tab->mutex); page->db_rec[j] = 0; if (i >= dev->db_tab->min_group2) j = MTHCA_DB_REC_PER_PAGE - 1 - j; clear_bit(j, page->used); if (bitmap_empty(page->used, MTHCA_DB_REC_PER_PAGE) && i >= dev->db_tab->max_group1 - 1) { mthca_UNMAP_ICM(dev, mthca_uarc_virt(dev, &dev->driver_uar, i), 1, &status); dma_free_coherent(&dev->pdev->dev, MTHCA_ICM_PAGE_SIZE, page->db_rec, page->mapping); page->db_rec = NULL; if (i == dev->db_tab->max_group1) { --dev->db_tab->max_group1; /* XXX may be able to unmap more pages now */ } if (i == dev->db_tab->min_group2) ++dev->db_tab->min_group2; } mutex_unlock(&dev->db_tab->mutex); } int mthca_init_db_tab(struct mthca_dev *dev) { int i; if (!mthca_is_memfree(dev)) return 0; dev->db_tab = kmalloc(sizeof *dev->db_tab, GFP_KERNEL); if (!dev->db_tab) return -ENOMEM; mutex_init(&dev->db_tab->mutex); dev->db_tab->npages = dev->uar_table.uarc_size / MTHCA_ICM_PAGE_SIZE; dev->db_tab->max_group1 = 0; dev->db_tab->min_group2 = dev->db_tab->npages - 1; dev->db_tab->page = kmalloc(dev->db_tab->npages * sizeof *dev->db_tab->page, GFP_KERNEL); if (!dev->db_tab->page) { kfree(dev->db_tab); return -ENOMEM; } for (i = 0; i < dev->db_tab->npages; ++i) dev->db_tab->page[i].db_rec = NULL; return 0; } void mthca_cleanup_db_tab(struct mthca_dev *dev) { int i; u8 status; if (!mthca_is_memfree(dev)) return; /* * Because we don't always free our UARC pages when they * become empty to make mthca_free_db() simpler we need to * make a sweep through the doorbell pages and free any * leftover pages now. */ for (i = 0; i < dev->db_tab->npages; ++i) { if (!dev->db_tab->page[i].db_rec) continue; if (!bitmap_empty(dev->db_tab->page[i].used, MTHCA_DB_REC_PER_PAGE)) mthca_warn(dev, "Kernel UARC page %d not empty\n", i); mthca_UNMAP_ICM(dev, mthca_uarc_virt(dev, &dev->driver_uar, i), 1, &status); dma_free_coherent(&dev->pdev->dev, MTHCA_ICM_PAGE_SIZE, dev->db_tab->page[i].db_rec, dev->db_tab->page[i].mapping); } kfree(dev->db_tab->page); kfree(dev->db_tab); }
gpl-2.0
omonar/linux
arch/mips/pci/fixup-tb0287.c
4350
1630
/* * fixup-tb0287.c, The TANBAC TB0287 specific PCI fixups. * * Copyright (C) 2005 Yoichi Yuasa <yuasa@linux-mips.org> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <linux/init.h> #include <linux/pci.h> #include <asm/vr41xx/tb0287.h> int __init pcibios_map_irq(const struct pci_dev *dev, u8 slot, u8 pin) { unsigned char bus; int irq = -1; bus = dev->bus->number; if (bus == 0) { switch (slot) { case 16: irq = TB0287_SM501_IRQ; break; case 17: irq = TB0287_SIL680A_IRQ; break; default: break; } } else if (bus == 1) { switch (PCI_SLOT(dev->devfn)) { case 0: irq = TB0287_PCI_SLOT_IRQ; break; case 2: case 3: irq = TB0287_RTL8110_IRQ; break; default: break; } } else if (bus > 1) { irq = TB0287_PCI_SLOT_IRQ; } return irq; } /* Do platform specific device initialization at pci_enable_device() time */ int pcibios_plat_dev_init(struct pci_dev *dev) { return 0; }
gpl-2.0
mifl/android_kernel_pantech_oscar
arch/mips/kernel/signal.c
4350
17911
/* * This file is subject to the terms and conditions of the GNU General Public * License. See the file "COPYING" in the main directory of this archive * for more details. * * Copyright (C) 1991, 1992 Linus Torvalds * Copyright (C) 1994 - 2000 Ralf Baechle * Copyright (C) 1999, 2000 Silicon Graphics, Inc. */ #include <linux/cache.h> #include <linux/irqflags.h> #include <linux/sched.h> #include <linux/mm.h> #include <linux/personality.h> #include <linux/smp.h> #include <linux/kernel.h> #include <linux/signal.h> #include <linux/errno.h> #include <linux/wait.h> #include <linux/ptrace.h> #include <linux/unistd.h> #include <linux/compiler.h> #include <linux/syscalls.h> #include <linux/uaccess.h> #include <linux/tracehook.h> #include <asm/abi.h> #include <asm/asm.h> #include <linux/bitops.h> #include <asm/cacheflush.h> #include <asm/fpu.h> #include <asm/sim.h> #include <asm/ucontext.h> #include <asm/cpu-features.h> #include <asm/war.h> #include <asm/vdso.h> #include <asm/dsp.h> #include "signal-common.h" static int (*save_fp_context)(struct sigcontext __user *sc); static int (*restore_fp_context)(struct sigcontext __user *sc); extern asmlinkage int _save_fp_context(struct sigcontext __user *sc); extern asmlinkage int _restore_fp_context(struct sigcontext __user *sc); extern asmlinkage int fpu_emulator_save_context(struct sigcontext __user *sc); extern asmlinkage int fpu_emulator_restore_context(struct sigcontext __user *sc); struct sigframe { u32 sf_ass[4]; /* argument save space for o32 */ u32 sf_pad[2]; /* Was: signal trampoline */ struct sigcontext sf_sc; sigset_t sf_mask; }; struct rt_sigframe { u32 rs_ass[4]; /* argument save space for o32 */ u32 rs_pad[2]; /* Was: signal trampoline */ struct siginfo rs_info; struct ucontext rs_uc; }; /* * Helper routines */ static int protected_save_fp_context(struct sigcontext __user *sc) { int err; while (1) { lock_fpu_owner(); own_fpu_inatomic(1); err = save_fp_context(sc); /* this might fail */ unlock_fpu_owner(); if (likely(!err)) break; /* touch the sigcontext and try again */ err = __put_user(0, &sc->sc_fpregs[0]) | __put_user(0, &sc->sc_fpregs[31]) | __put_user(0, &sc->sc_fpc_csr); if (err) break; /* really bad sigcontext */ } return err; } static int protected_restore_fp_context(struct sigcontext __user *sc) { int err, tmp __maybe_unused; while (1) { lock_fpu_owner(); own_fpu_inatomic(0); err = restore_fp_context(sc); /* this might fail */ unlock_fpu_owner(); if (likely(!err)) break; /* touch the sigcontext and try again */ err = __get_user(tmp, &sc->sc_fpregs[0]) | __get_user(tmp, &sc->sc_fpregs[31]) | __get_user(tmp, &sc->sc_fpc_csr); if (err) break; /* really bad sigcontext */ } return err; } int setup_sigcontext(struct pt_regs *regs, struct sigcontext __user *sc) { int err = 0; int i; unsigned int used_math; err |= __put_user(regs->cp0_epc, &sc->sc_pc); err |= __put_user(0, &sc->sc_regs[0]); for (i = 1; i < 32; i++) err |= __put_user(regs->regs[i], &sc->sc_regs[i]); #ifdef CONFIG_CPU_HAS_SMARTMIPS err |= __put_user(regs->acx, &sc->sc_acx); #endif err |= __put_user(regs->hi, &sc->sc_mdhi); err |= __put_user(regs->lo, &sc->sc_mdlo); if (cpu_has_dsp) { err |= __put_user(mfhi1(), &sc->sc_hi1); err |= __put_user(mflo1(), &sc->sc_lo1); err |= __put_user(mfhi2(), &sc->sc_hi2); err |= __put_user(mflo2(), &sc->sc_lo2); err |= __put_user(mfhi3(), &sc->sc_hi3); err |= __put_user(mflo3(), &sc->sc_lo3); err |= __put_user(rddsp(DSP_MASK), &sc->sc_dsp); } used_math = !!used_math(); err |= __put_user(used_math, &sc->sc_used_math); if (used_math) { /* * Save FPU state to signal context. Signal handler * will "inherit" current FPU state. */ err |= protected_save_fp_context(sc); } return err; } int fpcsr_pending(unsigned int __user *fpcsr) { int err, sig = 0; unsigned int csr, enabled; err = __get_user(csr, fpcsr); enabled = FPU_CSR_UNI_X | ((csr & FPU_CSR_ALL_E) << 5); /* * If the signal handler set some FPU exceptions, clear it and * send SIGFPE. */ if (csr & enabled) { csr &= ~enabled; err |= __put_user(csr, fpcsr); sig = SIGFPE; } return err ?: sig; } static int check_and_restore_fp_context(struct sigcontext __user *sc) { int err, sig; err = sig = fpcsr_pending(&sc->sc_fpc_csr); if (err > 0) err = 0; err |= protected_restore_fp_context(sc); return err ?: sig; } int restore_sigcontext(struct pt_regs *regs, struct sigcontext __user *sc) { unsigned int used_math; unsigned long treg; int err = 0; int i; /* Always make any pending restarted system calls return -EINTR */ current_thread_info()->restart_block.fn = do_no_restart_syscall; err |= __get_user(regs->cp0_epc, &sc->sc_pc); #ifdef CONFIG_CPU_HAS_SMARTMIPS err |= __get_user(regs->acx, &sc->sc_acx); #endif err |= __get_user(regs->hi, &sc->sc_mdhi); err |= __get_user(regs->lo, &sc->sc_mdlo); if (cpu_has_dsp) { err |= __get_user(treg, &sc->sc_hi1); mthi1(treg); err |= __get_user(treg, &sc->sc_lo1); mtlo1(treg); err |= __get_user(treg, &sc->sc_hi2); mthi2(treg); err |= __get_user(treg, &sc->sc_lo2); mtlo2(treg); err |= __get_user(treg, &sc->sc_hi3); mthi3(treg); err |= __get_user(treg, &sc->sc_lo3); mtlo3(treg); err |= __get_user(treg, &sc->sc_dsp); wrdsp(treg, DSP_MASK); } for (i = 1; i < 32; i++) err |= __get_user(regs->regs[i], &sc->sc_regs[i]); err |= __get_user(used_math, &sc->sc_used_math); conditional_used_math(used_math); if (used_math) { /* restore fpu context if we have used it before */ if (!err) err = check_and_restore_fp_context(sc); } else { /* signal handler may have used FPU. Give it up. */ lose_fpu(0); } return err; } void __user *get_sigframe(struct k_sigaction *ka, struct pt_regs *regs, size_t frame_size) { unsigned long sp; /* Default to using normal stack */ sp = regs->regs[29]; /* * FPU emulator may have it's own trampoline active just * above the user stack, 16-bytes before the next lowest * 16 byte boundary. Try to avoid trashing it. */ sp -= 32; /* This is the X/Open sanctioned signal stack switching. */ if ((ka->sa.sa_flags & SA_ONSTACK) && (sas_ss_flags (sp) == 0)) sp = current->sas_ss_sp + current->sas_ss_size; return (void __user *)((sp - frame_size) & (ICACHE_REFILLS_WORKAROUND_WAR ? ~(cpu_icache_line_size()-1) : ALMASK)); } /* * Atomically swap in the new signal mask, and wait for a signal. */ #ifdef CONFIG_TRAD_SIGNALS asmlinkage int sys_sigsuspend(nabi_no_regargs struct pt_regs regs) { sigset_t newset; sigset_t __user *uset; uset = (sigset_t __user *) regs.regs[4]; if (copy_from_user(&newset, uset, sizeof(sigset_t))) return -EFAULT; sigdelsetmask(&newset, ~_BLOCKABLE); current->saved_sigmask = current->blocked; set_current_blocked(&newset); current->state = TASK_INTERRUPTIBLE; schedule(); set_thread_flag(TIF_RESTORE_SIGMASK); return -ERESTARTNOHAND; } #endif asmlinkage int sys_rt_sigsuspend(nabi_no_regargs struct pt_regs regs) { sigset_t newset; sigset_t __user *unewset; size_t sigsetsize; /* XXX Don't preclude handling different sized sigset_t's. */ sigsetsize = regs.regs[5]; if (sigsetsize != sizeof(sigset_t)) return -EINVAL; unewset = (sigset_t __user *) regs.regs[4]; if (copy_from_user(&newset, unewset, sizeof(newset))) return -EFAULT; sigdelsetmask(&newset, ~_BLOCKABLE); current->saved_sigmask = current->blocked; set_current_blocked(&newset); current->state = TASK_INTERRUPTIBLE; schedule(); set_thread_flag(TIF_RESTORE_SIGMASK); return -ERESTARTNOHAND; } #ifdef CONFIG_TRAD_SIGNALS SYSCALL_DEFINE3(sigaction, int, sig, const struct sigaction __user *, act, struct sigaction __user *, oact) { struct k_sigaction new_ka, old_ka; int ret; int err = 0; if (act) { old_sigset_t mask; if (!access_ok(VERIFY_READ, act, sizeof(*act))) return -EFAULT; err |= __get_user(new_ka.sa.sa_handler, &act->sa_handler); err |= __get_user(new_ka.sa.sa_flags, &act->sa_flags); err |= __get_user(mask, &act->sa_mask.sig[0]); if (err) return -EFAULT; siginitset(&new_ka.sa.sa_mask, mask); } ret = do_sigaction(sig, act ? &new_ka : NULL, oact ? &old_ka : NULL); if (!ret && oact) { if (!access_ok(VERIFY_WRITE, oact, sizeof(*oact))) return -EFAULT; err |= __put_user(old_ka.sa.sa_flags, &oact->sa_flags); err |= __put_user(old_ka.sa.sa_handler, &oact->sa_handler); err |= __put_user(old_ka.sa.sa_mask.sig[0], oact->sa_mask.sig); err |= __put_user(0, &oact->sa_mask.sig[1]); err |= __put_user(0, &oact->sa_mask.sig[2]); err |= __put_user(0, &oact->sa_mask.sig[3]); if (err) return -EFAULT; } return ret; } #endif asmlinkage int sys_sigaltstack(nabi_no_regargs struct pt_regs regs) { const stack_t __user *uss = (const stack_t __user *) regs.regs[4]; stack_t __user *uoss = (stack_t __user *) regs.regs[5]; unsigned long usp = regs.regs[29]; return do_sigaltstack(uss, uoss, usp); } #ifdef CONFIG_TRAD_SIGNALS asmlinkage void sys_sigreturn(nabi_no_regargs struct pt_regs regs) { struct sigframe __user *frame; sigset_t blocked; int sig; frame = (struct sigframe __user *) regs.regs[29]; if (!access_ok(VERIFY_READ, frame, sizeof(*frame))) goto badframe; if (__copy_from_user(&blocked, &frame->sf_mask, sizeof(blocked))) goto badframe; sigdelsetmask(&blocked, ~_BLOCKABLE); set_current_blocked(&blocked); sig = restore_sigcontext(&regs, &frame->sf_sc); if (sig < 0) goto badframe; else if (sig) force_sig(sig, current); /* * Don't let your children do this ... */ __asm__ __volatile__( "move\t$29, %0\n\t" "j\tsyscall_exit" :/* no outputs */ :"r" (&regs)); /* Unreached */ badframe: force_sig(SIGSEGV, current); } #endif /* CONFIG_TRAD_SIGNALS */ asmlinkage void sys_rt_sigreturn(nabi_no_regargs struct pt_regs regs) { struct rt_sigframe __user *frame; sigset_t set; int sig; frame = (struct rt_sigframe __user *) regs.regs[29]; if (!access_ok(VERIFY_READ, frame, sizeof(*frame))) goto badframe; if (__copy_from_user(&set, &frame->rs_uc.uc_sigmask, sizeof(set))) goto badframe; sigdelsetmask(&set, ~_BLOCKABLE); set_current_blocked(&set); sig = restore_sigcontext(&regs, &frame->rs_uc.uc_mcontext); if (sig < 0) goto badframe; else if (sig) force_sig(sig, current); /* It is more difficult to avoid calling this function than to call it and ignore errors. */ do_sigaltstack(&frame->rs_uc.uc_stack, NULL, regs.regs[29]); /* * Don't let your children do this ... */ __asm__ __volatile__( "move\t$29, %0\n\t" "j\tsyscall_exit" :/* no outputs */ :"r" (&regs)); /* Unreached */ badframe: force_sig(SIGSEGV, current); } #ifdef CONFIG_TRAD_SIGNALS static int setup_frame(void *sig_return, struct k_sigaction *ka, struct pt_regs *regs, int signr, sigset_t *set) { struct sigframe __user *frame; int err = 0; frame = get_sigframe(ka, regs, sizeof(*frame)); if (!access_ok(VERIFY_WRITE, frame, sizeof (*frame))) goto give_sigsegv; err |= setup_sigcontext(regs, &frame->sf_sc); err |= __copy_to_user(&frame->sf_mask, set, sizeof(*set)); if (err) goto give_sigsegv; /* * Arguments to signal handler: * * a0 = signal number * a1 = 0 (should be cause) * a2 = pointer to struct sigcontext * * $25 and c0_epc point to the signal handler, $29 points to the * struct sigframe. */ regs->regs[ 4] = signr; regs->regs[ 5] = 0; regs->regs[ 6] = (unsigned long) &frame->sf_sc; regs->regs[29] = (unsigned long) frame; regs->regs[31] = (unsigned long) sig_return; regs->cp0_epc = regs->regs[25] = (unsigned long) ka->sa.sa_handler; DEBUGP("SIG deliver (%s:%d): sp=0x%p pc=0x%lx ra=0x%lx\n", current->comm, current->pid, frame, regs->cp0_epc, regs->regs[31]); return 0; give_sigsegv: force_sigsegv(signr, current); return -EFAULT; } #endif static int setup_rt_frame(void *sig_return, struct k_sigaction *ka, struct pt_regs *regs, int signr, sigset_t *set, siginfo_t *info) { struct rt_sigframe __user *frame; int err = 0; frame = get_sigframe(ka, regs, sizeof(*frame)); if (!access_ok(VERIFY_WRITE, frame, sizeof (*frame))) goto give_sigsegv; /* Create siginfo. */ err |= copy_siginfo_to_user(&frame->rs_info, info); /* Create the ucontext. */ err |= __put_user(0, &frame->rs_uc.uc_flags); err |= __put_user(NULL, &frame->rs_uc.uc_link); err |= __put_user((void __user *)current->sas_ss_sp, &frame->rs_uc.uc_stack.ss_sp); err |= __put_user(sas_ss_flags(regs->regs[29]), &frame->rs_uc.uc_stack.ss_flags); err |= __put_user(current->sas_ss_size, &frame->rs_uc.uc_stack.ss_size); err |= setup_sigcontext(regs, &frame->rs_uc.uc_mcontext); err |= __copy_to_user(&frame->rs_uc.uc_sigmask, set, sizeof(*set)); if (err) goto give_sigsegv; /* * Arguments to signal handler: * * a0 = signal number * a1 = 0 (should be cause) * a2 = pointer to ucontext * * $25 and c0_epc point to the signal handler, $29 points to * the struct rt_sigframe. */ regs->regs[ 4] = signr; regs->regs[ 5] = (unsigned long) &frame->rs_info; regs->regs[ 6] = (unsigned long) &frame->rs_uc; regs->regs[29] = (unsigned long) frame; regs->regs[31] = (unsigned long) sig_return; regs->cp0_epc = regs->regs[25] = (unsigned long) ka->sa.sa_handler; DEBUGP("SIG deliver (%s:%d): sp=0x%p pc=0x%lx ra=0x%lx\n", current->comm, current->pid, frame, regs->cp0_epc, regs->regs[31]); return 0; give_sigsegv: force_sigsegv(signr, current); return -EFAULT; } struct mips_abi mips_abi = { #ifdef CONFIG_TRAD_SIGNALS .setup_frame = setup_frame, .signal_return_offset = offsetof(struct mips_vdso, signal_trampoline), #endif .setup_rt_frame = setup_rt_frame, .rt_signal_return_offset = offsetof(struct mips_vdso, rt_signal_trampoline), .restart = __NR_restart_syscall }; static int handle_signal(unsigned long sig, siginfo_t *info, struct k_sigaction *ka, sigset_t *oldset, struct pt_regs *regs) { int ret; struct mips_abi *abi = current->thread.abi; void *vdso = current->mm->context.vdso; if (regs->regs[0]) { switch(regs->regs[2]) { case ERESTART_RESTARTBLOCK: case ERESTARTNOHAND: regs->regs[2] = EINTR; break; case ERESTARTSYS: if (!(ka->sa.sa_flags & SA_RESTART)) { regs->regs[2] = EINTR; break; } /* fallthrough */ case ERESTARTNOINTR: regs->regs[7] = regs->regs[26]; regs->regs[2] = regs->regs[0]; regs->cp0_epc -= 4; } regs->regs[0] = 0; /* Don't deal with this again. */ } if (sig_uses_siginfo(ka)) ret = abi->setup_rt_frame(vdso + abi->rt_signal_return_offset, ka, regs, sig, oldset, info); else ret = abi->setup_frame(vdso + abi->signal_return_offset, ka, regs, sig, oldset); if (ret) return ret; block_sigmask(ka, sig); return ret; } static void do_signal(struct pt_regs *regs) { struct k_sigaction ka; sigset_t *oldset; siginfo_t info; int signr; /* * We want the common case to go fast, which is why we may in certain * cases get here from kernel mode. Just return without doing anything * if so. */ if (!user_mode(regs)) return; if (test_thread_flag(TIF_RESTORE_SIGMASK)) oldset = &current->saved_sigmask; else oldset = &current->blocked; signr = get_signal_to_deliver(&info, &ka, regs, NULL); if (signr > 0) { /* Whee! Actually deliver the signal. */ if (handle_signal(signr, &info, &ka, oldset, regs) == 0) { /* * A signal was successfully delivered; the saved * sigmask will have been stored in the signal frame, * and will be restored by sigreturn, so we can simply * clear the TIF_RESTORE_SIGMASK flag. */ if (test_thread_flag(TIF_RESTORE_SIGMASK)) clear_thread_flag(TIF_RESTORE_SIGMASK); } return; } if (regs->regs[0]) { if (regs->regs[2] == ERESTARTNOHAND || regs->regs[2] == ERESTARTSYS || regs->regs[2] == ERESTARTNOINTR) { regs->regs[2] = regs->regs[0]; regs->regs[7] = regs->regs[26]; regs->cp0_epc -= 4; } if (regs->regs[2] == ERESTART_RESTARTBLOCK) { regs->regs[2] = current->thread.abi->restart; regs->regs[7] = regs->regs[26]; regs->cp0_epc -= 4; } regs->regs[0] = 0; /* Don't deal with this again. */ } /* * If there's no signal to deliver, we just put the saved sigmask * back */ if (test_thread_flag(TIF_RESTORE_SIGMASK)) { clear_thread_flag(TIF_RESTORE_SIGMASK); sigprocmask(SIG_SETMASK, &current->saved_sigmask, NULL); } } /* * notification of userspace execution resumption * - triggered by the TIF_WORK_MASK flags */ asmlinkage void do_notify_resume(struct pt_regs *regs, void *unused, __u32 thread_info_flags) { local_irq_enable(); /* deal with pending signal delivery */ if (thread_info_flags & (_TIF_SIGPENDING | _TIF_RESTORE_SIGMASK)) do_signal(regs); if (thread_info_flags & _TIF_NOTIFY_RESUME) { clear_thread_flag(TIF_NOTIFY_RESUME); tracehook_notify_resume(regs); if (current->replacement_session_keyring) key_replace_session_keyring(); } } #ifdef CONFIG_SMP static int smp_save_fp_context(struct sigcontext __user *sc) { return raw_cpu_has_fpu ? _save_fp_context(sc) : fpu_emulator_save_context(sc); } static int smp_restore_fp_context(struct sigcontext __user *sc) { return raw_cpu_has_fpu ? _restore_fp_context(sc) : fpu_emulator_restore_context(sc); } #endif static int signal_setup(void) { #ifdef CONFIG_SMP /* For now just do the cpu_has_fpu check when the functions are invoked */ save_fp_context = smp_save_fp_context; restore_fp_context = smp_restore_fp_context; #else if (cpu_has_fpu) { save_fp_context = _save_fp_context; restore_fp_context = _restore_fp_context; } else { save_fp_context = fpu_emulator_save_context; restore_fp_context = fpu_emulator_restore_context; } #endif return 0; } arch_initcall(signal_setup);
gpl-2.0
kgp700/nexroid-sgs4a-jb
fs/signalfd.c
6142
8174
/* * fs/signalfd.c * * Copyright (C) 2003 Linus Torvalds * * Mon Mar 5, 2007: Davide Libenzi <davidel@xmailserver.org> * Changed ->read() to return a siginfo strcture instead of signal number. * Fixed locking in ->poll(). * Added sighand-detach notification. * Added fd re-use in sys_signalfd() syscall. * Now using anonymous inode source. * Thanks to Oleg Nesterov for useful code review and suggestions. * More comments and suggestions from Arnd Bergmann. * Sat May 19, 2007: Davi E. M. Arnaut <davi@haxent.com.br> * Retrieve multiple signals with one read() call * Sun Jul 15, 2007: Davide Libenzi <davidel@xmailserver.org> * Attach to the sighand only during read() and poll(). */ #include <linux/file.h> #include <linux/poll.h> #include <linux/init.h> #include <linux/fs.h> #include <linux/sched.h> #include <linux/slab.h> #include <linux/kernel.h> #include <linux/signal.h> #include <linux/list.h> #include <linux/anon_inodes.h> #include <linux/signalfd.h> #include <linux/syscalls.h> void signalfd_cleanup(struct sighand_struct *sighand) { wait_queue_head_t *wqh = &sighand->signalfd_wqh; /* * The lockless check can race with remove_wait_queue() in progress, * but in this case its caller should run under rcu_read_lock() and * sighand_cachep is SLAB_DESTROY_BY_RCU, we can safely return. */ if (likely(!waitqueue_active(wqh))) return; /* wait_queue_t->func(POLLFREE) should do remove_wait_queue() */ wake_up_poll(wqh, POLLHUP | POLLFREE); } struct signalfd_ctx { sigset_t sigmask; }; static int signalfd_release(struct inode *inode, struct file *file) { kfree(file->private_data); return 0; } static unsigned int signalfd_poll(struct file *file, poll_table *wait) { struct signalfd_ctx *ctx = file->private_data; unsigned int events = 0; poll_wait(file, &current->sighand->signalfd_wqh, wait); spin_lock_irq(&current->sighand->siglock); if (next_signal(&current->pending, &ctx->sigmask) || next_signal(&current->signal->shared_pending, &ctx->sigmask)) events |= POLLIN; spin_unlock_irq(&current->sighand->siglock); return events; } /* * Copied from copy_siginfo_to_user() in kernel/signal.c */ static int signalfd_copyinfo(struct signalfd_siginfo __user *uinfo, siginfo_t const *kinfo) { long err; BUILD_BUG_ON(sizeof(struct signalfd_siginfo) != 128); /* * Unused members should be zero ... */ err = __clear_user(uinfo, sizeof(*uinfo)); /* * If you change siginfo_t structure, please be sure * this code is fixed accordingly. */ err |= __put_user(kinfo->si_signo, &uinfo->ssi_signo); err |= __put_user(kinfo->si_errno, &uinfo->ssi_errno); err |= __put_user((short) kinfo->si_code, &uinfo->ssi_code); switch (kinfo->si_code & __SI_MASK) { case __SI_KILL: err |= __put_user(kinfo->si_pid, &uinfo->ssi_pid); err |= __put_user(kinfo->si_uid, &uinfo->ssi_uid); break; case __SI_TIMER: err |= __put_user(kinfo->si_tid, &uinfo->ssi_tid); err |= __put_user(kinfo->si_overrun, &uinfo->ssi_overrun); err |= __put_user((long) kinfo->si_ptr, &uinfo->ssi_ptr); err |= __put_user(kinfo->si_int, &uinfo->ssi_int); break; case __SI_POLL: err |= __put_user(kinfo->si_band, &uinfo->ssi_band); err |= __put_user(kinfo->si_fd, &uinfo->ssi_fd); break; case __SI_FAULT: err |= __put_user((long) kinfo->si_addr, &uinfo->ssi_addr); #ifdef __ARCH_SI_TRAPNO err |= __put_user(kinfo->si_trapno, &uinfo->ssi_trapno); #endif #ifdef BUS_MCEERR_AO /* * Other callers might not initialize the si_lsb field, * so check explicitly for the right codes here. */ if (kinfo->si_code == BUS_MCEERR_AR || kinfo->si_code == BUS_MCEERR_AO) err |= __put_user((short) kinfo->si_addr_lsb, &uinfo->ssi_addr_lsb); #endif break; case __SI_CHLD: err |= __put_user(kinfo->si_pid, &uinfo->ssi_pid); err |= __put_user(kinfo->si_uid, &uinfo->ssi_uid); err |= __put_user(kinfo->si_status, &uinfo->ssi_status); err |= __put_user(kinfo->si_utime, &uinfo->ssi_utime); err |= __put_user(kinfo->si_stime, &uinfo->ssi_stime); break; case __SI_RT: /* This is not generated by the kernel as of now. */ case __SI_MESGQ: /* But this is */ err |= __put_user(kinfo->si_pid, &uinfo->ssi_pid); err |= __put_user(kinfo->si_uid, &uinfo->ssi_uid); err |= __put_user((long) kinfo->si_ptr, &uinfo->ssi_ptr); err |= __put_user(kinfo->si_int, &uinfo->ssi_int); break; default: /* * This case catches also the signals queued by sigqueue(). */ err |= __put_user(kinfo->si_pid, &uinfo->ssi_pid); err |= __put_user(kinfo->si_uid, &uinfo->ssi_uid); err |= __put_user((long) kinfo->si_ptr, &uinfo->ssi_ptr); err |= __put_user(kinfo->si_int, &uinfo->ssi_int); break; } return err ? -EFAULT: sizeof(*uinfo); } static ssize_t signalfd_dequeue(struct signalfd_ctx *ctx, siginfo_t *info, int nonblock) { ssize_t ret; DECLARE_WAITQUEUE(wait, current); spin_lock_irq(&current->sighand->siglock); ret = dequeue_signal(current, &ctx->sigmask, info); switch (ret) { case 0: if (!nonblock) break; ret = -EAGAIN; default: spin_unlock_irq(&current->sighand->siglock); return ret; } add_wait_queue(&current->sighand->signalfd_wqh, &wait); for (;;) { set_current_state(TASK_INTERRUPTIBLE); ret = dequeue_signal(current, &ctx->sigmask, info); if (ret != 0) break; if (signal_pending(current)) { ret = -ERESTARTSYS; break; } spin_unlock_irq(&current->sighand->siglock); schedule(); spin_lock_irq(&current->sighand->siglock); } spin_unlock_irq(&current->sighand->siglock); remove_wait_queue(&current->sighand->signalfd_wqh, &wait); __set_current_state(TASK_RUNNING); return ret; } /* * Returns a multiple of the size of a "struct signalfd_siginfo", or a negative * error code. The "count" parameter must be at least the size of a * "struct signalfd_siginfo". */ static ssize_t signalfd_read(struct file *file, char __user *buf, size_t count, loff_t *ppos) { struct signalfd_ctx *ctx = file->private_data; struct signalfd_siginfo __user *siginfo; int nonblock = file->f_flags & O_NONBLOCK; ssize_t ret, total = 0; siginfo_t info; count /= sizeof(struct signalfd_siginfo); if (!count) return -EINVAL; siginfo = (struct signalfd_siginfo __user *) buf; do { ret = signalfd_dequeue(ctx, &info, nonblock); if (unlikely(ret <= 0)) break; ret = signalfd_copyinfo(siginfo, &info); if (ret < 0) break; siginfo++; total += ret; nonblock = 1; } while (--count); return total ? total: ret; } static const struct file_operations signalfd_fops = { .release = signalfd_release, .poll = signalfd_poll, .read = signalfd_read, .llseek = noop_llseek, }; SYSCALL_DEFINE4(signalfd4, int, ufd, sigset_t __user *, user_mask, size_t, sizemask, int, flags) { sigset_t sigmask; struct signalfd_ctx *ctx; /* Check the SFD_* constants for consistency. */ BUILD_BUG_ON(SFD_CLOEXEC != O_CLOEXEC); BUILD_BUG_ON(SFD_NONBLOCK != O_NONBLOCK); if (flags & ~(SFD_CLOEXEC | SFD_NONBLOCK)) return -EINVAL; if (sizemask != sizeof(sigset_t) || copy_from_user(&sigmask, user_mask, sizeof(sigmask))) return -EINVAL; sigdelsetmask(&sigmask, sigmask(SIGKILL) | sigmask(SIGSTOP)); signotset(&sigmask); if (ufd == -1) { ctx = kmalloc(sizeof(*ctx), GFP_KERNEL); if (!ctx) return -ENOMEM; ctx->sigmask = sigmask; /* * When we call this, the initialization must be complete, since * anon_inode_getfd() will install the fd. */ ufd = anon_inode_getfd("[signalfd]", &signalfd_fops, ctx, O_RDWR | (flags & (O_CLOEXEC | O_NONBLOCK))); if (ufd < 0) kfree(ctx); } else { struct file *file = fget(ufd); if (!file) return -EBADF; ctx = file->private_data; if (file->f_op != &signalfd_fops) { fput(file); return -EINVAL; } spin_lock_irq(&current->sighand->siglock); ctx->sigmask = sigmask; spin_unlock_irq(&current->sighand->siglock); wake_up(&current->sighand->signalfd_wqh); fput(file); } return ufd; } SYSCALL_DEFINE3(signalfd, int, ufd, sigset_t __user *, user_mask, size_t, sizemask) { return sys_signalfd4(ufd, user_mask, sizemask, 0); }
gpl-2.0
SANGHA1398/Wind_iproj_JB_kernel
drivers/usb/host/ehci-lpm.c
7934
2632
/* ehci-lpm.c EHCI HCD LPM support code * Copyright (c) 2008 - 2010, Intel Corporation. * Author: Jacob Pan <jacob.jun.pan@intel.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., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* this file is part of ehci-hcd.c */ static int __maybe_unused ehci_lpm_set_da(struct ehci_hcd *ehci, int dev_addr, int port_num) { u32 __iomem portsc; ehci_dbg(ehci, "set dev address %d for port %d\n", dev_addr, port_num); if (port_num > HCS_N_PORTS(ehci->hcs_params)) { ehci_dbg(ehci, "invalid port number %d\n", port_num); return -ENODEV; } portsc = ehci_readl(ehci, &ehci->regs->port_status[port_num-1]); portsc &= ~PORT_DEV_ADDR; portsc |= dev_addr<<25; ehci_writel(ehci, portsc, &ehci->regs->port_status[port_num-1]); return 0; } /* * this function is used to check if the device support LPM * if yes, mark the PORTSC register with PORT_LPM bit */ static int __maybe_unused ehci_lpm_check(struct ehci_hcd *ehci, int port) { u32 __iomem *portsc ; u32 val32; int retval; portsc = &ehci->regs->port_status[port-1]; val32 = ehci_readl(ehci, portsc); if (!(val32 & PORT_DEV_ADDR)) { ehci_dbg(ehci, "LPM: no device attached\n"); return -ENODEV; } val32 |= PORT_LPM; ehci_writel(ehci, val32, portsc); msleep(5); val32 |= PORT_SUSPEND; ehci_dbg(ehci, "Sending LPM 0x%08x to port %d\n", val32, port); ehci_writel(ehci, val32, portsc); /* wait for ACK */ msleep(10); retval = handshake(ehci, &ehci->regs->port_status[port-1], PORT_SSTS, PORTSC_SUSPEND_STS_ACK, 125); dbg_port(ehci, "LPM", port, val32); if (retval != -ETIMEDOUT) { ehci_dbg(ehci, "LPM: device ACK for LPM\n"); val32 |= PORT_LPM; /* * now device should be in L1 sleep, let's wake up the device * so that we can complete enumeration. */ ehci_writel(ehci, val32, portsc); msleep(10); val32 |= PORT_RESUME; ehci_writel(ehci, val32, portsc); } else { ehci_dbg(ehci, "LPM: device does not ACK, disable LPM %d\n", retval); val32 &= ~PORT_LPM; retval = -ETIMEDOUT; ehci_writel(ehci, val32, portsc); } return retval; }
gpl-2.0
SystemTera/SystemTera.Server-V-3.14-Kernel
drivers/net/wireless/b43/phy_g.c
7934
83156
/* Broadcom B43 wireless driver IEEE 802.11g PHY driver Copyright (c) 2005 Martin Langer <martin-langer@gmx.de>, Copyright (c) 2005-2007 Stefano Brivio <stefano.brivio@polimi.it> Copyright (c) 2005-2008 Michael Buesch <m@bues.ch> Copyright (c) 2005, 2006 Danny van Dyk <kugelfang@gentoo.org> Copyright (c) 2005, 2006 Andreas Jaggi <andreas.jaggi@waterwave.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; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Steet, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "b43.h" #include "phy_g.h" #include "phy_common.h" #include "lo.h" #include "main.h" #include <linux/bitrev.h> #include <linux/slab.h> static const s8 b43_tssi2dbm_g_table[] = { 77, 77, 77, 76, 76, 76, 75, 75, 74, 74, 73, 73, 73, 72, 72, 71, 71, 70, 70, 69, 68, 68, 67, 67, 66, 65, 65, 64, 63, 63, 62, 61, 60, 59, 58, 57, 56, 55, 54, 53, 52, 50, 49, 47, 45, 43, 40, 37, 33, 28, 22, 14, 5, -7, -20, -20, -20, -20, -20, -20, -20, -20, -20, -20, }; static const u8 b43_radio_channel_codes_bg[] = { 12, 17, 22, 27, 32, 37, 42, 47, 52, 57, 62, 67, 72, 84, }; static void b43_calc_nrssi_threshold(struct b43_wldev *dev); #define bitrev4(tmp) (bitrev8(tmp) >> 4) /* Get the freq, as it has to be written to the device. */ static inline u16 channel2freq_bg(u8 channel) { B43_WARN_ON(!(channel >= 1 && channel <= 14)); return b43_radio_channel_codes_bg[channel - 1]; } static void generate_rfatt_list(struct b43_wldev *dev, struct b43_rfatt_list *list) { struct b43_phy *phy = &dev->phy; /* APHY.rev < 5 || GPHY.rev < 6 */ static const struct b43_rfatt rfatt_0[] = { {.att = 3,.with_padmix = 0,}, {.att = 1,.with_padmix = 0,}, {.att = 5,.with_padmix = 0,}, {.att = 7,.with_padmix = 0,}, {.att = 9,.with_padmix = 0,}, {.att = 2,.with_padmix = 0,}, {.att = 0,.with_padmix = 0,}, {.att = 4,.with_padmix = 0,}, {.att = 6,.with_padmix = 0,}, {.att = 8,.with_padmix = 0,}, {.att = 1,.with_padmix = 1,}, {.att = 2,.with_padmix = 1,}, {.att = 3,.with_padmix = 1,}, {.att = 4,.with_padmix = 1,}, }; /* Radio.rev == 8 && Radio.version == 0x2050 */ static const struct b43_rfatt rfatt_1[] = { {.att = 2,.with_padmix = 1,}, {.att = 4,.with_padmix = 1,}, {.att = 6,.with_padmix = 1,}, {.att = 8,.with_padmix = 1,}, {.att = 10,.with_padmix = 1,}, {.att = 12,.with_padmix = 1,}, {.att = 14,.with_padmix = 1,}, }; /* Otherwise */ static const struct b43_rfatt rfatt_2[] = { {.att = 0,.with_padmix = 1,}, {.att = 2,.with_padmix = 1,}, {.att = 4,.with_padmix = 1,}, {.att = 6,.with_padmix = 1,}, {.att = 8,.with_padmix = 1,}, {.att = 9,.with_padmix = 1,}, {.att = 9,.with_padmix = 1,}, }; if (!b43_has_hardware_pctl(dev)) { /* Software pctl */ list->list = rfatt_0; list->len = ARRAY_SIZE(rfatt_0); list->min_val = 0; list->max_val = 9; return; } if (phy->radio_ver == 0x2050 && phy->radio_rev == 8) { /* Hardware pctl */ list->list = rfatt_1; list->len = ARRAY_SIZE(rfatt_1); list->min_val = 0; list->max_val = 14; return; } /* Hardware pctl */ list->list = rfatt_2; list->len = ARRAY_SIZE(rfatt_2); list->min_val = 0; list->max_val = 9; } static void generate_bbatt_list(struct b43_wldev *dev, struct b43_bbatt_list *list) { static const struct b43_bbatt bbatt_0[] = { {.att = 0,}, {.att = 1,}, {.att = 2,}, {.att = 3,}, {.att = 4,}, {.att = 5,}, {.att = 6,}, {.att = 7,}, {.att = 8,}, }; list->list = bbatt_0; list->len = ARRAY_SIZE(bbatt_0); list->min_val = 0; list->max_val = 8; } static void b43_shm_clear_tssi(struct b43_wldev *dev) { b43_shm_write16(dev, B43_SHM_SHARED, 0x0058, 0x7F7F); b43_shm_write16(dev, B43_SHM_SHARED, 0x005a, 0x7F7F); b43_shm_write16(dev, B43_SHM_SHARED, 0x0070, 0x7F7F); b43_shm_write16(dev, B43_SHM_SHARED, 0x0072, 0x7F7F); } /* Synthetic PU workaround */ static void b43_synth_pu_workaround(struct b43_wldev *dev, u8 channel) { struct b43_phy *phy = &dev->phy; might_sleep(); if (phy->radio_ver != 0x2050 || phy->radio_rev >= 6) { /* We do not need the workaround. */ return; } if (channel <= 10) { b43_write16(dev, B43_MMIO_CHANNEL, channel2freq_bg(channel + 4)); } else { b43_write16(dev, B43_MMIO_CHANNEL, channel2freq_bg(1)); } msleep(1); b43_write16(dev, B43_MMIO_CHANNEL, channel2freq_bg(channel)); } /* Set the baseband attenuation value on chip. */ void b43_gphy_set_baseband_attenuation(struct b43_wldev *dev, u16 baseband_attenuation) { struct b43_phy *phy = &dev->phy; if (phy->analog == 0) { b43_write16(dev, B43_MMIO_PHY0, (b43_read16(dev, B43_MMIO_PHY0) & 0xFFF0) | baseband_attenuation); } else if (phy->analog > 1) { b43_phy_maskset(dev, B43_PHY_DACCTL, 0xFFC3, (baseband_attenuation << 2)); } else { b43_phy_maskset(dev, B43_PHY_DACCTL, 0xFF87, (baseband_attenuation << 3)); } } /* Adjust the transmission power output (G-PHY) */ static void b43_set_txpower_g(struct b43_wldev *dev, const struct b43_bbatt *bbatt, const struct b43_rfatt *rfatt, u8 tx_control) { struct b43_phy *phy = &dev->phy; struct b43_phy_g *gphy = phy->g; struct b43_txpower_lo_control *lo = gphy->lo_control; u16 bb, rf; u16 tx_bias, tx_magn; bb = bbatt->att; rf = rfatt->att; tx_bias = lo->tx_bias; tx_magn = lo->tx_magn; if (unlikely(tx_bias == 0xFF)) tx_bias = 0; /* Save the values for later. Use memmove, because it's valid * to pass &gphy->rfatt as rfatt pointer argument. Same for bbatt. */ gphy->tx_control = tx_control; memmove(&gphy->rfatt, rfatt, sizeof(*rfatt)); gphy->rfatt.with_padmix = !!(tx_control & B43_TXCTL_TXMIX); memmove(&gphy->bbatt, bbatt, sizeof(*bbatt)); if (b43_debug(dev, B43_DBG_XMITPOWER)) { b43dbg(dev->wl, "Tuning TX-power to bbatt(%u), " "rfatt(%u), tx_control(0x%02X), " "tx_bias(0x%02X), tx_magn(0x%02X)\n", bb, rf, tx_control, tx_bias, tx_magn); } b43_gphy_set_baseband_attenuation(dev, bb); b43_shm_write16(dev, B43_SHM_SHARED, B43_SHM_SH_RFATT, rf); if (phy->radio_ver == 0x2050 && phy->radio_rev == 8) { b43_radio_write16(dev, 0x43, (rf & 0x000F) | (tx_control & 0x0070)); } else { b43_radio_maskset(dev, 0x43, 0xFFF0, (rf & 0x000F)); b43_radio_maskset(dev, 0x52, ~0x0070, (tx_control & 0x0070)); } if (has_tx_magnification(phy)) { b43_radio_write16(dev, 0x52, tx_magn | tx_bias); } else { b43_radio_maskset(dev, 0x52, 0xFFF0, (tx_bias & 0x000F)); } b43_lo_g_adjust(dev); } /* GPHY_TSSI_Power_Lookup_Table_Init */ static void b43_gphy_tssi_power_lt_init(struct b43_wldev *dev) { struct b43_phy_g *gphy = dev->phy.g; int i; u16 value; for (i = 0; i < 32; i++) b43_ofdmtab_write16(dev, 0x3C20, i, gphy->tssi2dbm[i]); for (i = 32; i < 64; i++) b43_ofdmtab_write16(dev, 0x3C00, i - 32, gphy->tssi2dbm[i]); for (i = 0; i < 64; i += 2) { value = (u16) gphy->tssi2dbm[i]; value |= ((u16) gphy->tssi2dbm[i + 1]) << 8; b43_phy_write(dev, 0x380 + (i / 2), value); } } /* GPHY_Gain_Lookup_Table_Init */ static void b43_gphy_gain_lt_init(struct b43_wldev *dev) { struct b43_phy *phy = &dev->phy; struct b43_phy_g *gphy = phy->g; struct b43_txpower_lo_control *lo = gphy->lo_control; u16 nr_written = 0; u16 tmp; u8 rf, bb; for (rf = 0; rf < lo->rfatt_list.len; rf++) { for (bb = 0; bb < lo->bbatt_list.len; bb++) { if (nr_written >= 0x40) return; tmp = lo->bbatt_list.list[bb].att; tmp <<= 8; if (phy->radio_rev == 8) tmp |= 0x50; else tmp |= 0x40; tmp |= lo->rfatt_list.list[rf].att; b43_phy_write(dev, 0x3C0 + nr_written, tmp); nr_written++; } } } static void b43_set_all_gains(struct b43_wldev *dev, s16 first, s16 second, s16 third) { struct b43_phy *phy = &dev->phy; u16 i; u16 start = 0x08, end = 0x18; u16 tmp; u16 table; if (phy->rev <= 1) { start = 0x10; end = 0x20; } table = B43_OFDMTAB_GAINX; if (phy->rev <= 1) table = B43_OFDMTAB_GAINX_R1; for (i = 0; i < 4; i++) b43_ofdmtab_write16(dev, table, i, first); for (i = start; i < end; i++) b43_ofdmtab_write16(dev, table, i, second); if (third != -1) { tmp = ((u16) third << 14) | ((u16) third << 6); b43_phy_maskset(dev, 0x04A0, 0xBFBF, tmp); b43_phy_maskset(dev, 0x04A1, 0xBFBF, tmp); b43_phy_maskset(dev, 0x04A2, 0xBFBF, tmp); } b43_dummy_transmission(dev, false, true); } static void b43_set_original_gains(struct b43_wldev *dev) { struct b43_phy *phy = &dev->phy; u16 i, tmp; u16 table; u16 start = 0x0008, end = 0x0018; if (phy->rev <= 1) { start = 0x0010; end = 0x0020; } table = B43_OFDMTAB_GAINX; if (phy->rev <= 1) table = B43_OFDMTAB_GAINX_R1; for (i = 0; i < 4; i++) { tmp = (i & 0xFFFC); tmp |= (i & 0x0001) << 1; tmp |= (i & 0x0002) >> 1; b43_ofdmtab_write16(dev, table, i, tmp); } for (i = start; i < end; i++) b43_ofdmtab_write16(dev, table, i, i - start); b43_phy_maskset(dev, 0x04A0, 0xBFBF, 0x4040); b43_phy_maskset(dev, 0x04A1, 0xBFBF, 0x4040); b43_phy_maskset(dev, 0x04A2, 0xBFBF, 0x4000); b43_dummy_transmission(dev, false, true); } /* http://bcm-specs.sipsolutions.net/NRSSILookupTable */ static void b43_nrssi_hw_write(struct b43_wldev *dev, u16 offset, s16 val) { b43_phy_write(dev, B43_PHY_NRSSILT_CTRL, offset); b43_phy_write(dev, B43_PHY_NRSSILT_DATA, (u16) val); } /* http://bcm-specs.sipsolutions.net/NRSSILookupTable */ static s16 b43_nrssi_hw_read(struct b43_wldev *dev, u16 offset) { u16 val; b43_phy_write(dev, B43_PHY_NRSSILT_CTRL, offset); val = b43_phy_read(dev, B43_PHY_NRSSILT_DATA); return (s16) val; } /* http://bcm-specs.sipsolutions.net/NRSSILookupTable */ static void b43_nrssi_hw_update(struct b43_wldev *dev, u16 val) { u16 i; s16 tmp; for (i = 0; i < 64; i++) { tmp = b43_nrssi_hw_read(dev, i); tmp -= val; tmp = clamp_val(tmp, -32, 31); b43_nrssi_hw_write(dev, i, tmp); } } /* http://bcm-specs.sipsolutions.net/NRSSILookupTable */ static void b43_nrssi_mem_update(struct b43_wldev *dev) { struct b43_phy_g *gphy = dev->phy.g; s16 i, delta; s32 tmp; delta = 0x1F - gphy->nrssi[0]; for (i = 0; i < 64; i++) { tmp = (i - delta) * gphy->nrssislope; tmp /= 0x10000; tmp += 0x3A; tmp = clamp_val(tmp, 0, 0x3F); gphy->nrssi_lt[i] = tmp; } } static void b43_calc_nrssi_offset(struct b43_wldev *dev) { struct b43_phy *phy = &dev->phy; u16 backup[20] = { 0 }; s16 v47F; u16 i; u16 saved = 0xFFFF; backup[0] = b43_phy_read(dev, 0x0001); backup[1] = b43_phy_read(dev, 0x0811); backup[2] = b43_phy_read(dev, 0x0812); if (phy->rev != 1) { /* Not in specs, but needed to prevent PPC machine check */ backup[3] = b43_phy_read(dev, 0x0814); backup[4] = b43_phy_read(dev, 0x0815); } backup[5] = b43_phy_read(dev, 0x005A); backup[6] = b43_phy_read(dev, 0x0059); backup[7] = b43_phy_read(dev, 0x0058); backup[8] = b43_phy_read(dev, 0x000A); backup[9] = b43_phy_read(dev, 0x0003); backup[10] = b43_radio_read16(dev, 0x007A); backup[11] = b43_radio_read16(dev, 0x0043); b43_phy_mask(dev, 0x0429, 0x7FFF); b43_phy_maskset(dev, 0x0001, 0x3FFF, 0x4000); b43_phy_set(dev, 0x0811, 0x000C); b43_phy_maskset(dev, 0x0812, 0xFFF3, 0x0004); b43_phy_mask(dev, 0x0802, ~(0x1 | 0x2)); if (phy->rev >= 6) { backup[12] = b43_phy_read(dev, 0x002E); backup[13] = b43_phy_read(dev, 0x002F); backup[14] = b43_phy_read(dev, 0x080F); backup[15] = b43_phy_read(dev, 0x0810); backup[16] = b43_phy_read(dev, 0x0801); backup[17] = b43_phy_read(dev, 0x0060); backup[18] = b43_phy_read(dev, 0x0014); backup[19] = b43_phy_read(dev, 0x0478); b43_phy_write(dev, 0x002E, 0); b43_phy_write(dev, 0x002F, 0); b43_phy_write(dev, 0x080F, 0); b43_phy_write(dev, 0x0810, 0); b43_phy_set(dev, 0x0478, 0x0100); b43_phy_set(dev, 0x0801, 0x0040); b43_phy_set(dev, 0x0060, 0x0040); b43_phy_set(dev, 0x0014, 0x0200); } b43_radio_set(dev, 0x007A, 0x0070); b43_radio_set(dev, 0x007A, 0x0080); udelay(30); v47F = (s16) ((b43_phy_read(dev, 0x047F) >> 8) & 0x003F); if (v47F >= 0x20) v47F -= 0x40; if (v47F == 31) { for (i = 7; i >= 4; i--) { b43_radio_write16(dev, 0x007B, i); udelay(20); v47F = (s16) ((b43_phy_read(dev, 0x047F) >> 8) & 0x003F); if (v47F >= 0x20) v47F -= 0x40; if (v47F < 31 && saved == 0xFFFF) saved = i; } if (saved == 0xFFFF) saved = 4; } else { b43_radio_mask(dev, 0x007A, 0x007F); if (phy->rev != 1) { /* Not in specs, but needed to prevent PPC machine check */ b43_phy_set(dev, 0x0814, 0x0001); b43_phy_mask(dev, 0x0815, 0xFFFE); } b43_phy_set(dev, 0x0811, 0x000C); b43_phy_set(dev, 0x0812, 0x000C); b43_phy_set(dev, 0x0811, 0x0030); b43_phy_set(dev, 0x0812, 0x0030); b43_phy_write(dev, 0x005A, 0x0480); b43_phy_write(dev, 0x0059, 0x0810); b43_phy_write(dev, 0x0058, 0x000D); if (phy->rev == 0) { b43_phy_write(dev, 0x0003, 0x0122); } else { b43_phy_set(dev, 0x000A, 0x2000); } if (phy->rev != 1) { /* Not in specs, but needed to prevent PPC machine check */ b43_phy_set(dev, 0x0814, 0x0004); b43_phy_mask(dev, 0x0815, 0xFFFB); } b43_phy_maskset(dev, 0x0003, 0xFF9F, 0x0040); b43_radio_set(dev, 0x007A, 0x000F); b43_set_all_gains(dev, 3, 0, 1); b43_radio_maskset(dev, 0x0043, 0x00F0, 0x000F); udelay(30); v47F = (s16) ((b43_phy_read(dev, 0x047F) >> 8) & 0x003F); if (v47F >= 0x20) v47F -= 0x40; if (v47F == -32) { for (i = 0; i < 4; i++) { b43_radio_write16(dev, 0x007B, i); udelay(20); v47F = (s16) ((b43_phy_read(dev, 0x047F) >> 8) & 0x003F); if (v47F >= 0x20) v47F -= 0x40; if (v47F > -31 && saved == 0xFFFF) saved = i; } if (saved == 0xFFFF) saved = 3; } else saved = 0; } b43_radio_write16(dev, 0x007B, saved); if (phy->rev >= 6) { b43_phy_write(dev, 0x002E, backup[12]); b43_phy_write(dev, 0x002F, backup[13]); b43_phy_write(dev, 0x080F, backup[14]); b43_phy_write(dev, 0x0810, backup[15]); } if (phy->rev != 1) { /* Not in specs, but needed to prevent PPC machine check */ b43_phy_write(dev, 0x0814, backup[3]); b43_phy_write(dev, 0x0815, backup[4]); } b43_phy_write(dev, 0x005A, backup[5]); b43_phy_write(dev, 0x0059, backup[6]); b43_phy_write(dev, 0x0058, backup[7]); b43_phy_write(dev, 0x000A, backup[8]); b43_phy_write(dev, 0x0003, backup[9]); b43_radio_write16(dev, 0x0043, backup[11]); b43_radio_write16(dev, 0x007A, backup[10]); b43_phy_write(dev, 0x0802, b43_phy_read(dev, 0x0802) | 0x1 | 0x2); b43_phy_set(dev, 0x0429, 0x8000); b43_set_original_gains(dev); if (phy->rev >= 6) { b43_phy_write(dev, 0x0801, backup[16]); b43_phy_write(dev, 0x0060, backup[17]); b43_phy_write(dev, 0x0014, backup[18]); b43_phy_write(dev, 0x0478, backup[19]); } b43_phy_write(dev, 0x0001, backup[0]); b43_phy_write(dev, 0x0812, backup[2]); b43_phy_write(dev, 0x0811, backup[1]); } static void b43_calc_nrssi_slope(struct b43_wldev *dev) { struct b43_phy *phy = &dev->phy; struct b43_phy_g *gphy = phy->g; u16 backup[18] = { 0 }; u16 tmp; s16 nrssi0, nrssi1; B43_WARN_ON(phy->type != B43_PHYTYPE_G); if (phy->radio_rev >= 9) return; if (phy->radio_rev == 8) b43_calc_nrssi_offset(dev); b43_phy_mask(dev, B43_PHY_G_CRS, 0x7FFF); b43_phy_mask(dev, 0x0802, 0xFFFC); backup[7] = b43_read16(dev, 0x03E2); b43_write16(dev, 0x03E2, b43_read16(dev, 0x03E2) | 0x8000); backup[0] = b43_radio_read16(dev, 0x007A); backup[1] = b43_radio_read16(dev, 0x0052); backup[2] = b43_radio_read16(dev, 0x0043); backup[3] = b43_phy_read(dev, 0x0015); backup[4] = b43_phy_read(dev, 0x005A); backup[5] = b43_phy_read(dev, 0x0059); backup[6] = b43_phy_read(dev, 0x0058); backup[8] = b43_read16(dev, 0x03E6); backup[9] = b43_read16(dev, B43_MMIO_CHANNEL_EXT); if (phy->rev >= 3) { backup[10] = b43_phy_read(dev, 0x002E); backup[11] = b43_phy_read(dev, 0x002F); backup[12] = b43_phy_read(dev, 0x080F); backup[13] = b43_phy_read(dev, B43_PHY_G_LO_CONTROL); backup[14] = b43_phy_read(dev, 0x0801); backup[15] = b43_phy_read(dev, 0x0060); backup[16] = b43_phy_read(dev, 0x0014); backup[17] = b43_phy_read(dev, 0x0478); b43_phy_write(dev, 0x002E, 0); b43_phy_write(dev, B43_PHY_G_LO_CONTROL, 0); switch (phy->rev) { case 4: case 6: case 7: b43_phy_set(dev, 0x0478, 0x0100); b43_phy_set(dev, 0x0801, 0x0040); break; case 3: case 5: b43_phy_mask(dev, 0x0801, 0xFFBF); break; } b43_phy_set(dev, 0x0060, 0x0040); b43_phy_set(dev, 0x0014, 0x0200); } b43_radio_set(dev, 0x007A, 0x0070); b43_set_all_gains(dev, 0, 8, 0); b43_radio_mask(dev, 0x007A, 0x00F7); if (phy->rev >= 2) { b43_phy_maskset(dev, 0x0811, 0xFFCF, 0x0030); b43_phy_maskset(dev, 0x0812, 0xFFCF, 0x0010); } b43_radio_set(dev, 0x007A, 0x0080); udelay(20); nrssi0 = (s16) ((b43_phy_read(dev, 0x047F) >> 8) & 0x003F); if (nrssi0 >= 0x0020) nrssi0 -= 0x0040; b43_radio_mask(dev, 0x007A, 0x007F); if (phy->rev >= 2) { b43_phy_maskset(dev, 0x0003, 0xFF9F, 0x0040); } b43_write16(dev, B43_MMIO_CHANNEL_EXT, b43_read16(dev, B43_MMIO_CHANNEL_EXT) | 0x2000); b43_radio_set(dev, 0x007A, 0x000F); b43_phy_write(dev, 0x0015, 0xF330); if (phy->rev >= 2) { b43_phy_maskset(dev, 0x0812, 0xFFCF, 0x0020); b43_phy_maskset(dev, 0x0811, 0xFFCF, 0x0020); } b43_set_all_gains(dev, 3, 0, 1); if (phy->radio_rev == 8) { b43_radio_write16(dev, 0x0043, 0x001F); } else { tmp = b43_radio_read16(dev, 0x0052) & 0xFF0F; b43_radio_write16(dev, 0x0052, tmp | 0x0060); tmp = b43_radio_read16(dev, 0x0043) & 0xFFF0; b43_radio_write16(dev, 0x0043, tmp | 0x0009); } b43_phy_write(dev, 0x005A, 0x0480); b43_phy_write(dev, 0x0059, 0x0810); b43_phy_write(dev, 0x0058, 0x000D); udelay(20); nrssi1 = (s16) ((b43_phy_read(dev, 0x047F) >> 8) & 0x003F); if (nrssi1 >= 0x0020) nrssi1 -= 0x0040; if (nrssi0 == nrssi1) gphy->nrssislope = 0x00010000; else gphy->nrssislope = 0x00400000 / (nrssi0 - nrssi1); if (nrssi0 >= -4) { gphy->nrssi[0] = nrssi1; gphy->nrssi[1] = nrssi0; } if (phy->rev >= 3) { b43_phy_write(dev, 0x002E, backup[10]); b43_phy_write(dev, 0x002F, backup[11]); b43_phy_write(dev, 0x080F, backup[12]); b43_phy_write(dev, B43_PHY_G_LO_CONTROL, backup[13]); } if (phy->rev >= 2) { b43_phy_mask(dev, 0x0812, 0xFFCF); b43_phy_mask(dev, 0x0811, 0xFFCF); } b43_radio_write16(dev, 0x007A, backup[0]); b43_radio_write16(dev, 0x0052, backup[1]); b43_radio_write16(dev, 0x0043, backup[2]); b43_write16(dev, 0x03E2, backup[7]); b43_write16(dev, 0x03E6, backup[8]); b43_write16(dev, B43_MMIO_CHANNEL_EXT, backup[9]); b43_phy_write(dev, 0x0015, backup[3]); b43_phy_write(dev, 0x005A, backup[4]); b43_phy_write(dev, 0x0059, backup[5]); b43_phy_write(dev, 0x0058, backup[6]); b43_synth_pu_workaround(dev, phy->channel); b43_phy_set(dev, 0x0802, (0x0001 | 0x0002)); b43_set_original_gains(dev); b43_phy_set(dev, B43_PHY_G_CRS, 0x8000); if (phy->rev >= 3) { b43_phy_write(dev, 0x0801, backup[14]); b43_phy_write(dev, 0x0060, backup[15]); b43_phy_write(dev, 0x0014, backup[16]); b43_phy_write(dev, 0x0478, backup[17]); } b43_nrssi_mem_update(dev); b43_calc_nrssi_threshold(dev); } static void b43_calc_nrssi_threshold(struct b43_wldev *dev) { struct b43_phy *phy = &dev->phy; struct b43_phy_g *gphy = phy->g; s32 a, b; s16 tmp16; u16 tmp_u16; B43_WARN_ON(phy->type != B43_PHYTYPE_G); if (!phy->gmode || !(dev->dev->bus_sprom->boardflags_lo & B43_BFL_RSSI)) { tmp16 = b43_nrssi_hw_read(dev, 0x20); if (tmp16 >= 0x20) tmp16 -= 0x40; if (tmp16 < 3) { b43_phy_maskset(dev, 0x048A, 0xF000, 0x09EB); } else { b43_phy_maskset(dev, 0x048A, 0xF000, 0x0AED); } } else { if (gphy->interfmode == B43_INTERFMODE_NONWLAN) { a = 0xE; b = 0xA; } else if (!gphy->aci_wlan_automatic && gphy->aci_enable) { a = 0x13; b = 0x12; } else { a = 0xE; b = 0x11; } a = a * (gphy->nrssi[1] - gphy->nrssi[0]); a += (gphy->nrssi[0] << 6); if (a < 32) a += 31; else a += 32; a = a >> 6; a = clamp_val(a, -31, 31); b = b * (gphy->nrssi[1] - gphy->nrssi[0]); b += (gphy->nrssi[0] << 6); if (b < 32) b += 31; else b += 32; b = b >> 6; b = clamp_val(b, -31, 31); tmp_u16 = b43_phy_read(dev, 0x048A) & 0xF000; tmp_u16 |= ((u32) b & 0x0000003F); tmp_u16 |= (((u32) a & 0x0000003F) << 6); b43_phy_write(dev, 0x048A, tmp_u16); } } /* Stack implementation to save/restore values from the * interference mitigation code. * It is save to restore values in random order. */ static void _stack_save(u32 *_stackptr, size_t *stackidx, u8 id, u16 offset, u16 value) { u32 *stackptr = &(_stackptr[*stackidx]); B43_WARN_ON(offset & 0xF000); B43_WARN_ON(id & 0xF0); *stackptr = offset; *stackptr |= ((u32) id) << 12; *stackptr |= ((u32) value) << 16; (*stackidx)++; B43_WARN_ON(*stackidx >= B43_INTERFSTACK_SIZE); } static u16 _stack_restore(u32 *stackptr, u8 id, u16 offset) { size_t i; B43_WARN_ON(offset & 0xF000); B43_WARN_ON(id & 0xF0); for (i = 0; i < B43_INTERFSTACK_SIZE; i++, stackptr++) { if ((*stackptr & 0x00000FFF) != offset) continue; if (((*stackptr & 0x0000F000) >> 12) != id) continue; return ((*stackptr & 0xFFFF0000) >> 16); } B43_WARN_ON(1); return 0; } #define phy_stacksave(offset) \ do { \ _stack_save(stack, &stackidx, 0x1, (offset), \ b43_phy_read(dev, (offset))); \ } while (0) #define phy_stackrestore(offset) \ do { \ b43_phy_write(dev, (offset), \ _stack_restore(stack, 0x1, \ (offset))); \ } while (0) #define radio_stacksave(offset) \ do { \ _stack_save(stack, &stackidx, 0x2, (offset), \ b43_radio_read16(dev, (offset))); \ } while (0) #define radio_stackrestore(offset) \ do { \ b43_radio_write16(dev, (offset), \ _stack_restore(stack, 0x2, \ (offset))); \ } while (0) #define ofdmtab_stacksave(table, offset) \ do { \ _stack_save(stack, &stackidx, 0x3, (offset)|(table), \ b43_ofdmtab_read16(dev, (table), (offset))); \ } while (0) #define ofdmtab_stackrestore(table, offset) \ do { \ b43_ofdmtab_write16(dev, (table), (offset), \ _stack_restore(stack, 0x3, \ (offset)|(table))); \ } while (0) static void b43_radio_interference_mitigation_enable(struct b43_wldev *dev, int mode) { struct b43_phy *phy = &dev->phy; struct b43_phy_g *gphy = phy->g; u16 tmp, flipped; size_t stackidx = 0; u32 *stack = gphy->interfstack; switch (mode) { case B43_INTERFMODE_NONWLAN: if (phy->rev != 1) { b43_phy_set(dev, 0x042B, 0x0800); b43_phy_mask(dev, B43_PHY_G_CRS, ~0x4000); break; } radio_stacksave(0x0078); tmp = (b43_radio_read16(dev, 0x0078) & 0x001E); B43_WARN_ON(tmp > 15); flipped = bitrev4(tmp); if (flipped < 10 && flipped >= 8) flipped = 7; else if (flipped >= 10) flipped -= 3; flipped = (bitrev4(flipped) << 1) | 0x0020; b43_radio_write16(dev, 0x0078, flipped); b43_calc_nrssi_threshold(dev); phy_stacksave(0x0406); b43_phy_write(dev, 0x0406, 0x7E28); b43_phy_set(dev, 0x042B, 0x0800); b43_phy_set(dev, B43_PHY_RADIO_BITFIELD, 0x1000); phy_stacksave(0x04A0); b43_phy_maskset(dev, 0x04A0, 0xC0C0, 0x0008); phy_stacksave(0x04A1); b43_phy_maskset(dev, 0x04A1, 0xC0C0, 0x0605); phy_stacksave(0x04A2); b43_phy_maskset(dev, 0x04A2, 0xC0C0, 0x0204); phy_stacksave(0x04A8); b43_phy_maskset(dev, 0x04A8, 0xC0C0, 0x0803); phy_stacksave(0x04AB); b43_phy_maskset(dev, 0x04AB, 0xC0C0, 0x0605); phy_stacksave(0x04A7); b43_phy_write(dev, 0x04A7, 0x0002); phy_stacksave(0x04A3); b43_phy_write(dev, 0x04A3, 0x287A); phy_stacksave(0x04A9); b43_phy_write(dev, 0x04A9, 0x2027); phy_stacksave(0x0493); b43_phy_write(dev, 0x0493, 0x32F5); phy_stacksave(0x04AA); b43_phy_write(dev, 0x04AA, 0x2027); phy_stacksave(0x04AC); b43_phy_write(dev, 0x04AC, 0x32F5); break; case B43_INTERFMODE_MANUALWLAN: if (b43_phy_read(dev, 0x0033) & 0x0800) break; gphy->aci_enable = true; phy_stacksave(B43_PHY_RADIO_BITFIELD); phy_stacksave(B43_PHY_G_CRS); if (phy->rev < 2) { phy_stacksave(0x0406); } else { phy_stacksave(0x04C0); phy_stacksave(0x04C1); } phy_stacksave(0x0033); phy_stacksave(0x04A7); phy_stacksave(0x04A3); phy_stacksave(0x04A9); phy_stacksave(0x04AA); phy_stacksave(0x04AC); phy_stacksave(0x0493); phy_stacksave(0x04A1); phy_stacksave(0x04A0); phy_stacksave(0x04A2); phy_stacksave(0x048A); phy_stacksave(0x04A8); phy_stacksave(0x04AB); if (phy->rev == 2) { phy_stacksave(0x04AD); phy_stacksave(0x04AE); } else if (phy->rev >= 3) { phy_stacksave(0x04AD); phy_stacksave(0x0415); phy_stacksave(0x0416); phy_stacksave(0x0417); ofdmtab_stacksave(0x1A00, 0x2); ofdmtab_stacksave(0x1A00, 0x3); } phy_stacksave(0x042B); phy_stacksave(0x048C); b43_phy_mask(dev, B43_PHY_RADIO_BITFIELD, ~0x1000); b43_phy_maskset(dev, B43_PHY_G_CRS, 0xFFFC, 0x0002); b43_phy_write(dev, 0x0033, 0x0800); b43_phy_write(dev, 0x04A3, 0x2027); b43_phy_write(dev, 0x04A9, 0x1CA8); b43_phy_write(dev, 0x0493, 0x287A); b43_phy_write(dev, 0x04AA, 0x1CA8); b43_phy_write(dev, 0x04AC, 0x287A); b43_phy_maskset(dev, 0x04A0, 0xFFC0, 0x001A); b43_phy_write(dev, 0x04A7, 0x000D); if (phy->rev < 2) { b43_phy_write(dev, 0x0406, 0xFF0D); } else if (phy->rev == 2) { b43_phy_write(dev, 0x04C0, 0xFFFF); b43_phy_write(dev, 0x04C1, 0x00A9); } else { b43_phy_write(dev, 0x04C0, 0x00C1); b43_phy_write(dev, 0x04C1, 0x0059); } b43_phy_maskset(dev, 0x04A1, 0xC0FF, 0x1800); b43_phy_maskset(dev, 0x04A1, 0xFFC0, 0x0015); b43_phy_maskset(dev, 0x04A8, 0xCFFF, 0x1000); b43_phy_maskset(dev, 0x04A8, 0xF0FF, 0x0A00); b43_phy_maskset(dev, 0x04AB, 0xCFFF, 0x1000); b43_phy_maskset(dev, 0x04AB, 0xF0FF, 0x0800); b43_phy_maskset(dev, 0x04AB, 0xFFCF, 0x0010); b43_phy_maskset(dev, 0x04AB, 0xFFF0, 0x0005); b43_phy_maskset(dev, 0x04A8, 0xFFCF, 0x0010); b43_phy_maskset(dev, 0x04A8, 0xFFF0, 0x0006); b43_phy_maskset(dev, 0x04A2, 0xF0FF, 0x0800); b43_phy_maskset(dev, 0x04A0, 0xF0FF, 0x0500); b43_phy_maskset(dev, 0x04A2, 0xFFF0, 0x000B); if (phy->rev >= 3) { b43_phy_mask(dev, 0x048A, 0x7FFF); b43_phy_maskset(dev, 0x0415, 0x8000, 0x36D8); b43_phy_maskset(dev, 0x0416, 0x8000, 0x36D8); b43_phy_maskset(dev, 0x0417, 0xFE00, 0x016D); } else { b43_phy_set(dev, 0x048A, 0x1000); b43_phy_maskset(dev, 0x048A, 0x9FFF, 0x2000); b43_hf_write(dev, b43_hf_read(dev) | B43_HF_ACIW); } if (phy->rev >= 2) { b43_phy_set(dev, 0x042B, 0x0800); } b43_phy_maskset(dev, 0x048C, 0xF0FF, 0x0200); if (phy->rev == 2) { b43_phy_maskset(dev, 0x04AE, 0xFF00, 0x007F); b43_phy_maskset(dev, 0x04AD, 0x00FF, 0x1300); } else if (phy->rev >= 6) { b43_ofdmtab_write16(dev, 0x1A00, 0x3, 0x007F); b43_ofdmtab_write16(dev, 0x1A00, 0x2, 0x007F); b43_phy_mask(dev, 0x04AD, 0x00FF); } b43_calc_nrssi_slope(dev); break; default: B43_WARN_ON(1); } } static void b43_radio_interference_mitigation_disable(struct b43_wldev *dev, int mode) { struct b43_phy *phy = &dev->phy; struct b43_phy_g *gphy = phy->g; u32 *stack = gphy->interfstack; switch (mode) { case B43_INTERFMODE_NONWLAN: if (phy->rev != 1) { b43_phy_mask(dev, 0x042B, ~0x0800); b43_phy_set(dev, B43_PHY_G_CRS, 0x4000); break; } radio_stackrestore(0x0078); b43_calc_nrssi_threshold(dev); phy_stackrestore(0x0406); b43_phy_mask(dev, 0x042B, ~0x0800); if (!dev->bad_frames_preempt) { b43_phy_mask(dev, B43_PHY_RADIO_BITFIELD, ~(1 << 11)); } b43_phy_set(dev, B43_PHY_G_CRS, 0x4000); phy_stackrestore(0x04A0); phy_stackrestore(0x04A1); phy_stackrestore(0x04A2); phy_stackrestore(0x04A8); phy_stackrestore(0x04AB); phy_stackrestore(0x04A7); phy_stackrestore(0x04A3); phy_stackrestore(0x04A9); phy_stackrestore(0x0493); phy_stackrestore(0x04AA); phy_stackrestore(0x04AC); break; case B43_INTERFMODE_MANUALWLAN: if (!(b43_phy_read(dev, 0x0033) & 0x0800)) break; gphy->aci_enable = false; phy_stackrestore(B43_PHY_RADIO_BITFIELD); phy_stackrestore(B43_PHY_G_CRS); phy_stackrestore(0x0033); phy_stackrestore(0x04A3); phy_stackrestore(0x04A9); phy_stackrestore(0x0493); phy_stackrestore(0x04AA); phy_stackrestore(0x04AC); phy_stackrestore(0x04A0); phy_stackrestore(0x04A7); if (phy->rev >= 2) { phy_stackrestore(0x04C0); phy_stackrestore(0x04C1); } else phy_stackrestore(0x0406); phy_stackrestore(0x04A1); phy_stackrestore(0x04AB); phy_stackrestore(0x04A8); if (phy->rev == 2) { phy_stackrestore(0x04AD); phy_stackrestore(0x04AE); } else if (phy->rev >= 3) { phy_stackrestore(0x04AD); phy_stackrestore(0x0415); phy_stackrestore(0x0416); phy_stackrestore(0x0417); ofdmtab_stackrestore(0x1A00, 0x2); ofdmtab_stackrestore(0x1A00, 0x3); } phy_stackrestore(0x04A2); phy_stackrestore(0x048A); phy_stackrestore(0x042B); phy_stackrestore(0x048C); b43_hf_write(dev, b43_hf_read(dev) & ~B43_HF_ACIW); b43_calc_nrssi_slope(dev); break; default: B43_WARN_ON(1); } } #undef phy_stacksave #undef phy_stackrestore #undef radio_stacksave #undef radio_stackrestore #undef ofdmtab_stacksave #undef ofdmtab_stackrestore static u16 b43_radio_core_calibration_value(struct b43_wldev *dev) { u16 reg, index, ret; static const u8 rcc_table[] = { 0x02, 0x03, 0x01, 0x0F, 0x06, 0x07, 0x05, 0x0F, 0x0A, 0x0B, 0x09, 0x0F, 0x0E, 0x0F, 0x0D, 0x0F, }; reg = b43_radio_read16(dev, 0x60); index = (reg & 0x001E) >> 1; ret = rcc_table[index] << 1; ret |= (reg & 0x0001); ret |= 0x0020; return ret; } #define LPD(L, P, D) (((L) << 2) | ((P) << 1) | ((D) << 0)) static u16 radio2050_rfover_val(struct b43_wldev *dev, u16 phy_register, unsigned int lpd) { struct b43_phy *phy = &dev->phy; struct b43_phy_g *gphy = phy->g; struct ssb_sprom *sprom = dev->dev->bus_sprom; if (!phy->gmode) return 0; if (has_loopback_gain(phy)) { int max_lb_gain = gphy->max_lb_gain; u16 extlna; u16 i; if (phy->radio_rev == 8) max_lb_gain += 0x3E; else max_lb_gain += 0x26; if (max_lb_gain >= 0x46) { extlna = 0x3000; max_lb_gain -= 0x46; } else if (max_lb_gain >= 0x3A) { extlna = 0x1000; max_lb_gain -= 0x3A; } else if (max_lb_gain >= 0x2E) { extlna = 0x2000; max_lb_gain -= 0x2E; } else { extlna = 0; max_lb_gain -= 0x10; } for (i = 0; i < 16; i++) { max_lb_gain -= (i * 6); if (max_lb_gain < 6) break; } if ((phy->rev < 7) || !(sprom->boardflags_lo & B43_BFL_EXTLNA)) { if (phy_register == B43_PHY_RFOVER) { return 0x1B3; } else if (phy_register == B43_PHY_RFOVERVAL) { extlna |= (i << 8); switch (lpd) { case LPD(0, 1, 1): return 0x0F92; case LPD(0, 0, 1): case LPD(1, 0, 1): return (0x0092 | extlna); case LPD(1, 0, 0): return (0x0093 | extlna); } B43_WARN_ON(1); } B43_WARN_ON(1); } else { if (phy_register == B43_PHY_RFOVER) { return 0x9B3; } else if (phy_register == B43_PHY_RFOVERVAL) { if (extlna) extlna |= 0x8000; extlna |= (i << 8); switch (lpd) { case LPD(0, 1, 1): return 0x8F92; case LPD(0, 0, 1): return (0x8092 | extlna); case LPD(1, 0, 1): return (0x2092 | extlna); case LPD(1, 0, 0): return (0x2093 | extlna); } B43_WARN_ON(1); } B43_WARN_ON(1); } } else { if ((phy->rev < 7) || !(sprom->boardflags_lo & B43_BFL_EXTLNA)) { if (phy_register == B43_PHY_RFOVER) { return 0x1B3; } else if (phy_register == B43_PHY_RFOVERVAL) { switch (lpd) { case LPD(0, 1, 1): return 0x0FB2; case LPD(0, 0, 1): return 0x00B2; case LPD(1, 0, 1): return 0x30B2; case LPD(1, 0, 0): return 0x30B3; } B43_WARN_ON(1); } B43_WARN_ON(1); } else { if (phy_register == B43_PHY_RFOVER) { return 0x9B3; } else if (phy_register == B43_PHY_RFOVERVAL) { switch (lpd) { case LPD(0, 1, 1): return 0x8FB2; case LPD(0, 0, 1): return 0x80B2; case LPD(1, 0, 1): return 0x20B2; case LPD(1, 0, 0): return 0x20B3; } B43_WARN_ON(1); } B43_WARN_ON(1); } } return 0; } struct init2050_saved_values { /* Core registers */ u16 reg_3EC; u16 reg_3E6; u16 reg_3F4; /* Radio registers */ u16 radio_43; u16 radio_51; u16 radio_52; /* PHY registers */ u16 phy_pgactl; u16 phy_cck_5A; u16 phy_cck_59; u16 phy_cck_58; u16 phy_cck_30; u16 phy_rfover; u16 phy_rfoverval; u16 phy_analogover; u16 phy_analogoverval; u16 phy_crs0; u16 phy_classctl; u16 phy_lo_mask; u16 phy_lo_ctl; u16 phy_syncctl; }; static u16 b43_radio_init2050(struct b43_wldev *dev) { struct b43_phy *phy = &dev->phy; struct init2050_saved_values sav; u16 rcc; u16 radio78; u16 ret; u16 i, j; u32 tmp1 = 0, tmp2 = 0; memset(&sav, 0, sizeof(sav)); /* get rid of "may be used uninitialized..." */ sav.radio_43 = b43_radio_read16(dev, 0x43); sav.radio_51 = b43_radio_read16(dev, 0x51); sav.radio_52 = b43_radio_read16(dev, 0x52); sav.phy_pgactl = b43_phy_read(dev, B43_PHY_PGACTL); sav.phy_cck_5A = b43_phy_read(dev, B43_PHY_CCK(0x5A)); sav.phy_cck_59 = b43_phy_read(dev, B43_PHY_CCK(0x59)); sav.phy_cck_58 = b43_phy_read(dev, B43_PHY_CCK(0x58)); if (phy->type == B43_PHYTYPE_B) { sav.phy_cck_30 = b43_phy_read(dev, B43_PHY_CCK(0x30)); sav.reg_3EC = b43_read16(dev, 0x3EC); b43_phy_write(dev, B43_PHY_CCK(0x30), 0xFF); b43_write16(dev, 0x3EC, 0x3F3F); } else if (phy->gmode || phy->rev >= 2) { sav.phy_rfover = b43_phy_read(dev, B43_PHY_RFOVER); sav.phy_rfoverval = b43_phy_read(dev, B43_PHY_RFOVERVAL); sav.phy_analogover = b43_phy_read(dev, B43_PHY_ANALOGOVER); sav.phy_analogoverval = b43_phy_read(dev, B43_PHY_ANALOGOVERVAL); sav.phy_crs0 = b43_phy_read(dev, B43_PHY_CRS0); sav.phy_classctl = b43_phy_read(dev, B43_PHY_CLASSCTL); b43_phy_set(dev, B43_PHY_ANALOGOVER, 0x0003); b43_phy_mask(dev, B43_PHY_ANALOGOVERVAL, 0xFFFC); b43_phy_mask(dev, B43_PHY_CRS0, 0x7FFF); b43_phy_mask(dev, B43_PHY_CLASSCTL, 0xFFFC); if (has_loopback_gain(phy)) { sav.phy_lo_mask = b43_phy_read(dev, B43_PHY_LO_MASK); sav.phy_lo_ctl = b43_phy_read(dev, B43_PHY_LO_CTL); if (phy->rev >= 3) b43_phy_write(dev, B43_PHY_LO_MASK, 0xC020); else b43_phy_write(dev, B43_PHY_LO_MASK, 0x8020); b43_phy_write(dev, B43_PHY_LO_CTL, 0); } b43_phy_write(dev, B43_PHY_RFOVERVAL, radio2050_rfover_val(dev, B43_PHY_RFOVERVAL, LPD(0, 1, 1))); b43_phy_write(dev, B43_PHY_RFOVER, radio2050_rfover_val(dev, B43_PHY_RFOVER, 0)); } b43_write16(dev, 0x3E2, b43_read16(dev, 0x3E2) | 0x8000); sav.phy_syncctl = b43_phy_read(dev, B43_PHY_SYNCCTL); b43_phy_mask(dev, B43_PHY_SYNCCTL, 0xFF7F); sav.reg_3E6 = b43_read16(dev, 0x3E6); sav.reg_3F4 = b43_read16(dev, 0x3F4); if (phy->analog == 0) { b43_write16(dev, 0x03E6, 0x0122); } else { if (phy->analog >= 2) { b43_phy_maskset(dev, B43_PHY_CCK(0x03), 0xFFBF, 0x40); } b43_write16(dev, B43_MMIO_CHANNEL_EXT, (b43_read16(dev, B43_MMIO_CHANNEL_EXT) | 0x2000)); } rcc = b43_radio_core_calibration_value(dev); if (phy->type == B43_PHYTYPE_B) b43_radio_write16(dev, 0x78, 0x26); if (phy->gmode || phy->rev >= 2) { b43_phy_write(dev, B43_PHY_RFOVERVAL, radio2050_rfover_val(dev, B43_PHY_RFOVERVAL, LPD(0, 1, 1))); } b43_phy_write(dev, B43_PHY_PGACTL, 0xBFAF); b43_phy_write(dev, B43_PHY_CCK(0x2B), 0x1403); if (phy->gmode || phy->rev >= 2) { b43_phy_write(dev, B43_PHY_RFOVERVAL, radio2050_rfover_val(dev, B43_PHY_RFOVERVAL, LPD(0, 0, 1))); } b43_phy_write(dev, B43_PHY_PGACTL, 0xBFA0); b43_radio_set(dev, 0x51, 0x0004); if (phy->radio_rev == 8) { b43_radio_write16(dev, 0x43, 0x1F); } else { b43_radio_write16(dev, 0x52, 0); b43_radio_maskset(dev, 0x43, 0xFFF0, 0x0009); } b43_phy_write(dev, B43_PHY_CCK(0x58), 0); for (i = 0; i < 16; i++) { b43_phy_write(dev, B43_PHY_CCK(0x5A), 0x0480); b43_phy_write(dev, B43_PHY_CCK(0x59), 0xC810); b43_phy_write(dev, B43_PHY_CCK(0x58), 0x000D); if (phy->gmode || phy->rev >= 2) { b43_phy_write(dev, B43_PHY_RFOVERVAL, radio2050_rfover_val(dev, B43_PHY_RFOVERVAL, LPD(1, 0, 1))); } b43_phy_write(dev, B43_PHY_PGACTL, 0xAFB0); udelay(10); if (phy->gmode || phy->rev >= 2) { b43_phy_write(dev, B43_PHY_RFOVERVAL, radio2050_rfover_val(dev, B43_PHY_RFOVERVAL, LPD(1, 0, 1))); } b43_phy_write(dev, B43_PHY_PGACTL, 0xEFB0); udelay(10); if (phy->gmode || phy->rev >= 2) { b43_phy_write(dev, B43_PHY_RFOVERVAL, radio2050_rfover_val(dev, B43_PHY_RFOVERVAL, LPD(1, 0, 0))); } b43_phy_write(dev, B43_PHY_PGACTL, 0xFFF0); udelay(20); tmp1 += b43_phy_read(dev, B43_PHY_LO_LEAKAGE); b43_phy_write(dev, B43_PHY_CCK(0x58), 0); if (phy->gmode || phy->rev >= 2) { b43_phy_write(dev, B43_PHY_RFOVERVAL, radio2050_rfover_val(dev, B43_PHY_RFOVERVAL, LPD(1, 0, 1))); } b43_phy_write(dev, B43_PHY_PGACTL, 0xAFB0); } udelay(10); b43_phy_write(dev, B43_PHY_CCK(0x58), 0); tmp1++; tmp1 >>= 9; for (i = 0; i < 16; i++) { radio78 = (bitrev4(i) << 1) | 0x0020; b43_radio_write16(dev, 0x78, radio78); udelay(10); for (j = 0; j < 16; j++) { b43_phy_write(dev, B43_PHY_CCK(0x5A), 0x0D80); b43_phy_write(dev, B43_PHY_CCK(0x59), 0xC810); b43_phy_write(dev, B43_PHY_CCK(0x58), 0x000D); if (phy->gmode || phy->rev >= 2) { b43_phy_write(dev, B43_PHY_RFOVERVAL, radio2050_rfover_val(dev, B43_PHY_RFOVERVAL, LPD(1, 0, 1))); } b43_phy_write(dev, B43_PHY_PGACTL, 0xAFB0); udelay(10); if (phy->gmode || phy->rev >= 2) { b43_phy_write(dev, B43_PHY_RFOVERVAL, radio2050_rfover_val(dev, B43_PHY_RFOVERVAL, LPD(1, 0, 1))); } b43_phy_write(dev, B43_PHY_PGACTL, 0xEFB0); udelay(10); if (phy->gmode || phy->rev >= 2) { b43_phy_write(dev, B43_PHY_RFOVERVAL, radio2050_rfover_val(dev, B43_PHY_RFOVERVAL, LPD(1, 0, 0))); } b43_phy_write(dev, B43_PHY_PGACTL, 0xFFF0); udelay(10); tmp2 += b43_phy_read(dev, B43_PHY_LO_LEAKAGE); b43_phy_write(dev, B43_PHY_CCK(0x58), 0); if (phy->gmode || phy->rev >= 2) { b43_phy_write(dev, B43_PHY_RFOVERVAL, radio2050_rfover_val(dev, B43_PHY_RFOVERVAL, LPD(1, 0, 1))); } b43_phy_write(dev, B43_PHY_PGACTL, 0xAFB0); } tmp2++; tmp2 >>= 8; if (tmp1 < tmp2) break; } /* Restore the registers */ b43_phy_write(dev, B43_PHY_PGACTL, sav.phy_pgactl); b43_radio_write16(dev, 0x51, sav.radio_51); b43_radio_write16(dev, 0x52, sav.radio_52); b43_radio_write16(dev, 0x43, sav.radio_43); b43_phy_write(dev, B43_PHY_CCK(0x5A), sav.phy_cck_5A); b43_phy_write(dev, B43_PHY_CCK(0x59), sav.phy_cck_59); b43_phy_write(dev, B43_PHY_CCK(0x58), sav.phy_cck_58); b43_write16(dev, 0x3E6, sav.reg_3E6); if (phy->analog != 0) b43_write16(dev, 0x3F4, sav.reg_3F4); b43_phy_write(dev, B43_PHY_SYNCCTL, sav.phy_syncctl); b43_synth_pu_workaround(dev, phy->channel); if (phy->type == B43_PHYTYPE_B) { b43_phy_write(dev, B43_PHY_CCK(0x30), sav.phy_cck_30); b43_write16(dev, 0x3EC, sav.reg_3EC); } else if (phy->gmode) { b43_write16(dev, B43_MMIO_PHY_RADIO, b43_read16(dev, B43_MMIO_PHY_RADIO) & 0x7FFF); b43_phy_write(dev, B43_PHY_RFOVER, sav.phy_rfover); b43_phy_write(dev, B43_PHY_RFOVERVAL, sav.phy_rfoverval); b43_phy_write(dev, B43_PHY_ANALOGOVER, sav.phy_analogover); b43_phy_write(dev, B43_PHY_ANALOGOVERVAL, sav.phy_analogoverval); b43_phy_write(dev, B43_PHY_CRS0, sav.phy_crs0); b43_phy_write(dev, B43_PHY_CLASSCTL, sav.phy_classctl); if (has_loopback_gain(phy)) { b43_phy_write(dev, B43_PHY_LO_MASK, sav.phy_lo_mask); b43_phy_write(dev, B43_PHY_LO_CTL, sav.phy_lo_ctl); } } if (i > 15) ret = radio78; else ret = rcc; return ret; } static void b43_phy_initb5(struct b43_wldev *dev) { struct b43_phy *phy = &dev->phy; struct b43_phy_g *gphy = phy->g; u16 offset, value; u8 old_channel; if (phy->analog == 1) { b43_radio_set(dev, 0x007A, 0x0050); } if ((dev->dev->board_vendor != SSB_BOARDVENDOR_BCM) && (dev->dev->board_type != SSB_BOARD_BU4306)) { value = 0x2120; for (offset = 0x00A8; offset < 0x00C7; offset++) { b43_phy_write(dev, offset, value); value += 0x202; } } b43_phy_maskset(dev, 0x0035, 0xF0FF, 0x0700); if (phy->radio_ver == 0x2050) b43_phy_write(dev, 0x0038, 0x0667); if (phy->gmode || phy->rev >= 2) { if (phy->radio_ver == 0x2050) { b43_radio_set(dev, 0x007A, 0x0020); b43_radio_set(dev, 0x0051, 0x0004); } b43_write16(dev, B43_MMIO_PHY_RADIO, 0x0000); b43_phy_set(dev, 0x0802, 0x0100); b43_phy_set(dev, 0x042B, 0x2000); b43_phy_write(dev, 0x001C, 0x186A); b43_phy_maskset(dev, 0x0013, 0x00FF, 0x1900); b43_phy_maskset(dev, 0x0035, 0xFFC0, 0x0064); b43_phy_maskset(dev, 0x005D, 0xFF80, 0x000A); } if (dev->bad_frames_preempt) { b43_phy_set(dev, B43_PHY_RADIO_BITFIELD, (1 << 11)); } if (phy->analog == 1) { b43_phy_write(dev, 0x0026, 0xCE00); b43_phy_write(dev, 0x0021, 0x3763); b43_phy_write(dev, 0x0022, 0x1BC3); b43_phy_write(dev, 0x0023, 0x06F9); b43_phy_write(dev, 0x0024, 0x037E); } else b43_phy_write(dev, 0x0026, 0xCC00); b43_phy_write(dev, 0x0030, 0x00C6); b43_write16(dev, 0x03EC, 0x3F22); if (phy->analog == 1) b43_phy_write(dev, 0x0020, 0x3E1C); else b43_phy_write(dev, 0x0020, 0x301C); if (phy->analog == 0) b43_write16(dev, 0x03E4, 0x3000); old_channel = phy->channel; /* Force to channel 7, even if not supported. */ b43_gphy_channel_switch(dev, 7, 0); if (phy->radio_ver != 0x2050) { b43_radio_write16(dev, 0x0075, 0x0080); b43_radio_write16(dev, 0x0079, 0x0081); } b43_radio_write16(dev, 0x0050, 0x0020); b43_radio_write16(dev, 0x0050, 0x0023); if (phy->radio_ver == 0x2050) { b43_radio_write16(dev, 0x0050, 0x0020); b43_radio_write16(dev, 0x005A, 0x0070); } b43_radio_write16(dev, 0x005B, 0x007B); b43_radio_write16(dev, 0x005C, 0x00B0); b43_radio_set(dev, 0x007A, 0x0007); b43_gphy_channel_switch(dev, old_channel, 0); b43_phy_write(dev, 0x0014, 0x0080); b43_phy_write(dev, 0x0032, 0x00CA); b43_phy_write(dev, 0x002A, 0x88A3); b43_set_txpower_g(dev, &gphy->bbatt, &gphy->rfatt, gphy->tx_control); if (phy->radio_ver == 0x2050) b43_radio_write16(dev, 0x005D, 0x000D); b43_write16(dev, 0x03E4, (b43_read16(dev, 0x03E4) & 0xFFC0) | 0x0004); } static void b43_phy_initb6(struct b43_wldev *dev) { struct b43_phy *phy = &dev->phy; struct b43_phy_g *gphy = phy->g; u16 offset, val; u8 old_channel; b43_phy_write(dev, 0x003E, 0x817A); b43_radio_write16(dev, 0x007A, (b43_radio_read16(dev, 0x007A) | 0x0058)); if (phy->radio_rev == 4 || phy->radio_rev == 5) { b43_radio_write16(dev, 0x51, 0x37); b43_radio_write16(dev, 0x52, 0x70); b43_radio_write16(dev, 0x53, 0xB3); b43_radio_write16(dev, 0x54, 0x9B); b43_radio_write16(dev, 0x5A, 0x88); b43_radio_write16(dev, 0x5B, 0x88); b43_radio_write16(dev, 0x5D, 0x88); b43_radio_write16(dev, 0x5E, 0x88); b43_radio_write16(dev, 0x7D, 0x88); b43_hf_write(dev, b43_hf_read(dev) | B43_HF_TSSIRPSMW); } B43_WARN_ON(phy->radio_rev == 6 || phy->radio_rev == 7); /* We had code for these revs here... */ if (phy->radio_rev == 8) { b43_radio_write16(dev, 0x51, 0); b43_radio_write16(dev, 0x52, 0x40); b43_radio_write16(dev, 0x53, 0xB7); b43_radio_write16(dev, 0x54, 0x98); b43_radio_write16(dev, 0x5A, 0x88); b43_radio_write16(dev, 0x5B, 0x6B); b43_radio_write16(dev, 0x5C, 0x0F); if (dev->dev->bus_sprom->boardflags_lo & B43_BFL_ALTIQ) { b43_radio_write16(dev, 0x5D, 0xFA); b43_radio_write16(dev, 0x5E, 0xD8); } else { b43_radio_write16(dev, 0x5D, 0xF5); b43_radio_write16(dev, 0x5E, 0xB8); } b43_radio_write16(dev, 0x0073, 0x0003); b43_radio_write16(dev, 0x007D, 0x00A8); b43_radio_write16(dev, 0x007C, 0x0001); b43_radio_write16(dev, 0x007E, 0x0008); } val = 0x1E1F; for (offset = 0x0088; offset < 0x0098; offset++) { b43_phy_write(dev, offset, val); val -= 0x0202; } val = 0x3E3F; for (offset = 0x0098; offset < 0x00A8; offset++) { b43_phy_write(dev, offset, val); val -= 0x0202; } val = 0x2120; for (offset = 0x00A8; offset < 0x00C8; offset++) { b43_phy_write(dev, offset, (val & 0x3F3F)); val += 0x0202; } if (phy->type == B43_PHYTYPE_G) { b43_radio_set(dev, 0x007A, 0x0020); b43_radio_set(dev, 0x0051, 0x0004); b43_phy_set(dev, 0x0802, 0x0100); b43_phy_set(dev, 0x042B, 0x2000); b43_phy_write(dev, 0x5B, 0); b43_phy_write(dev, 0x5C, 0); } old_channel = phy->channel; if (old_channel >= 8) b43_gphy_channel_switch(dev, 1, 0); else b43_gphy_channel_switch(dev, 13, 0); b43_radio_write16(dev, 0x0050, 0x0020); b43_radio_write16(dev, 0x0050, 0x0023); udelay(40); if (phy->radio_rev < 6 || phy->radio_rev == 8) { b43_radio_write16(dev, 0x7C, (b43_radio_read16(dev, 0x7C) | 0x0002)); b43_radio_write16(dev, 0x50, 0x20); } if (phy->radio_rev <= 2) { b43_radio_write16(dev, 0x7C, 0x20); b43_radio_write16(dev, 0x5A, 0x70); b43_radio_write16(dev, 0x5B, 0x7B); b43_radio_write16(dev, 0x5C, 0xB0); } b43_radio_maskset(dev, 0x007A, 0x00F8, 0x0007); b43_gphy_channel_switch(dev, old_channel, 0); b43_phy_write(dev, 0x0014, 0x0200); if (phy->radio_rev >= 6) b43_phy_write(dev, 0x2A, 0x88C2); else b43_phy_write(dev, 0x2A, 0x8AC0); b43_phy_write(dev, 0x0038, 0x0668); b43_set_txpower_g(dev, &gphy->bbatt, &gphy->rfatt, gphy->tx_control); if (phy->radio_rev <= 5) { b43_phy_maskset(dev, 0x5D, 0xFF80, 0x0003); } if (phy->radio_rev <= 2) b43_radio_write16(dev, 0x005D, 0x000D); if (phy->analog == 4) { b43_write16(dev, 0x3E4, 9); b43_phy_mask(dev, 0x61, 0x0FFF); } else { b43_phy_maskset(dev, 0x0002, 0xFFC0, 0x0004); } if (phy->type == B43_PHYTYPE_B) B43_WARN_ON(1); else if (phy->type == B43_PHYTYPE_G) b43_write16(dev, 0x03E6, 0x0); } static void b43_calc_loopback_gain(struct b43_wldev *dev) { struct b43_phy *phy = &dev->phy; struct b43_phy_g *gphy = phy->g; u16 backup_phy[16] = { 0 }; u16 backup_radio[3]; u16 backup_bband; u16 i, j, loop_i_max; u16 trsw_rx; u16 loop1_outer_done, loop1_inner_done; backup_phy[0] = b43_phy_read(dev, B43_PHY_CRS0); backup_phy[1] = b43_phy_read(dev, B43_PHY_CCKBBANDCFG); backup_phy[2] = b43_phy_read(dev, B43_PHY_RFOVER); backup_phy[3] = b43_phy_read(dev, B43_PHY_RFOVERVAL); if (phy->rev != 1) { /* Not in specs, but needed to prevent PPC machine check */ backup_phy[4] = b43_phy_read(dev, B43_PHY_ANALOGOVER); backup_phy[5] = b43_phy_read(dev, B43_PHY_ANALOGOVERVAL); } backup_phy[6] = b43_phy_read(dev, B43_PHY_CCK(0x5A)); backup_phy[7] = b43_phy_read(dev, B43_PHY_CCK(0x59)); backup_phy[8] = b43_phy_read(dev, B43_PHY_CCK(0x58)); backup_phy[9] = b43_phy_read(dev, B43_PHY_CCK(0x0A)); backup_phy[10] = b43_phy_read(dev, B43_PHY_CCK(0x03)); backup_phy[11] = b43_phy_read(dev, B43_PHY_LO_MASK); backup_phy[12] = b43_phy_read(dev, B43_PHY_LO_CTL); backup_phy[13] = b43_phy_read(dev, B43_PHY_CCK(0x2B)); backup_phy[14] = b43_phy_read(dev, B43_PHY_PGACTL); backup_phy[15] = b43_phy_read(dev, B43_PHY_LO_LEAKAGE); backup_bband = gphy->bbatt.att; backup_radio[0] = b43_radio_read16(dev, 0x52); backup_radio[1] = b43_radio_read16(dev, 0x43); backup_radio[2] = b43_radio_read16(dev, 0x7A); b43_phy_mask(dev, B43_PHY_CRS0, 0x3FFF); b43_phy_set(dev, B43_PHY_CCKBBANDCFG, 0x8000); b43_phy_set(dev, B43_PHY_RFOVER, 0x0002); b43_phy_mask(dev, B43_PHY_RFOVERVAL, 0xFFFD); b43_phy_set(dev, B43_PHY_RFOVER, 0x0001); b43_phy_mask(dev, B43_PHY_RFOVERVAL, 0xFFFE); if (phy->rev != 1) { /* Not in specs, but needed to prevent PPC machine check */ b43_phy_set(dev, B43_PHY_ANALOGOVER, 0x0001); b43_phy_mask(dev, B43_PHY_ANALOGOVERVAL, 0xFFFE); b43_phy_set(dev, B43_PHY_ANALOGOVER, 0x0002); b43_phy_mask(dev, B43_PHY_ANALOGOVERVAL, 0xFFFD); } b43_phy_set(dev, B43_PHY_RFOVER, 0x000C); b43_phy_set(dev, B43_PHY_RFOVERVAL, 0x000C); b43_phy_set(dev, B43_PHY_RFOVER, 0x0030); b43_phy_maskset(dev, B43_PHY_RFOVERVAL, 0xFFCF, 0x10); b43_phy_write(dev, B43_PHY_CCK(0x5A), 0x0780); b43_phy_write(dev, B43_PHY_CCK(0x59), 0xC810); b43_phy_write(dev, B43_PHY_CCK(0x58), 0x000D); b43_phy_set(dev, B43_PHY_CCK(0x0A), 0x2000); if (phy->rev != 1) { /* Not in specs, but needed to prevent PPC machine check */ b43_phy_set(dev, B43_PHY_ANALOGOVER, 0x0004); b43_phy_mask(dev, B43_PHY_ANALOGOVERVAL, 0xFFFB); } b43_phy_maskset(dev, B43_PHY_CCK(0x03), 0xFF9F, 0x40); if (phy->radio_rev == 8) { b43_radio_write16(dev, 0x43, 0x000F); } else { b43_radio_write16(dev, 0x52, 0); b43_radio_maskset(dev, 0x43, 0xFFF0, 0x9); } b43_gphy_set_baseband_attenuation(dev, 11); if (phy->rev >= 3) b43_phy_write(dev, B43_PHY_LO_MASK, 0xC020); else b43_phy_write(dev, B43_PHY_LO_MASK, 0x8020); b43_phy_write(dev, B43_PHY_LO_CTL, 0); b43_phy_maskset(dev, B43_PHY_CCK(0x2B), 0xFFC0, 0x01); b43_phy_maskset(dev, B43_PHY_CCK(0x2B), 0xC0FF, 0x800); b43_phy_set(dev, B43_PHY_RFOVER, 0x0100); b43_phy_mask(dev, B43_PHY_RFOVERVAL, 0xCFFF); if (dev->dev->bus_sprom->boardflags_lo & B43_BFL_EXTLNA) { if (phy->rev >= 7) { b43_phy_set(dev, B43_PHY_RFOVER, 0x0800); b43_phy_set(dev, B43_PHY_RFOVERVAL, 0x8000); } } b43_radio_mask(dev, 0x7A, 0x00F7); j = 0; loop_i_max = (phy->radio_rev == 8) ? 15 : 9; for (i = 0; i < loop_i_max; i++) { for (j = 0; j < 16; j++) { b43_radio_write16(dev, 0x43, i); b43_phy_maskset(dev, B43_PHY_RFOVERVAL, 0xF0FF, (j << 8)); b43_phy_maskset(dev, B43_PHY_PGACTL, 0x0FFF, 0xA000); b43_phy_set(dev, B43_PHY_PGACTL, 0xF000); udelay(20); if (b43_phy_read(dev, B43_PHY_LO_LEAKAGE) >= 0xDFC) goto exit_loop1; } } exit_loop1: loop1_outer_done = i; loop1_inner_done = j; if (j >= 8) { b43_phy_set(dev, B43_PHY_RFOVERVAL, 0x30); trsw_rx = 0x1B; for (j = j - 8; j < 16; j++) { b43_phy_maskset(dev, B43_PHY_RFOVERVAL, 0xF0FF, (j << 8)); b43_phy_maskset(dev, B43_PHY_PGACTL, 0x0FFF, 0xA000); b43_phy_set(dev, B43_PHY_PGACTL, 0xF000); udelay(20); trsw_rx -= 3; if (b43_phy_read(dev, B43_PHY_LO_LEAKAGE) >= 0xDFC) goto exit_loop2; } } else trsw_rx = 0x18; exit_loop2: if (phy->rev != 1) { /* Not in specs, but needed to prevent PPC machine check */ b43_phy_write(dev, B43_PHY_ANALOGOVER, backup_phy[4]); b43_phy_write(dev, B43_PHY_ANALOGOVERVAL, backup_phy[5]); } b43_phy_write(dev, B43_PHY_CCK(0x5A), backup_phy[6]); b43_phy_write(dev, B43_PHY_CCK(0x59), backup_phy[7]); b43_phy_write(dev, B43_PHY_CCK(0x58), backup_phy[8]); b43_phy_write(dev, B43_PHY_CCK(0x0A), backup_phy[9]); b43_phy_write(dev, B43_PHY_CCK(0x03), backup_phy[10]); b43_phy_write(dev, B43_PHY_LO_MASK, backup_phy[11]); b43_phy_write(dev, B43_PHY_LO_CTL, backup_phy[12]); b43_phy_write(dev, B43_PHY_CCK(0x2B), backup_phy[13]); b43_phy_write(dev, B43_PHY_PGACTL, backup_phy[14]); b43_gphy_set_baseband_attenuation(dev, backup_bband); b43_radio_write16(dev, 0x52, backup_radio[0]); b43_radio_write16(dev, 0x43, backup_radio[1]); b43_radio_write16(dev, 0x7A, backup_radio[2]); b43_phy_write(dev, B43_PHY_RFOVER, backup_phy[2] | 0x0003); udelay(10); b43_phy_write(dev, B43_PHY_RFOVER, backup_phy[2]); b43_phy_write(dev, B43_PHY_RFOVERVAL, backup_phy[3]); b43_phy_write(dev, B43_PHY_CRS0, backup_phy[0]); b43_phy_write(dev, B43_PHY_CCKBBANDCFG, backup_phy[1]); gphy->max_lb_gain = ((loop1_inner_done * 6) - (loop1_outer_done * 4)) - 11; gphy->trsw_rx_gain = trsw_rx * 2; } static void b43_hardware_pctl_early_init(struct b43_wldev *dev) { struct b43_phy *phy = &dev->phy; if (!b43_has_hardware_pctl(dev)) { b43_phy_write(dev, 0x047A, 0xC111); return; } b43_phy_mask(dev, 0x0036, 0xFEFF); b43_phy_write(dev, 0x002F, 0x0202); b43_phy_set(dev, 0x047C, 0x0002); b43_phy_set(dev, 0x047A, 0xF000); if (phy->radio_ver == 0x2050 && phy->radio_rev == 8) { b43_phy_maskset(dev, 0x047A, 0xFF0F, 0x0010); b43_phy_set(dev, 0x005D, 0x8000); b43_phy_maskset(dev, 0x004E, 0xFFC0, 0x0010); b43_phy_write(dev, 0x002E, 0xC07F); b43_phy_set(dev, 0x0036, 0x0400); } else { b43_phy_set(dev, 0x0036, 0x0200); b43_phy_set(dev, 0x0036, 0x0400); b43_phy_mask(dev, 0x005D, 0x7FFF); b43_phy_mask(dev, 0x004F, 0xFFFE); b43_phy_maskset(dev, 0x004E, 0xFFC0, 0x0010); b43_phy_write(dev, 0x002E, 0xC07F); b43_phy_maskset(dev, 0x047A, 0xFF0F, 0x0010); } } /* Hardware power control for G-PHY */ static void b43_hardware_pctl_init_gphy(struct b43_wldev *dev) { struct b43_phy *phy = &dev->phy; struct b43_phy_g *gphy = phy->g; if (!b43_has_hardware_pctl(dev)) { /* No hardware power control */ b43_hf_write(dev, b43_hf_read(dev) & ~B43_HF_HWPCTL); return; } b43_phy_maskset(dev, 0x0036, 0xFFC0, (gphy->tgt_idle_tssi - gphy->cur_idle_tssi)); b43_phy_maskset(dev, 0x0478, 0xFF00, (gphy->tgt_idle_tssi - gphy->cur_idle_tssi)); b43_gphy_tssi_power_lt_init(dev); b43_gphy_gain_lt_init(dev); b43_phy_mask(dev, 0x0060, 0xFFBF); b43_phy_write(dev, 0x0014, 0x0000); B43_WARN_ON(phy->rev < 6); b43_phy_set(dev, 0x0478, 0x0800); b43_phy_mask(dev, 0x0478, 0xFEFF); b43_phy_mask(dev, 0x0801, 0xFFBF); b43_gphy_dc_lt_init(dev, 1); /* Enable hardware pctl in firmware. */ b43_hf_write(dev, b43_hf_read(dev) | B43_HF_HWPCTL); } /* Initialize B/G PHY power control */ static void b43_phy_init_pctl(struct b43_wldev *dev) { struct b43_phy *phy = &dev->phy; struct b43_phy_g *gphy = phy->g; struct b43_rfatt old_rfatt; struct b43_bbatt old_bbatt; u8 old_tx_control = 0; B43_WARN_ON(phy->type != B43_PHYTYPE_G); if ((dev->dev->board_vendor == SSB_BOARDVENDOR_BCM) && (dev->dev->board_type == SSB_BOARD_BU4306)) return; b43_phy_write(dev, 0x0028, 0x8018); /* This does something with the Analog... */ b43_write16(dev, B43_MMIO_PHY0, b43_read16(dev, B43_MMIO_PHY0) & 0xFFDF); if (!phy->gmode) return; b43_hardware_pctl_early_init(dev); if (gphy->cur_idle_tssi == 0) { if (phy->radio_ver == 0x2050 && phy->analog == 0) { b43_radio_maskset(dev, 0x0076, 0x00F7, 0x0084); } else { struct b43_rfatt rfatt; struct b43_bbatt bbatt; memcpy(&old_rfatt, &gphy->rfatt, sizeof(old_rfatt)); memcpy(&old_bbatt, &gphy->bbatt, sizeof(old_bbatt)); old_tx_control = gphy->tx_control; bbatt.att = 11; if (phy->radio_rev == 8) { rfatt.att = 15; rfatt.with_padmix = true; } else { rfatt.att = 9; rfatt.with_padmix = false; } b43_set_txpower_g(dev, &bbatt, &rfatt, 0); } b43_dummy_transmission(dev, false, true); gphy->cur_idle_tssi = b43_phy_read(dev, B43_PHY_ITSSI); if (B43_DEBUG) { /* Current-Idle-TSSI sanity check. */ if (abs(gphy->cur_idle_tssi - gphy->tgt_idle_tssi) >= 20) { b43dbg(dev->wl, "!WARNING! Idle-TSSI phy->cur_idle_tssi " "measuring failed. (cur=%d, tgt=%d). Disabling TX power " "adjustment.\n", gphy->cur_idle_tssi, gphy->tgt_idle_tssi); gphy->cur_idle_tssi = 0; } } if (phy->radio_ver == 0x2050 && phy->analog == 0) { b43_radio_mask(dev, 0x0076, 0xFF7B); } else { b43_set_txpower_g(dev, &old_bbatt, &old_rfatt, old_tx_control); } } b43_hardware_pctl_init_gphy(dev); b43_shm_clear_tssi(dev); } static void b43_phy_initg(struct b43_wldev *dev) { struct b43_phy *phy = &dev->phy; struct b43_phy_g *gphy = phy->g; u16 tmp; if (phy->rev == 1) b43_phy_initb5(dev); else b43_phy_initb6(dev); if (phy->rev >= 2 || phy->gmode) b43_phy_inita(dev); if (phy->rev >= 2) { b43_phy_write(dev, B43_PHY_ANALOGOVER, 0); b43_phy_write(dev, B43_PHY_ANALOGOVERVAL, 0); } if (phy->rev == 2) { b43_phy_write(dev, B43_PHY_RFOVER, 0); b43_phy_write(dev, B43_PHY_PGACTL, 0xC0); } if (phy->rev > 5) { b43_phy_write(dev, B43_PHY_RFOVER, 0x400); b43_phy_write(dev, B43_PHY_PGACTL, 0xC0); } if (phy->gmode || phy->rev >= 2) { tmp = b43_phy_read(dev, B43_PHY_VERSION_OFDM); tmp &= B43_PHYVER_VERSION; if (tmp == 3 || tmp == 5) { b43_phy_write(dev, B43_PHY_OFDM(0xC2), 0x1816); b43_phy_write(dev, B43_PHY_OFDM(0xC3), 0x8006); } if (tmp == 5) { b43_phy_maskset(dev, B43_PHY_OFDM(0xCC), 0x00FF, 0x1F00); } } if ((phy->rev <= 2 && phy->gmode) || phy->rev >= 2) b43_phy_write(dev, B43_PHY_OFDM(0x7E), 0x78); if (phy->radio_rev == 8) { b43_phy_set(dev, B43_PHY_EXTG(0x01), 0x80); b43_phy_set(dev, B43_PHY_OFDM(0x3E), 0x4); } if (has_loopback_gain(phy)) b43_calc_loopback_gain(dev); if (phy->radio_rev != 8) { if (gphy->initval == 0xFFFF) gphy->initval = b43_radio_init2050(dev); else b43_radio_write16(dev, 0x0078, gphy->initval); } b43_lo_g_init(dev); if (has_tx_magnification(phy)) { b43_radio_write16(dev, 0x52, (b43_radio_read16(dev, 0x52) & 0xFF00) | gphy->lo_control->tx_bias | gphy-> lo_control->tx_magn); } else { b43_radio_maskset(dev, 0x52, 0xFFF0, gphy->lo_control->tx_bias); } if (phy->rev >= 6) { b43_phy_maskset(dev, B43_PHY_CCK(0x36), 0x0FFF, (gphy->lo_control->tx_bias << 12)); } if (dev->dev->bus_sprom->boardflags_lo & B43_BFL_PACTRL) b43_phy_write(dev, B43_PHY_CCK(0x2E), 0x8075); else b43_phy_write(dev, B43_PHY_CCK(0x2E), 0x807F); if (phy->rev < 2) b43_phy_write(dev, B43_PHY_CCK(0x2F), 0x101); else b43_phy_write(dev, B43_PHY_CCK(0x2F), 0x202); if (phy->gmode || phy->rev >= 2) { b43_lo_g_adjust(dev); b43_phy_write(dev, B43_PHY_LO_MASK, 0x8078); } if (!(dev->dev->bus_sprom->boardflags_lo & B43_BFL_RSSI)) { /* The specs state to update the NRSSI LT with * the value 0x7FFFFFFF here. I think that is some weird * compiler optimization in the original driver. * Essentially, what we do here is resetting all NRSSI LT * entries to -32 (see the clamp_val() in nrssi_hw_update()) */ b43_nrssi_hw_update(dev, 0xFFFF); //FIXME? b43_calc_nrssi_threshold(dev); } else if (phy->gmode || phy->rev >= 2) { if (gphy->nrssi[0] == -1000) { B43_WARN_ON(gphy->nrssi[1] != -1000); b43_calc_nrssi_slope(dev); } else b43_calc_nrssi_threshold(dev); } if (phy->radio_rev == 8) b43_phy_write(dev, B43_PHY_EXTG(0x05), 0x3230); b43_phy_init_pctl(dev); /* FIXME: The spec says in the following if, the 0 should be replaced 'if OFDM may not be used in the current locale' but OFDM is legal everywhere */ if ((dev->dev->chip_id == 0x4306 && dev->dev->chip_pkg == 2) || 0) { b43_phy_mask(dev, B43_PHY_CRS0, 0xBFFF); b43_phy_mask(dev, B43_PHY_OFDM(0xC3), 0x7FFF); } } void b43_gphy_channel_switch(struct b43_wldev *dev, unsigned int channel, bool synthetic_pu_workaround) { if (synthetic_pu_workaround) b43_synth_pu_workaround(dev, channel); b43_write16(dev, B43_MMIO_CHANNEL, channel2freq_bg(channel)); if (channel == 14) { if (dev->dev->bus_sprom->country_code == SSB_SPROM1CCODE_JAPAN) b43_hf_write(dev, b43_hf_read(dev) & ~B43_HF_ACPR); else b43_hf_write(dev, b43_hf_read(dev) | B43_HF_ACPR); b43_write16(dev, B43_MMIO_CHANNEL_EXT, b43_read16(dev, B43_MMIO_CHANNEL_EXT) | (1 << 11)); } else { b43_write16(dev, B43_MMIO_CHANNEL_EXT, b43_read16(dev, B43_MMIO_CHANNEL_EXT) & 0xF7BF); } } static void default_baseband_attenuation(struct b43_wldev *dev, struct b43_bbatt *bb) { struct b43_phy *phy = &dev->phy; if (phy->radio_ver == 0x2050 && phy->radio_rev < 6) bb->att = 0; else bb->att = 2; } static void default_radio_attenuation(struct b43_wldev *dev, struct b43_rfatt *rf) { struct b43_bus_dev *bdev = dev->dev; struct b43_phy *phy = &dev->phy; rf->with_padmix = false; if (dev->dev->board_vendor == SSB_BOARDVENDOR_BCM && dev->dev->board_type == SSB_BOARD_BCM4309G) { if (dev->dev->board_rev < 0x43) { rf->att = 2; return; } else if (dev->dev->board_rev < 0x51) { rf->att = 3; return; } } if (phy->type == B43_PHYTYPE_A) { rf->att = 0x60; return; } switch (phy->radio_ver) { case 0x2053: switch (phy->radio_rev) { case 1: rf->att = 6; return; } break; case 0x2050: switch (phy->radio_rev) { case 0: rf->att = 5; return; case 1: if (phy->type == B43_PHYTYPE_G) { if (bdev->board_vendor == SSB_BOARDVENDOR_BCM && bdev->board_type == SSB_BOARD_BCM4309G && bdev->board_rev >= 30) rf->att = 3; else if (bdev->board_vendor == SSB_BOARDVENDOR_BCM && bdev->board_type == SSB_BOARD_BU4306) rf->att = 3; else rf->att = 1; } else { if (bdev->board_vendor == SSB_BOARDVENDOR_BCM && bdev->board_type == SSB_BOARD_BCM4309G && bdev->board_rev >= 30) rf->att = 7; else rf->att = 6; } return; case 2: if (phy->type == B43_PHYTYPE_G) { if (bdev->board_vendor == SSB_BOARDVENDOR_BCM && bdev->board_type == SSB_BOARD_BCM4309G && bdev->board_rev >= 30) rf->att = 3; else if (bdev->board_vendor == SSB_BOARDVENDOR_BCM && bdev->board_type == SSB_BOARD_BU4306) rf->att = 5; else if (bdev->chip_id == 0x4320) rf->att = 4; else rf->att = 3; } else rf->att = 6; return; case 3: rf->att = 5; return; case 4: case 5: rf->att = 1; return; case 6: case 7: rf->att = 5; return; case 8: rf->att = 0xA; rf->with_padmix = true; return; case 9: default: rf->att = 5; return; } } rf->att = 5; } static u16 default_tx_control(struct b43_wldev *dev) { struct b43_phy *phy = &dev->phy; if (phy->radio_ver != 0x2050) return 0; if (phy->radio_rev == 1) return B43_TXCTL_PA2DB | B43_TXCTL_TXMIX; if (phy->radio_rev < 6) return B43_TXCTL_PA2DB; if (phy->radio_rev == 8) return B43_TXCTL_TXMIX; return 0; } static u8 b43_gphy_aci_detect(struct b43_wldev *dev, u8 channel) { struct b43_phy *phy = &dev->phy; struct b43_phy_g *gphy = phy->g; u8 ret = 0; u16 saved, rssi, temp; int i, j = 0; saved = b43_phy_read(dev, 0x0403); b43_switch_channel(dev, channel); b43_phy_write(dev, 0x0403, (saved & 0xFFF8) | 5); if (gphy->aci_hw_rssi) rssi = b43_phy_read(dev, 0x048A) & 0x3F; else rssi = saved & 0x3F; /* clamp temp to signed 5bit */ if (rssi > 32) rssi -= 64; for (i = 0; i < 100; i++) { temp = (b43_phy_read(dev, 0x047F) >> 8) & 0x3F; if (temp > 32) temp -= 64; if (temp < rssi) j++; if (j >= 20) ret = 1; } b43_phy_write(dev, 0x0403, saved); return ret; } static u8 b43_gphy_aci_scan(struct b43_wldev *dev) { struct b43_phy *phy = &dev->phy; u8 ret[13]; unsigned int channel = phy->channel; unsigned int i, j, start, end; if (!((phy->type == B43_PHYTYPE_G) && (phy->rev > 0))) return 0; b43_phy_lock(dev); b43_radio_lock(dev); b43_phy_mask(dev, 0x0802, 0xFFFC); b43_phy_mask(dev, B43_PHY_G_CRS, 0x7FFF); b43_set_all_gains(dev, 3, 8, 1); start = (channel - 5 > 0) ? channel - 5 : 1; end = (channel + 5 < 14) ? channel + 5 : 13; for (i = start; i <= end; i++) { if (abs(channel - i) > 2) ret[i - 1] = b43_gphy_aci_detect(dev, i); } b43_switch_channel(dev, channel); b43_phy_maskset(dev, 0x0802, 0xFFFC, 0x0003); b43_phy_mask(dev, 0x0403, 0xFFF8); b43_phy_set(dev, B43_PHY_G_CRS, 0x8000); b43_set_original_gains(dev); for (i = 0; i < 13; i++) { if (!ret[i]) continue; end = (i + 5 < 13) ? i + 5 : 13; for (j = i; j < end; j++) ret[j] = 1; } b43_radio_unlock(dev); b43_phy_unlock(dev); return ret[channel - 1]; } static s32 b43_tssi2dbm_ad(s32 num, s32 den) { if (num < 0) return num / den; else return (num + den / 2) / den; } static s8 b43_tssi2dbm_entry(s8 entry[], u8 index, s16 pab0, s16 pab1, s16 pab2) { s32 m1, m2, f = 256, q, delta; s8 i = 0; m1 = b43_tssi2dbm_ad(16 * pab0 + index * pab1, 32); m2 = max(b43_tssi2dbm_ad(32768 + index * pab2, 256), 1); do { if (i > 15) return -EINVAL; q = b43_tssi2dbm_ad(f * 4096 - b43_tssi2dbm_ad(m2 * f, 16) * f, 2048); delta = abs(q - f); f = q; i++; } while (delta >= 2); entry[index] = clamp_val(b43_tssi2dbm_ad(m1 * f, 8192), -127, 128); return 0; } u8 *b43_generate_dyn_tssi2dbm_tab(struct b43_wldev *dev, s16 pab0, s16 pab1, s16 pab2) { unsigned int i; u8 *tab; int err; tab = kmalloc(64, GFP_KERNEL); if (!tab) { b43err(dev->wl, "Could not allocate memory " "for tssi2dbm table\n"); return NULL; } for (i = 0; i < 64; i++) { err = b43_tssi2dbm_entry(tab, i, pab0, pab1, pab2); if (err) { b43err(dev->wl, "Could not generate " "tssi2dBm table\n"); kfree(tab); return NULL; } } return tab; } /* Initialise the TSSI->dBm lookup table */ static int b43_gphy_init_tssi2dbm_table(struct b43_wldev *dev) { struct b43_phy *phy = &dev->phy; struct b43_phy_g *gphy = phy->g; s16 pab0, pab1, pab2; pab0 = (s16) (dev->dev->bus_sprom->pa0b0); pab1 = (s16) (dev->dev->bus_sprom->pa0b1); pab2 = (s16) (dev->dev->bus_sprom->pa0b2); B43_WARN_ON((dev->dev->chip_id == 0x4301) && (phy->radio_ver != 0x2050)); /* Not supported anymore */ gphy->dyn_tssi_tbl = false; if (pab0 != 0 && pab1 != 0 && pab2 != 0 && pab0 != -1 && pab1 != -1 && pab2 != -1) { /* The pabX values are set in SPROM. Use them. */ if ((s8) dev->dev->bus_sprom->itssi_bg != 0 && (s8) dev->dev->bus_sprom->itssi_bg != -1) { gphy->tgt_idle_tssi = (s8) (dev->dev->bus_sprom->itssi_bg); } else gphy->tgt_idle_tssi = 62; gphy->tssi2dbm = b43_generate_dyn_tssi2dbm_tab(dev, pab0, pab1, pab2); if (!gphy->tssi2dbm) return -ENOMEM; gphy->dyn_tssi_tbl = true; } else { /* pabX values not set in SPROM. */ gphy->tgt_idle_tssi = 52; gphy->tssi2dbm = b43_tssi2dbm_g_table; } return 0; } static int b43_gphy_op_allocate(struct b43_wldev *dev) { struct b43_phy_g *gphy; struct b43_txpower_lo_control *lo; int err; gphy = kzalloc(sizeof(*gphy), GFP_KERNEL); if (!gphy) { err = -ENOMEM; goto error; } dev->phy.g = gphy; lo = kzalloc(sizeof(*lo), GFP_KERNEL); if (!lo) { err = -ENOMEM; goto err_free_gphy; } gphy->lo_control = lo; err = b43_gphy_init_tssi2dbm_table(dev); if (err) goto err_free_lo; return 0; err_free_lo: kfree(lo); err_free_gphy: kfree(gphy); error: return err; } static void b43_gphy_op_prepare_structs(struct b43_wldev *dev) { struct b43_phy *phy = &dev->phy; struct b43_phy_g *gphy = phy->g; const void *tssi2dbm; int tgt_idle_tssi; struct b43_txpower_lo_control *lo; unsigned int i; /* tssi2dbm table is constant, so it is initialized at alloc time. * Save a copy of the pointer. */ tssi2dbm = gphy->tssi2dbm; tgt_idle_tssi = gphy->tgt_idle_tssi; /* Save the LO pointer. */ lo = gphy->lo_control; /* Zero out the whole PHY structure. */ memset(gphy, 0, sizeof(*gphy)); /* Restore pointers. */ gphy->tssi2dbm = tssi2dbm; gphy->tgt_idle_tssi = tgt_idle_tssi; gphy->lo_control = lo; memset(gphy->minlowsig, 0xFF, sizeof(gphy->minlowsig)); /* NRSSI */ for (i = 0; i < ARRAY_SIZE(gphy->nrssi); i++) gphy->nrssi[i] = -1000; for (i = 0; i < ARRAY_SIZE(gphy->nrssi_lt); i++) gphy->nrssi_lt[i] = i; gphy->lofcal = 0xFFFF; gphy->initval = 0xFFFF; gphy->interfmode = B43_INTERFMODE_NONE; /* OFDM-table address caching. */ gphy->ofdmtab_addr_direction = B43_OFDMTAB_DIRECTION_UNKNOWN; gphy->average_tssi = 0xFF; /* Local Osciallator structure */ lo->tx_bias = 0xFF; INIT_LIST_HEAD(&lo->calib_list); } static void b43_gphy_op_free(struct b43_wldev *dev) { struct b43_phy *phy = &dev->phy; struct b43_phy_g *gphy = phy->g; kfree(gphy->lo_control); if (gphy->dyn_tssi_tbl) kfree(gphy->tssi2dbm); gphy->dyn_tssi_tbl = false; gphy->tssi2dbm = NULL; kfree(gphy); dev->phy.g = NULL; } static int b43_gphy_op_prepare_hardware(struct b43_wldev *dev) { struct b43_phy *phy = &dev->phy; struct b43_phy_g *gphy = phy->g; struct b43_txpower_lo_control *lo = gphy->lo_control; B43_WARN_ON(phy->type != B43_PHYTYPE_G); default_baseband_attenuation(dev, &gphy->bbatt); default_radio_attenuation(dev, &gphy->rfatt); gphy->tx_control = (default_tx_control(dev) << 4); generate_rfatt_list(dev, &lo->rfatt_list); generate_bbatt_list(dev, &lo->bbatt_list); /* Commit previous writes */ b43_read32(dev, B43_MMIO_MACCTL); if (phy->rev == 1) { /* Workaround: Temporarly disable gmode through the early init * phase, as the gmode stuff is not needed for phy rev 1 */ phy->gmode = false; b43_wireless_core_reset(dev, 0); b43_phy_initg(dev); phy->gmode = true; b43_wireless_core_reset(dev, 1); } return 0; } static int b43_gphy_op_init(struct b43_wldev *dev) { b43_phy_initg(dev); return 0; } static void b43_gphy_op_exit(struct b43_wldev *dev) { b43_lo_g_cleanup(dev); } static u16 b43_gphy_op_read(struct b43_wldev *dev, u16 reg) { b43_write16(dev, B43_MMIO_PHY_CONTROL, reg); return b43_read16(dev, B43_MMIO_PHY_DATA); } static void b43_gphy_op_write(struct b43_wldev *dev, u16 reg, u16 value) { b43_write16(dev, B43_MMIO_PHY_CONTROL, reg); b43_write16(dev, B43_MMIO_PHY_DATA, value); } static u16 b43_gphy_op_radio_read(struct b43_wldev *dev, u16 reg) { /* Register 1 is a 32-bit register. */ B43_WARN_ON(reg == 1); /* G-PHY needs 0x80 for read access. */ reg |= 0x80; b43_write16(dev, B43_MMIO_RADIO_CONTROL, reg); return b43_read16(dev, B43_MMIO_RADIO_DATA_LOW); } static void b43_gphy_op_radio_write(struct b43_wldev *dev, u16 reg, u16 value) { /* Register 1 is a 32-bit register. */ B43_WARN_ON(reg == 1); b43_write16(dev, B43_MMIO_RADIO_CONTROL, reg); b43_write16(dev, B43_MMIO_RADIO_DATA_LOW, value); } static bool b43_gphy_op_supports_hwpctl(struct b43_wldev *dev) { return (dev->phy.rev >= 6); } static void b43_gphy_op_software_rfkill(struct b43_wldev *dev, bool blocked) { struct b43_phy *phy = &dev->phy; struct b43_phy_g *gphy = phy->g; unsigned int channel; might_sleep(); if (!blocked) { /* Turn radio ON */ if (phy->radio_on) return; b43_phy_write(dev, 0x0015, 0x8000); b43_phy_write(dev, 0x0015, 0xCC00); b43_phy_write(dev, 0x0015, (phy->gmode ? 0x00C0 : 0x0000)); if (gphy->radio_off_context.valid) { /* Restore the RFover values. */ b43_phy_write(dev, B43_PHY_RFOVER, gphy->radio_off_context.rfover); b43_phy_write(dev, B43_PHY_RFOVERVAL, gphy->radio_off_context.rfoverval); gphy->radio_off_context.valid = false; } channel = phy->channel; b43_gphy_channel_switch(dev, 6, 1); b43_gphy_channel_switch(dev, channel, 0); } else { /* Turn radio OFF */ u16 rfover, rfoverval; rfover = b43_phy_read(dev, B43_PHY_RFOVER); rfoverval = b43_phy_read(dev, B43_PHY_RFOVERVAL); gphy->radio_off_context.rfover = rfover; gphy->radio_off_context.rfoverval = rfoverval; gphy->radio_off_context.valid = true; b43_phy_write(dev, B43_PHY_RFOVER, rfover | 0x008C); b43_phy_write(dev, B43_PHY_RFOVERVAL, rfoverval & 0xFF73); } } static int b43_gphy_op_switch_channel(struct b43_wldev *dev, unsigned int new_channel) { if ((new_channel < 1) || (new_channel > 14)) return -EINVAL; b43_gphy_channel_switch(dev, new_channel, 0); return 0; } static unsigned int b43_gphy_op_get_default_chan(struct b43_wldev *dev) { return 1; /* Default to channel 1 */ } static void b43_gphy_op_set_rx_antenna(struct b43_wldev *dev, int antenna) { struct b43_phy *phy = &dev->phy; u16 tmp; int autodiv = 0; if (antenna == B43_ANTENNA_AUTO0 || antenna == B43_ANTENNA_AUTO1) autodiv = 1; b43_hf_write(dev, b43_hf_read(dev) & ~B43_HF_ANTDIVHELP); b43_phy_maskset(dev, B43_PHY_BBANDCFG, ~B43_PHY_BBANDCFG_RXANT, (autodiv ? B43_ANTENNA_AUTO1 : antenna) << B43_PHY_BBANDCFG_RXANT_SHIFT); if (autodiv) { tmp = b43_phy_read(dev, B43_PHY_ANTDWELL); if (antenna == B43_ANTENNA_AUTO1) tmp &= ~B43_PHY_ANTDWELL_AUTODIV1; else tmp |= B43_PHY_ANTDWELL_AUTODIV1; b43_phy_write(dev, B43_PHY_ANTDWELL, tmp); } tmp = b43_phy_read(dev, B43_PHY_ANTWRSETT); if (autodiv) tmp |= B43_PHY_ANTWRSETT_ARXDIV; else tmp &= ~B43_PHY_ANTWRSETT_ARXDIV; b43_phy_write(dev, B43_PHY_ANTWRSETT, tmp); if (autodiv) b43_phy_set(dev, B43_PHY_ANTWRSETT, B43_PHY_ANTWRSETT_ARXDIV); else { b43_phy_mask(dev, B43_PHY_ANTWRSETT, B43_PHY_ANTWRSETT_ARXDIV); } if (phy->rev >= 2) { b43_phy_set(dev, B43_PHY_OFDM61, B43_PHY_OFDM61_10); b43_phy_maskset(dev, B43_PHY_DIVSRCHGAINBACK, 0xFF00, 0x15); if (phy->rev == 2) b43_phy_write(dev, B43_PHY_ADIVRELATED, 8); else b43_phy_maskset(dev, B43_PHY_ADIVRELATED, 0xFF00, 8); } if (phy->rev >= 6) b43_phy_write(dev, B43_PHY_OFDM9B, 0xDC); b43_hf_write(dev, b43_hf_read(dev) | B43_HF_ANTDIVHELP); } static int b43_gphy_op_interf_mitigation(struct b43_wldev *dev, enum b43_interference_mitigation mode) { struct b43_phy *phy = &dev->phy; struct b43_phy_g *gphy = phy->g; int currentmode; B43_WARN_ON(phy->type != B43_PHYTYPE_G); if ((phy->rev == 0) || (!phy->gmode)) return -ENODEV; gphy->aci_wlan_automatic = false; switch (mode) { case B43_INTERFMODE_AUTOWLAN: gphy->aci_wlan_automatic = true; if (gphy->aci_enable) mode = B43_INTERFMODE_MANUALWLAN; else mode = B43_INTERFMODE_NONE; break; case B43_INTERFMODE_NONE: case B43_INTERFMODE_NONWLAN: case B43_INTERFMODE_MANUALWLAN: break; default: return -EINVAL; } currentmode = gphy->interfmode; if (currentmode == mode) return 0; if (currentmode != B43_INTERFMODE_NONE) b43_radio_interference_mitigation_disable(dev, currentmode); if (mode == B43_INTERFMODE_NONE) { gphy->aci_enable = false; gphy->aci_hw_rssi = false; } else b43_radio_interference_mitigation_enable(dev, mode); gphy->interfmode = mode; return 0; } /* http://bcm-specs.sipsolutions.net/EstimatePowerOut * This function converts a TSSI value to dBm in Q5.2 */ static s8 b43_gphy_estimate_power_out(struct b43_wldev *dev, s8 tssi) { struct b43_phy_g *gphy = dev->phy.g; s8 dbm; s32 tmp; tmp = (gphy->tgt_idle_tssi - gphy->cur_idle_tssi + tssi); tmp = clamp_val(tmp, 0x00, 0x3F); dbm = gphy->tssi2dbm[tmp]; return dbm; } static void b43_put_attenuation_into_ranges(struct b43_wldev *dev, int *_bbatt, int *_rfatt) { int rfatt = *_rfatt; int bbatt = *_bbatt; struct b43_txpower_lo_control *lo = dev->phy.g->lo_control; /* Get baseband and radio attenuation values into their permitted ranges. * Radio attenuation affects power level 4 times as much as baseband. */ /* Range constants */ const int rf_min = lo->rfatt_list.min_val; const int rf_max = lo->rfatt_list.max_val; const int bb_min = lo->bbatt_list.min_val; const int bb_max = lo->bbatt_list.max_val; while (1) { if (rfatt > rf_max && bbatt > bb_max - 4) break; /* Can not get it into ranges */ if (rfatt < rf_min && bbatt < bb_min + 4) break; /* Can not get it into ranges */ if (bbatt > bb_max && rfatt > rf_max - 1) break; /* Can not get it into ranges */ if (bbatt < bb_min && rfatt < rf_min + 1) break; /* Can not get it into ranges */ if (bbatt > bb_max) { bbatt -= 4; rfatt += 1; continue; } if (bbatt < bb_min) { bbatt += 4; rfatt -= 1; continue; } if (rfatt > rf_max) { rfatt -= 1; bbatt += 4; continue; } if (rfatt < rf_min) { rfatt += 1; bbatt -= 4; continue; } break; } *_rfatt = clamp_val(rfatt, rf_min, rf_max); *_bbatt = clamp_val(bbatt, bb_min, bb_max); } static void b43_gphy_op_adjust_txpower(struct b43_wldev *dev) { struct b43_phy *phy = &dev->phy; struct b43_phy_g *gphy = phy->g; int rfatt, bbatt; u8 tx_control; b43_mac_suspend(dev); /* Calculate the new attenuation values. */ bbatt = gphy->bbatt.att; bbatt += gphy->bbatt_delta; rfatt = gphy->rfatt.att; rfatt += gphy->rfatt_delta; b43_put_attenuation_into_ranges(dev, &bbatt, &rfatt); tx_control = gphy->tx_control; if ((phy->radio_ver == 0x2050) && (phy->radio_rev == 2)) { if (rfatt <= 1) { if (tx_control == 0) { tx_control = B43_TXCTL_PA2DB | B43_TXCTL_TXMIX; rfatt += 2; bbatt += 2; } else if (dev->dev->bus_sprom-> boardflags_lo & B43_BFL_PACTRL) { bbatt += 4 * (rfatt - 2); rfatt = 2; } } else if (rfatt > 4 && tx_control) { tx_control = 0; if (bbatt < 3) { rfatt -= 3; bbatt += 2; } else { rfatt -= 2; bbatt -= 2; } } } /* Save the control values */ gphy->tx_control = tx_control; b43_put_attenuation_into_ranges(dev, &bbatt, &rfatt); gphy->rfatt.att = rfatt; gphy->bbatt.att = bbatt; if (b43_debug(dev, B43_DBG_XMITPOWER)) b43dbg(dev->wl, "Adjusting TX power\n"); /* Adjust the hardware */ b43_phy_lock(dev); b43_radio_lock(dev); b43_set_txpower_g(dev, &gphy->bbatt, &gphy->rfatt, gphy->tx_control); b43_radio_unlock(dev); b43_phy_unlock(dev); b43_mac_enable(dev); } static enum b43_txpwr_result b43_gphy_op_recalc_txpower(struct b43_wldev *dev, bool ignore_tssi) { struct b43_phy *phy = &dev->phy; struct b43_phy_g *gphy = phy->g; unsigned int average_tssi; int cck_result, ofdm_result; int estimated_pwr, desired_pwr, pwr_adjust; int rfatt_delta, bbatt_delta; unsigned int max_pwr; /* First get the average TSSI */ cck_result = b43_phy_shm_tssi_read(dev, B43_SHM_SH_TSSI_CCK); ofdm_result = b43_phy_shm_tssi_read(dev, B43_SHM_SH_TSSI_OFDM_G); if ((cck_result < 0) && (ofdm_result < 0)) { /* No TSSI information available */ if (!ignore_tssi) goto no_adjustment_needed; cck_result = 0; ofdm_result = 0; } if (cck_result < 0) average_tssi = ofdm_result; else if (ofdm_result < 0) average_tssi = cck_result; else average_tssi = (cck_result + ofdm_result) / 2; /* Merge the average with the stored value. */ if (likely(gphy->average_tssi != 0xFF)) average_tssi = (average_tssi + gphy->average_tssi) / 2; gphy->average_tssi = average_tssi; B43_WARN_ON(average_tssi >= B43_TSSI_MAX); /* Estimate the TX power emission based on the TSSI */ estimated_pwr = b43_gphy_estimate_power_out(dev, average_tssi); B43_WARN_ON(phy->type != B43_PHYTYPE_G); max_pwr = dev->dev->bus_sprom->maxpwr_bg; if (dev->dev->bus_sprom->boardflags_lo & B43_BFL_PACTRL) max_pwr -= 3; /* minus 0.75 */ if (unlikely(max_pwr >= INT_TO_Q52(30/*dBm*/))) { b43warn(dev->wl, "Invalid max-TX-power value in SPROM.\n"); max_pwr = INT_TO_Q52(20); /* fake it */ dev->dev->bus_sprom->maxpwr_bg = max_pwr; } /* Get desired power (in Q5.2) */ if (phy->desired_txpower < 0) desired_pwr = INT_TO_Q52(0); else desired_pwr = INT_TO_Q52(phy->desired_txpower); /* And limit it. max_pwr already is Q5.2 */ desired_pwr = clamp_val(desired_pwr, 0, max_pwr); if (b43_debug(dev, B43_DBG_XMITPOWER)) { b43dbg(dev->wl, "[TX power] current = " Q52_FMT " dBm, desired = " Q52_FMT " dBm, max = " Q52_FMT "\n", Q52_ARG(estimated_pwr), Q52_ARG(desired_pwr), Q52_ARG(max_pwr)); } /* Calculate the adjustment delta. */ pwr_adjust = desired_pwr - estimated_pwr; if (pwr_adjust == 0) goto no_adjustment_needed; /* RF attenuation delta. */ rfatt_delta = ((pwr_adjust + 7) / 8); /* Lower attenuation => Bigger power output. Negate it. */ rfatt_delta = -rfatt_delta; /* Baseband attenuation delta. */ bbatt_delta = pwr_adjust / 2; /* Lower attenuation => Bigger power output. Negate it. */ bbatt_delta = -bbatt_delta; /* RF att affects power level 4 times as much as * Baseband attennuation. Subtract it. */ bbatt_delta -= 4 * rfatt_delta; #if B43_DEBUG if (b43_debug(dev, B43_DBG_XMITPOWER)) { int dbm = pwr_adjust < 0 ? -pwr_adjust : pwr_adjust; b43dbg(dev->wl, "[TX power deltas] %s" Q52_FMT " dBm => " "bbatt-delta = %d, rfatt-delta = %d\n", (pwr_adjust < 0 ? "-" : ""), Q52_ARG(dbm), bbatt_delta, rfatt_delta); } #endif /* DEBUG */ /* So do we finally need to adjust something in hardware? */ if ((rfatt_delta == 0) && (bbatt_delta == 0)) goto no_adjustment_needed; /* Save the deltas for later when we adjust the power. */ gphy->bbatt_delta = bbatt_delta; gphy->rfatt_delta = rfatt_delta; /* We need to adjust the TX power on the device. */ return B43_TXPWR_RES_NEED_ADJUST; no_adjustment_needed: return B43_TXPWR_RES_DONE; } static void b43_gphy_op_pwork_15sec(struct b43_wldev *dev) { struct b43_phy *phy = &dev->phy; struct b43_phy_g *gphy = phy->g; b43_mac_suspend(dev); //TODO: update_aci_moving_average if (gphy->aci_enable && gphy->aci_wlan_automatic) { if (!gphy->aci_enable && 1 /*TODO: not scanning? */ ) { if (0 /*TODO: bunch of conditions */ ) { phy->ops->interf_mitigation(dev, B43_INTERFMODE_MANUALWLAN); } } else if (0 /*TODO*/) { if (/*(aci_average > 1000) &&*/ !b43_gphy_aci_scan(dev)) phy->ops->interf_mitigation(dev, B43_INTERFMODE_NONE); } } else if (gphy->interfmode == B43_INTERFMODE_NONWLAN && phy->rev == 1) { //TODO: implement rev1 workaround } b43_lo_g_maintanance_work(dev); b43_mac_enable(dev); } static void b43_gphy_op_pwork_60sec(struct b43_wldev *dev) { struct b43_phy *phy = &dev->phy; if (!(dev->dev->bus_sprom->boardflags_lo & B43_BFL_RSSI)) return; b43_mac_suspend(dev); b43_calc_nrssi_slope(dev); if ((phy->radio_ver == 0x2050) && (phy->radio_rev == 8)) { u8 old_chan = phy->channel; /* VCO Calibration */ if (old_chan >= 8) b43_switch_channel(dev, 1); else b43_switch_channel(dev, 13); b43_switch_channel(dev, old_chan); } b43_mac_enable(dev); } const struct b43_phy_operations b43_phyops_g = { .allocate = b43_gphy_op_allocate, .free = b43_gphy_op_free, .prepare_structs = b43_gphy_op_prepare_structs, .prepare_hardware = b43_gphy_op_prepare_hardware, .init = b43_gphy_op_init, .exit = b43_gphy_op_exit, .phy_read = b43_gphy_op_read, .phy_write = b43_gphy_op_write, .radio_read = b43_gphy_op_radio_read, .radio_write = b43_gphy_op_radio_write, .supports_hwpctl = b43_gphy_op_supports_hwpctl, .software_rfkill = b43_gphy_op_software_rfkill, .switch_analog = b43_phyop_switch_analog_generic, .switch_channel = b43_gphy_op_switch_channel, .get_default_chan = b43_gphy_op_get_default_chan, .set_rx_antenna = b43_gphy_op_set_rx_antenna, .interf_mitigation = b43_gphy_op_interf_mitigation, .recalc_txpower = b43_gphy_op_recalc_txpower, .adjust_txpower = b43_gphy_op_adjust_txpower, .pwork_15sec = b43_gphy_op_pwork_15sec, .pwork_60sec = b43_gphy_op_pwork_60sec, };
gpl-2.0
marc1706/desire_kernel_35
drivers/scsi/bfa/bfa_ioim.c
767
31766
/* * Copyright (c) 2005-2009 Brocade Communications Systems, Inc. * All rights reserved * www.brocade.com * * Linux driver for Brocade Fibre Channel Host Bus Adapter. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License (GPL) 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 <bfa.h> #include <cs/bfa_debug.h> #include <bfa_cb_ioim_macros.h> BFA_TRC_FILE(HAL, IOIM); /* * forward declarations. */ static bfa_boolean_t bfa_ioim_send_ioreq(struct bfa_ioim_s *ioim); static bfa_boolean_t bfa_ioim_sge_setup(struct bfa_ioim_s *ioim); static void bfa_ioim_sgpg_setup(struct bfa_ioim_s *ioim); static bfa_boolean_t bfa_ioim_send_abort(struct bfa_ioim_s *ioim); static void bfa_ioim_notify_cleanup(struct bfa_ioim_s *ioim); static void __bfa_cb_ioim_good_comp(void *cbarg, bfa_boolean_t complete); static void __bfa_cb_ioim_comp(void *cbarg, bfa_boolean_t complete); static void __bfa_cb_ioim_abort(void *cbarg, bfa_boolean_t complete); static void __bfa_cb_ioim_failed(void *cbarg, bfa_boolean_t complete); static void __bfa_cb_ioim_pathtov(void *cbarg, bfa_boolean_t complete); /** * bfa_ioim_sm */ /** * IO state machine events */ enum bfa_ioim_event { BFA_IOIM_SM_START = 1, /* io start request from host */ BFA_IOIM_SM_COMP_GOOD = 2, /* io good comp, resource free */ BFA_IOIM_SM_COMP = 3, /* io comp, resource is free */ BFA_IOIM_SM_COMP_UTAG = 4, /* io comp, resource is free */ BFA_IOIM_SM_DONE = 5, /* io comp, resource not free */ BFA_IOIM_SM_FREE = 6, /* io resource is freed */ BFA_IOIM_SM_ABORT = 7, /* abort request from scsi stack */ BFA_IOIM_SM_ABORT_COMP = 8, /* abort from f/w */ BFA_IOIM_SM_ABORT_DONE = 9, /* abort completion from f/w */ BFA_IOIM_SM_QRESUME = 10, /* CQ space available to queue IO */ BFA_IOIM_SM_SGALLOCED = 11, /* SG page allocation successful */ BFA_IOIM_SM_SQRETRY = 12, /* sequence recovery retry */ BFA_IOIM_SM_HCB = 13, /* bfa callback complete */ BFA_IOIM_SM_CLEANUP = 14, /* IO cleanup from itnim */ BFA_IOIM_SM_TMSTART = 15, /* IO cleanup from tskim */ BFA_IOIM_SM_TMDONE = 16, /* IO cleanup from tskim */ BFA_IOIM_SM_HWFAIL = 17, /* IOC h/w failure event */ BFA_IOIM_SM_IOTOV = 18, /* ITN offline TOV */ }; /* * forward declaration of IO state machine */ static void bfa_ioim_sm_uninit(struct bfa_ioim_s *ioim, enum bfa_ioim_event event); static void bfa_ioim_sm_sgalloc(struct bfa_ioim_s *ioim, enum bfa_ioim_event event); static void bfa_ioim_sm_active(struct bfa_ioim_s *ioim, enum bfa_ioim_event event); static void bfa_ioim_sm_abort(struct bfa_ioim_s *ioim, enum bfa_ioim_event event); static void bfa_ioim_sm_cleanup(struct bfa_ioim_s *ioim, enum bfa_ioim_event event); static void bfa_ioim_sm_qfull(struct bfa_ioim_s *ioim, enum bfa_ioim_event event); static void bfa_ioim_sm_abort_qfull(struct bfa_ioim_s *ioim, enum bfa_ioim_event event); static void bfa_ioim_sm_cleanup_qfull(struct bfa_ioim_s *ioim, enum bfa_ioim_event event); static void bfa_ioim_sm_hcb(struct bfa_ioim_s *ioim, enum bfa_ioim_event event); static void bfa_ioim_sm_hcb_free(struct bfa_ioim_s *ioim, enum bfa_ioim_event event); static void bfa_ioim_sm_resfree(struct bfa_ioim_s *ioim, enum bfa_ioim_event event); /** * IO is not started (unallocated). */ static void bfa_ioim_sm_uninit(struct bfa_ioim_s *ioim, enum bfa_ioim_event event) { bfa_trc_fp(ioim->bfa, ioim->iotag); bfa_trc_fp(ioim->bfa, event); switch (event) { case BFA_IOIM_SM_START: if (!bfa_itnim_is_online(ioim->itnim)) { if (!bfa_itnim_hold_io(ioim->itnim)) { bfa_sm_set_state(ioim, bfa_ioim_sm_hcb); list_del(&ioim->qe); list_add_tail(&ioim->qe, &ioim->fcpim->ioim_comp_q); bfa_cb_queue(ioim->bfa, &ioim->hcb_qe, __bfa_cb_ioim_pathtov, ioim); } else { list_del(&ioim->qe); list_add_tail(&ioim->qe, &ioim->itnim->pending_q); } break; } if (ioim->nsges > BFI_SGE_INLINE) { if (!bfa_ioim_sge_setup(ioim)) { bfa_sm_set_state(ioim, bfa_ioim_sm_sgalloc); return; } } if (!bfa_ioim_send_ioreq(ioim)) { bfa_sm_set_state(ioim, bfa_ioim_sm_qfull); break; } bfa_sm_set_state(ioim, bfa_ioim_sm_active); break; case BFA_IOIM_SM_IOTOV: bfa_sm_set_state(ioim, bfa_ioim_sm_hcb); bfa_cb_queue(ioim->bfa, &ioim->hcb_qe, __bfa_cb_ioim_pathtov, ioim); break; case BFA_IOIM_SM_ABORT: /** * IO in pending queue can get abort requests. Complete abort * requests immediately. */ bfa_sm_set_state(ioim, bfa_ioim_sm_hcb); bfa_assert(bfa_q_is_on_q(&ioim->itnim->pending_q, ioim)); bfa_cb_queue(ioim->bfa, &ioim->hcb_qe, __bfa_cb_ioim_abort, ioim); break; default: bfa_sm_fault(ioim->bfa, event); } } /** * IO is waiting for SG pages. */ static void bfa_ioim_sm_sgalloc(struct bfa_ioim_s *ioim, enum bfa_ioim_event event) { bfa_trc(ioim->bfa, ioim->iotag); bfa_trc(ioim->bfa, event); switch (event) { case BFA_IOIM_SM_SGALLOCED: if (!bfa_ioim_send_ioreq(ioim)) { bfa_sm_set_state(ioim, bfa_ioim_sm_qfull); break; } bfa_sm_set_state(ioim, bfa_ioim_sm_active); break; case BFA_IOIM_SM_CLEANUP: bfa_sm_set_state(ioim, bfa_ioim_sm_hcb); bfa_sgpg_wcancel(ioim->bfa, &ioim->iosp->sgpg_wqe); bfa_cb_queue(ioim->bfa, &ioim->hcb_qe, __bfa_cb_ioim_failed, ioim); bfa_ioim_notify_cleanup(ioim); break; case BFA_IOIM_SM_ABORT: bfa_sm_set_state(ioim, bfa_ioim_sm_hcb); bfa_sgpg_wcancel(ioim->bfa, &ioim->iosp->sgpg_wqe); bfa_cb_queue(ioim->bfa, &ioim->hcb_qe, __bfa_cb_ioim_abort, ioim); break; case BFA_IOIM_SM_HWFAIL: bfa_sm_set_state(ioim, bfa_ioim_sm_hcb); bfa_sgpg_wcancel(ioim->bfa, &ioim->iosp->sgpg_wqe); bfa_cb_queue(ioim->bfa, &ioim->hcb_qe, __bfa_cb_ioim_failed, ioim); break; default: bfa_sm_fault(ioim->bfa, event); } } /** * IO is active. */ static void bfa_ioim_sm_active(struct bfa_ioim_s *ioim, enum bfa_ioim_event event) { bfa_trc_fp(ioim->bfa, ioim->iotag); bfa_trc_fp(ioim->bfa, event); switch (event) { case BFA_IOIM_SM_COMP_GOOD: bfa_sm_set_state(ioim, bfa_ioim_sm_hcb); bfa_cb_queue(ioim->bfa, &ioim->hcb_qe, __bfa_cb_ioim_good_comp, ioim); break; case BFA_IOIM_SM_COMP: bfa_sm_set_state(ioim, bfa_ioim_sm_hcb); bfa_cb_queue(ioim->bfa, &ioim->hcb_qe, __bfa_cb_ioim_comp, ioim); break; case BFA_IOIM_SM_DONE: bfa_sm_set_state(ioim, bfa_ioim_sm_hcb_free); bfa_cb_queue(ioim->bfa, &ioim->hcb_qe, __bfa_cb_ioim_comp, ioim); break; case BFA_IOIM_SM_ABORT: ioim->iosp->abort_explicit = BFA_TRUE; ioim->io_cbfn = __bfa_cb_ioim_abort; if (bfa_ioim_send_abort(ioim)) bfa_sm_set_state(ioim, bfa_ioim_sm_abort); else { bfa_sm_set_state(ioim, bfa_ioim_sm_abort_qfull); bfa_reqq_wait(ioim->bfa, ioim->itnim->reqq, &ioim->iosp->reqq_wait); } break; case BFA_IOIM_SM_CLEANUP: ioim->iosp->abort_explicit = BFA_FALSE; ioim->io_cbfn = __bfa_cb_ioim_failed; if (bfa_ioim_send_abort(ioim)) bfa_sm_set_state(ioim, bfa_ioim_sm_cleanup); else { bfa_sm_set_state(ioim, bfa_ioim_sm_cleanup_qfull); bfa_reqq_wait(ioim->bfa, ioim->itnim->reqq, &ioim->iosp->reqq_wait); } break; case BFA_IOIM_SM_HWFAIL: bfa_sm_set_state(ioim, bfa_ioim_sm_hcb); bfa_cb_queue(ioim->bfa, &ioim->hcb_qe, __bfa_cb_ioim_failed, ioim); break; default: bfa_sm_fault(ioim->bfa, event); } } /** * IO is being aborted, waiting for completion from firmware. */ static void bfa_ioim_sm_abort(struct bfa_ioim_s *ioim, enum bfa_ioim_event event) { bfa_trc(ioim->bfa, ioim->iotag); bfa_trc(ioim->bfa, event); switch (event) { case BFA_IOIM_SM_COMP_GOOD: case BFA_IOIM_SM_COMP: case BFA_IOIM_SM_DONE: case BFA_IOIM_SM_FREE: break; case BFA_IOIM_SM_ABORT_DONE: bfa_sm_set_state(ioim, bfa_ioim_sm_hcb_free); bfa_cb_queue(ioim->bfa, &ioim->hcb_qe, __bfa_cb_ioim_abort, ioim); break; case BFA_IOIM_SM_ABORT_COMP: bfa_sm_set_state(ioim, bfa_ioim_sm_hcb); bfa_cb_queue(ioim->bfa, &ioim->hcb_qe, __bfa_cb_ioim_abort, ioim); break; case BFA_IOIM_SM_COMP_UTAG: bfa_sm_set_state(ioim, bfa_ioim_sm_hcb); bfa_cb_queue(ioim->bfa, &ioim->hcb_qe, __bfa_cb_ioim_abort, ioim); break; case BFA_IOIM_SM_CLEANUP: bfa_assert(ioim->iosp->abort_explicit == BFA_TRUE); ioim->iosp->abort_explicit = BFA_FALSE; if (bfa_ioim_send_abort(ioim)) bfa_sm_set_state(ioim, bfa_ioim_sm_cleanup); else { bfa_sm_set_state(ioim, bfa_ioim_sm_cleanup_qfull); bfa_reqq_wait(ioim->bfa, ioim->itnim->reqq, &ioim->iosp->reqq_wait); } break; case BFA_IOIM_SM_HWFAIL: bfa_sm_set_state(ioim, bfa_ioim_sm_hcb); bfa_cb_queue(ioim->bfa, &ioim->hcb_qe, __bfa_cb_ioim_failed, ioim); break; default: bfa_sm_fault(ioim->bfa, event); } } /** * IO is being cleaned up (implicit abort), waiting for completion from * firmware. */ static void bfa_ioim_sm_cleanup(struct bfa_ioim_s *ioim, enum bfa_ioim_event event) { bfa_trc(ioim->bfa, ioim->iotag); bfa_trc(ioim->bfa, event); switch (event) { case BFA_IOIM_SM_COMP_GOOD: case BFA_IOIM_SM_COMP: case BFA_IOIM_SM_DONE: case BFA_IOIM_SM_FREE: break; case BFA_IOIM_SM_ABORT: /** * IO is already being aborted implicitly */ ioim->io_cbfn = __bfa_cb_ioim_abort; break; case BFA_IOIM_SM_ABORT_DONE: bfa_sm_set_state(ioim, bfa_ioim_sm_hcb_free); bfa_cb_queue(ioim->bfa, &ioim->hcb_qe, ioim->io_cbfn, ioim); bfa_ioim_notify_cleanup(ioim); break; case BFA_IOIM_SM_ABORT_COMP: bfa_sm_set_state(ioim, bfa_ioim_sm_hcb); bfa_cb_queue(ioim->bfa, &ioim->hcb_qe, ioim->io_cbfn, ioim); bfa_ioim_notify_cleanup(ioim); break; case BFA_IOIM_SM_COMP_UTAG: bfa_sm_set_state(ioim, bfa_ioim_sm_hcb); bfa_cb_queue(ioim->bfa, &ioim->hcb_qe, ioim->io_cbfn, ioim); bfa_ioim_notify_cleanup(ioim); break; case BFA_IOIM_SM_HWFAIL: bfa_sm_set_state(ioim, bfa_ioim_sm_hcb); bfa_cb_queue(ioim->bfa, &ioim->hcb_qe, __bfa_cb_ioim_failed, ioim); break; case BFA_IOIM_SM_CLEANUP: /** * IO can be in cleanup state already due to TM command. 2nd cleanup * request comes from ITN offline event. */ break; default: bfa_sm_fault(ioim->bfa, event); } } /** * IO is waiting for room in request CQ */ static void bfa_ioim_sm_qfull(struct bfa_ioim_s *ioim, enum bfa_ioim_event event) { bfa_trc(ioim->bfa, ioim->iotag); bfa_trc(ioim->bfa, event); switch (event) { case BFA_IOIM_SM_QRESUME: bfa_sm_set_state(ioim, bfa_ioim_sm_active); bfa_ioim_send_ioreq(ioim); break; case BFA_IOIM_SM_ABORT: bfa_sm_set_state(ioim, bfa_ioim_sm_hcb); bfa_reqq_wcancel(&ioim->iosp->reqq_wait); bfa_cb_queue(ioim->bfa, &ioim->hcb_qe, __bfa_cb_ioim_abort, ioim); break; case BFA_IOIM_SM_CLEANUP: bfa_sm_set_state(ioim, bfa_ioim_sm_hcb); bfa_reqq_wcancel(&ioim->iosp->reqq_wait); bfa_cb_queue(ioim->bfa, &ioim->hcb_qe, __bfa_cb_ioim_failed, ioim); bfa_ioim_notify_cleanup(ioim); break; case BFA_IOIM_SM_HWFAIL: bfa_sm_set_state(ioim, bfa_ioim_sm_hcb); bfa_reqq_wcancel(&ioim->iosp->reqq_wait); bfa_cb_queue(ioim->bfa, &ioim->hcb_qe, __bfa_cb_ioim_failed, ioim); break; default: bfa_sm_fault(ioim->bfa, event); } } /** * Active IO is being aborted, waiting for room in request CQ. */ static void bfa_ioim_sm_abort_qfull(struct bfa_ioim_s *ioim, enum bfa_ioim_event event) { bfa_trc(ioim->bfa, ioim->iotag); bfa_trc(ioim->bfa, event); switch (event) { case BFA_IOIM_SM_QRESUME: bfa_sm_set_state(ioim, bfa_ioim_sm_abort); bfa_ioim_send_abort(ioim); break; case BFA_IOIM_SM_CLEANUP: bfa_assert(ioim->iosp->abort_explicit == BFA_TRUE); ioim->iosp->abort_explicit = BFA_FALSE; bfa_sm_set_state(ioim, bfa_ioim_sm_cleanup_qfull); break; case BFA_IOIM_SM_COMP_GOOD: case BFA_IOIM_SM_COMP: bfa_sm_set_state(ioim, bfa_ioim_sm_hcb); bfa_reqq_wcancel(&ioim->iosp->reqq_wait); bfa_cb_queue(ioim->bfa, &ioim->hcb_qe, __bfa_cb_ioim_abort, ioim); break; case BFA_IOIM_SM_DONE: bfa_sm_set_state(ioim, bfa_ioim_sm_hcb_free); bfa_reqq_wcancel(&ioim->iosp->reqq_wait); bfa_cb_queue(ioim->bfa, &ioim->hcb_qe, __bfa_cb_ioim_abort, ioim); break; case BFA_IOIM_SM_HWFAIL: bfa_sm_set_state(ioim, bfa_ioim_sm_hcb); bfa_reqq_wcancel(&ioim->iosp->reqq_wait); bfa_cb_queue(ioim->bfa, &ioim->hcb_qe, __bfa_cb_ioim_failed, ioim); break; default: bfa_sm_fault(ioim->bfa, event); } } /** * Active IO is being cleaned up, waiting for room in request CQ. */ static void bfa_ioim_sm_cleanup_qfull(struct bfa_ioim_s *ioim, enum bfa_ioim_event event) { bfa_trc(ioim->bfa, ioim->iotag); bfa_trc(ioim->bfa, event); switch (event) { case BFA_IOIM_SM_QRESUME: bfa_sm_set_state(ioim, bfa_ioim_sm_cleanup); bfa_ioim_send_abort(ioim); break; case BFA_IOIM_SM_ABORT: /** * IO is alraedy being cleaned up implicitly */ ioim->io_cbfn = __bfa_cb_ioim_abort; break; case BFA_IOIM_SM_COMP_GOOD: case BFA_IOIM_SM_COMP: bfa_sm_set_state(ioim, bfa_ioim_sm_hcb); bfa_reqq_wcancel(&ioim->iosp->reqq_wait); bfa_cb_queue(ioim->bfa, &ioim->hcb_qe, ioim->io_cbfn, ioim); bfa_ioim_notify_cleanup(ioim); break; case BFA_IOIM_SM_DONE: bfa_sm_set_state(ioim, bfa_ioim_sm_hcb_free); bfa_reqq_wcancel(&ioim->iosp->reqq_wait); bfa_cb_queue(ioim->bfa, &ioim->hcb_qe, ioim->io_cbfn, ioim); bfa_ioim_notify_cleanup(ioim); break; case BFA_IOIM_SM_HWFAIL: bfa_sm_set_state(ioim, bfa_ioim_sm_hcb); bfa_reqq_wcancel(&ioim->iosp->reqq_wait); bfa_cb_queue(ioim->bfa, &ioim->hcb_qe, __bfa_cb_ioim_failed, ioim); break; default: bfa_sm_fault(ioim->bfa, event); } } /** * IO bfa callback is pending. */ static void bfa_ioim_sm_hcb(struct bfa_ioim_s *ioim, enum bfa_ioim_event event) { bfa_trc_fp(ioim->bfa, ioim->iotag); bfa_trc_fp(ioim->bfa, event); switch (event) { case BFA_IOIM_SM_HCB: bfa_sm_set_state(ioim, bfa_ioim_sm_uninit); bfa_ioim_free(ioim); bfa_cb_ioim_resfree(ioim->bfa->bfad); break; case BFA_IOIM_SM_CLEANUP: bfa_ioim_notify_cleanup(ioim); break; case BFA_IOIM_SM_HWFAIL: break; default: bfa_sm_fault(ioim->bfa, event); } } /** * IO bfa callback is pending. IO resource cannot be freed. */ static void bfa_ioim_sm_hcb_free(struct bfa_ioim_s *ioim, enum bfa_ioim_event event) { bfa_trc(ioim->bfa, ioim->iotag); bfa_trc(ioim->bfa, event); switch (event) { case BFA_IOIM_SM_HCB: bfa_sm_set_state(ioim, bfa_ioim_sm_resfree); list_del(&ioim->qe); list_add_tail(&ioim->qe, &ioim->fcpim->ioim_resfree_q); break; case BFA_IOIM_SM_FREE: bfa_sm_set_state(ioim, bfa_ioim_sm_hcb); break; case BFA_IOIM_SM_CLEANUP: bfa_ioim_notify_cleanup(ioim); break; case BFA_IOIM_SM_HWFAIL: bfa_sm_set_state(ioim, bfa_ioim_sm_hcb); break; default: bfa_sm_fault(ioim->bfa, event); } } /** * IO is completed, waiting resource free from firmware. */ static void bfa_ioim_sm_resfree(struct bfa_ioim_s *ioim, enum bfa_ioim_event event) { bfa_trc(ioim->bfa, ioim->iotag); bfa_trc(ioim->bfa, event); switch (event) { case BFA_IOIM_SM_FREE: bfa_sm_set_state(ioim, bfa_ioim_sm_uninit); bfa_ioim_free(ioim); bfa_cb_ioim_resfree(ioim->bfa->bfad); break; case BFA_IOIM_SM_CLEANUP: bfa_ioim_notify_cleanup(ioim); break; case BFA_IOIM_SM_HWFAIL: break; default: bfa_sm_fault(ioim->bfa, event); } } /** * bfa_ioim_private */ static void __bfa_cb_ioim_good_comp(void *cbarg, bfa_boolean_t complete) { struct bfa_ioim_s *ioim = cbarg; if (!complete) { bfa_sm_send_event(ioim, BFA_IOIM_SM_HCB); return; } bfa_cb_ioim_good_comp(ioim->bfa->bfad, ioim->dio); } static void __bfa_cb_ioim_comp(void *cbarg, bfa_boolean_t complete) { struct bfa_ioim_s *ioim = cbarg; struct bfi_ioim_rsp_s *m; u8 *snsinfo = NULL; u8 sns_len = 0; s32 residue = 0; if (!complete) { bfa_sm_send_event(ioim, BFA_IOIM_SM_HCB); return; } m = (struct bfi_ioim_rsp_s *) &ioim->iosp->comp_rspmsg; if (m->io_status == BFI_IOIM_STS_OK) { /** * setup sense information, if present */ if (m->scsi_status == SCSI_STATUS_CHECK_CONDITION && m->sns_len) { sns_len = m->sns_len; snsinfo = ioim->iosp->snsinfo; } /** * setup residue value correctly for normal completions */ if (m->resid_flags == FCP_RESID_UNDER) residue = bfa_os_ntohl(m->residue); if (m->resid_flags == FCP_RESID_OVER) { residue = bfa_os_ntohl(m->residue); residue = -residue; } } bfa_cb_ioim_done(ioim->bfa->bfad, ioim->dio, m->io_status, m->scsi_status, sns_len, snsinfo, residue); } static void __bfa_cb_ioim_failed(void *cbarg, bfa_boolean_t complete) { struct bfa_ioim_s *ioim = cbarg; if (!complete) { bfa_sm_send_event(ioim, BFA_IOIM_SM_HCB); return; } bfa_cb_ioim_done(ioim->bfa->bfad, ioim->dio, BFI_IOIM_STS_ABORTED, 0, 0, NULL, 0); } static void __bfa_cb_ioim_pathtov(void *cbarg, bfa_boolean_t complete) { struct bfa_ioim_s *ioim = cbarg; if (!complete) { bfa_sm_send_event(ioim, BFA_IOIM_SM_HCB); return; } bfa_cb_ioim_done(ioim->bfa->bfad, ioim->dio, BFI_IOIM_STS_PATHTOV, 0, 0, NULL, 0); } static void __bfa_cb_ioim_abort(void *cbarg, bfa_boolean_t complete) { struct bfa_ioim_s *ioim = cbarg; if (!complete) { bfa_sm_send_event(ioim, BFA_IOIM_SM_HCB); return; } bfa_cb_ioim_abort(ioim->bfa->bfad, ioim->dio); } static void bfa_ioim_sgpg_alloced(void *cbarg) { struct bfa_ioim_s *ioim = cbarg; ioim->nsgpgs = BFA_SGPG_NPAGE(ioim->nsges); list_splice_tail_init(&ioim->iosp->sgpg_wqe.sgpg_q, &ioim->sgpg_q); bfa_ioim_sgpg_setup(ioim); bfa_sm_send_event(ioim, BFA_IOIM_SM_SGALLOCED); } /** * Send I/O request to firmware. */ static bfa_boolean_t bfa_ioim_send_ioreq(struct bfa_ioim_s *ioim) { struct bfa_itnim_s *itnim = ioim->itnim; struct bfi_ioim_req_s *m; static struct fcp_cmnd_s cmnd_z0 = { 0 }; struct bfi_sge_s *sge; u32 pgdlen = 0; u64 addr; struct scatterlist *sg; struct scsi_cmnd *cmnd = (struct scsi_cmnd *) ioim->dio; /** * check for room in queue to send request now */ m = bfa_reqq_next(ioim->bfa, itnim->reqq); if (!m) { bfa_reqq_wait(ioim->bfa, ioim->itnim->reqq, &ioim->iosp->reqq_wait); return BFA_FALSE; } /** * build i/o request message next */ m->io_tag = bfa_os_htons(ioim->iotag); m->rport_hdl = ioim->itnim->rport->fw_handle; m->io_timeout = bfa_cb_ioim_get_timeout(ioim->dio); /** * build inline IO SG element here */ sge = &m->sges[0]; if (ioim->nsges) { sg = (struct scatterlist *)scsi_sglist(cmnd); addr = bfa_os_sgaddr(sg_dma_address(sg)); sge->sga = *(union bfi_addr_u *) &addr; pgdlen = sg_dma_len(sg); sge->sg_len = pgdlen; sge->flags = (ioim->nsges > BFI_SGE_INLINE) ? BFI_SGE_DATA_CPL : BFI_SGE_DATA_LAST; bfa_sge_to_be(sge); sge++; } if (ioim->nsges > BFI_SGE_INLINE) { sge->sga = ioim->sgpg->sgpg_pa; } else { sge->sga.a32.addr_lo = 0; sge->sga.a32.addr_hi = 0; } sge->sg_len = pgdlen; sge->flags = BFI_SGE_PGDLEN; bfa_sge_to_be(sge); /** * set up I/O command parameters */ bfa_os_assign(m->cmnd, cmnd_z0); m->cmnd.lun = bfa_cb_ioim_get_lun(ioim->dio); m->cmnd.iodir = bfa_cb_ioim_get_iodir(ioim->dio); bfa_os_assign(m->cmnd.cdb, *(struct scsi_cdb_s *)bfa_cb_ioim_get_cdb(ioim->dio)); m->cmnd.fcp_dl = bfa_os_htonl(bfa_cb_ioim_get_size(ioim->dio)); /** * set up I/O message header */ switch (m->cmnd.iodir) { case FCP_IODIR_READ: bfi_h2i_set(m->mh, BFI_MC_IOIM_READ, 0, bfa_lpuid(ioim->bfa)); bfa_stats(itnim, input_reqs); break; case FCP_IODIR_WRITE: bfi_h2i_set(m->mh, BFI_MC_IOIM_WRITE, 0, bfa_lpuid(ioim->bfa)); bfa_stats(itnim, output_reqs); break; case FCP_IODIR_RW: bfa_stats(itnim, input_reqs); bfa_stats(itnim, output_reqs); default: bfi_h2i_set(m->mh, BFI_MC_IOIM_IO, 0, bfa_lpuid(ioim->bfa)); } if (itnim->seq_rec || (bfa_cb_ioim_get_size(ioim->dio) & (sizeof(u32) - 1))) bfi_h2i_set(m->mh, BFI_MC_IOIM_IO, 0, bfa_lpuid(ioim->bfa)); #ifdef IOIM_ADVANCED m->cmnd.crn = bfa_cb_ioim_get_crn(ioim->dio); m->cmnd.priority = bfa_cb_ioim_get_priority(ioim->dio); m->cmnd.taskattr = bfa_cb_ioim_get_taskattr(ioim->dio); /** * Handle large CDB (>16 bytes). */ m->cmnd.addl_cdb_len = (bfa_cb_ioim_get_cdblen(ioim->dio) - FCP_CMND_CDB_LEN) / sizeof(u32); if (m->cmnd.addl_cdb_len) { bfa_os_memcpy(&m->cmnd.cdb + 1, (struct scsi_cdb_s *) bfa_cb_ioim_get_cdb(ioim->dio) + 1, m->cmnd.addl_cdb_len * sizeof(u32)); fcp_cmnd_fcpdl(&m->cmnd) = bfa_os_htonl(bfa_cb_ioim_get_size(ioim->dio)); } #endif /** * queue I/O message to firmware */ bfa_reqq_produce(ioim->bfa, itnim->reqq); return BFA_TRUE; } /** * Setup any additional SG pages needed.Inline SG element is setup * at queuing time. */ static bfa_boolean_t bfa_ioim_sge_setup(struct bfa_ioim_s *ioim) { u16 nsgpgs; bfa_assert(ioim->nsges > BFI_SGE_INLINE); /** * allocate SG pages needed */ nsgpgs = BFA_SGPG_NPAGE(ioim->nsges); if (!nsgpgs) return BFA_TRUE; if (bfa_sgpg_malloc(ioim->bfa, &ioim->sgpg_q, nsgpgs) != BFA_STATUS_OK) { bfa_sgpg_wait(ioim->bfa, &ioim->iosp->sgpg_wqe, nsgpgs); return BFA_FALSE; } ioim->nsgpgs = nsgpgs; bfa_ioim_sgpg_setup(ioim); return BFA_TRUE; } static void bfa_ioim_sgpg_setup(struct bfa_ioim_s *ioim) { int sgeid, nsges, i; struct bfi_sge_s *sge; struct bfa_sgpg_s *sgpg; u32 pgcumsz; u64 addr; struct scatterlist *sg; struct scsi_cmnd *cmnd = (struct scsi_cmnd *) ioim->dio; sgeid = BFI_SGE_INLINE; ioim->sgpg = sgpg = bfa_q_first(&ioim->sgpg_q); sg = scsi_sglist(cmnd); sg = sg_next(sg); do { sge = sgpg->sgpg->sges; nsges = ioim->nsges - sgeid; if (nsges > BFI_SGPG_DATA_SGES) nsges = BFI_SGPG_DATA_SGES; pgcumsz = 0; for (i = 0; i < nsges; i++, sge++, sgeid++, sg = sg_next(sg)) { addr = bfa_os_sgaddr(sg_dma_address(sg)); sge->sga = *(union bfi_addr_u *) &addr; sge->sg_len = sg_dma_len(sg); pgcumsz += sge->sg_len; /** * set flags */ if (i < (nsges - 1)) sge->flags = BFI_SGE_DATA; else if (sgeid < (ioim->nsges - 1)) sge->flags = BFI_SGE_DATA_CPL; else sge->flags = BFI_SGE_DATA_LAST; } sgpg = (struct bfa_sgpg_s *) bfa_q_next(sgpg); /** * set the link element of each page */ if (sgeid == ioim->nsges) { sge->flags = BFI_SGE_PGDLEN; sge->sga.a32.addr_lo = 0; sge->sga.a32.addr_hi = 0; } else { sge->flags = BFI_SGE_LINK; sge->sga = sgpg->sgpg_pa; } sge->sg_len = pgcumsz; } while (sgeid < ioim->nsges); } /** * Send I/O abort request to firmware. */ static bfa_boolean_t bfa_ioim_send_abort(struct bfa_ioim_s *ioim) { struct bfa_itnim_s *itnim = ioim->itnim; struct bfi_ioim_abort_req_s *m; enum bfi_ioim_h2i msgop; /** * check for room in queue to send request now */ m = bfa_reqq_next(ioim->bfa, itnim->reqq); if (!m) return BFA_FALSE; /** * build i/o request message next */ if (ioim->iosp->abort_explicit) msgop = BFI_IOIM_H2I_IOABORT_REQ; else msgop = BFI_IOIM_H2I_IOCLEANUP_REQ; bfi_h2i_set(m->mh, BFI_MC_IOIM, msgop, bfa_lpuid(ioim->bfa)); m->io_tag = bfa_os_htons(ioim->iotag); m->abort_tag = ++ioim->abort_tag; /** * queue I/O message to firmware */ bfa_reqq_produce(ioim->bfa, itnim->reqq); return BFA_TRUE; } /** * Call to resume any I/O requests waiting for room in request queue. */ static void bfa_ioim_qresume(void *cbarg) { struct bfa_ioim_s *ioim = cbarg; bfa_fcpim_stats(ioim->fcpim, qresumes); bfa_sm_send_event(ioim, BFA_IOIM_SM_QRESUME); } static void bfa_ioim_notify_cleanup(struct bfa_ioim_s *ioim) { /** * Move IO from itnim queue to fcpim global queue since itnim will be * freed. */ list_del(&ioim->qe); list_add_tail(&ioim->qe, &ioim->fcpim->ioim_comp_q); if (!ioim->iosp->tskim) { if (ioim->fcpim->delay_comp && ioim->itnim->iotov_active) { bfa_cb_dequeue(&ioim->hcb_qe); list_del(&ioim->qe); list_add_tail(&ioim->qe, &ioim->itnim->delay_comp_q); } bfa_itnim_iodone(ioim->itnim); } else bfa_tskim_iodone(ioim->iosp->tskim); } /** * or after the link comes back. */ void bfa_ioim_delayed_comp(struct bfa_ioim_s *ioim, bfa_boolean_t iotov) { /** * If path tov timer expired, failback with PATHTOV status - these * IO requests are not normally retried by IO stack. * * Otherwise device cameback online and fail it with normal failed * status so that IO stack retries these failed IO requests. */ if (iotov) ioim->io_cbfn = __bfa_cb_ioim_pathtov; else ioim->io_cbfn = __bfa_cb_ioim_failed; bfa_cb_queue(ioim->bfa, &ioim->hcb_qe, ioim->io_cbfn, ioim); /** * Move IO to fcpim global queue since itnim will be * freed. */ list_del(&ioim->qe); list_add_tail(&ioim->qe, &ioim->fcpim->ioim_comp_q); } /** * bfa_ioim_friend */ /** * Memory allocation and initialization. */ void bfa_ioim_attach(struct bfa_fcpim_mod_s *fcpim, struct bfa_meminfo_s *minfo) { struct bfa_ioim_s *ioim; struct bfa_ioim_sp_s *iosp; u16 i; u8 *snsinfo; u32 snsbufsz; /** * claim memory first */ ioim = (struct bfa_ioim_s *) bfa_meminfo_kva(minfo); fcpim->ioim_arr = ioim; bfa_meminfo_kva(minfo) = (u8 *) (ioim + fcpim->num_ioim_reqs); iosp = (struct bfa_ioim_sp_s *) bfa_meminfo_kva(minfo); fcpim->ioim_sp_arr = iosp; bfa_meminfo_kva(minfo) = (u8 *) (iosp + fcpim->num_ioim_reqs); /** * Claim DMA memory for per IO sense data. */ snsbufsz = fcpim->num_ioim_reqs * BFI_IOIM_SNSLEN; fcpim->snsbase.pa = bfa_meminfo_dma_phys(minfo); bfa_meminfo_dma_phys(minfo) += snsbufsz; fcpim->snsbase.kva = bfa_meminfo_dma_virt(minfo); bfa_meminfo_dma_virt(minfo) += snsbufsz; snsinfo = fcpim->snsbase.kva; bfa_iocfc_set_snsbase(fcpim->bfa, fcpim->snsbase.pa); /** * Initialize ioim free queues */ INIT_LIST_HEAD(&fcpim->ioim_free_q); INIT_LIST_HEAD(&fcpim->ioim_resfree_q); INIT_LIST_HEAD(&fcpim->ioim_comp_q); for (i = 0; i < fcpim->num_ioim_reqs; i++, ioim++, iosp++, snsinfo += BFI_IOIM_SNSLEN) { /* * initialize IOIM */ bfa_os_memset(ioim, 0, sizeof(struct bfa_ioim_s)); ioim->iotag = i; ioim->bfa = fcpim->bfa; ioim->fcpim = fcpim; ioim->iosp = iosp; iosp->snsinfo = snsinfo; INIT_LIST_HEAD(&ioim->sgpg_q); bfa_reqq_winit(&ioim->iosp->reqq_wait, bfa_ioim_qresume, ioim); bfa_sgpg_winit(&ioim->iosp->sgpg_wqe, bfa_ioim_sgpg_alloced, ioim); bfa_sm_set_state(ioim, bfa_ioim_sm_uninit); list_add_tail(&ioim->qe, &fcpim->ioim_free_q); } } /** * Driver detach time call. */ void bfa_ioim_detach(struct bfa_fcpim_mod_s *fcpim) { } void bfa_ioim_isr(struct bfa_s *bfa, struct bfi_msg_s *m) { struct bfa_fcpim_mod_s *fcpim = BFA_FCPIM_MOD(bfa); struct bfi_ioim_rsp_s *rsp = (struct bfi_ioim_rsp_s *) m; struct bfa_ioim_s *ioim; u16 iotag; enum bfa_ioim_event evt = BFA_IOIM_SM_COMP; iotag = bfa_os_ntohs(rsp->io_tag); ioim = BFA_IOIM_FROM_TAG(fcpim, iotag); bfa_assert(ioim->iotag == iotag); bfa_trc(ioim->bfa, ioim->iotag); bfa_trc(ioim->bfa, rsp->io_status); bfa_trc(ioim->bfa, rsp->reuse_io_tag); if (bfa_sm_cmp_state(ioim, bfa_ioim_sm_active)) bfa_os_assign(ioim->iosp->comp_rspmsg, *m); switch (rsp->io_status) { case BFI_IOIM_STS_OK: bfa_fcpim_stats(fcpim, iocomp_ok); if (rsp->reuse_io_tag == 0) evt = BFA_IOIM_SM_DONE; else evt = BFA_IOIM_SM_COMP; break; case BFI_IOIM_STS_TIMEDOUT: case BFI_IOIM_STS_ABORTED: rsp->io_status = BFI_IOIM_STS_ABORTED; bfa_fcpim_stats(fcpim, iocomp_aborted); if (rsp->reuse_io_tag == 0) evt = BFA_IOIM_SM_DONE; else evt = BFA_IOIM_SM_COMP; break; case BFI_IOIM_STS_PROTO_ERR: bfa_fcpim_stats(fcpim, iocom_proto_err); bfa_assert(rsp->reuse_io_tag); evt = BFA_IOIM_SM_COMP; break; case BFI_IOIM_STS_SQER_NEEDED: bfa_fcpim_stats(fcpim, iocom_sqer_needed); bfa_assert(rsp->reuse_io_tag == 0); evt = BFA_IOIM_SM_SQRETRY; break; case BFI_IOIM_STS_RES_FREE: bfa_fcpim_stats(fcpim, iocom_res_free); evt = BFA_IOIM_SM_FREE; break; case BFI_IOIM_STS_HOST_ABORTED: bfa_fcpim_stats(fcpim, iocom_hostabrts); if (rsp->abort_tag != ioim->abort_tag) { bfa_trc(ioim->bfa, rsp->abort_tag); bfa_trc(ioim->bfa, ioim->abort_tag); return; } if (rsp->reuse_io_tag) evt = BFA_IOIM_SM_ABORT_COMP; else evt = BFA_IOIM_SM_ABORT_DONE; break; case BFI_IOIM_STS_UTAG: bfa_fcpim_stats(fcpim, iocom_utags); evt = BFA_IOIM_SM_COMP_UTAG; break; default: bfa_assert(0); } bfa_sm_send_event(ioim, evt); } void bfa_ioim_good_comp_isr(struct bfa_s *bfa, struct bfi_msg_s *m) { struct bfa_fcpim_mod_s *fcpim = BFA_FCPIM_MOD(bfa); struct bfi_ioim_rsp_s *rsp = (struct bfi_ioim_rsp_s *) m; struct bfa_ioim_s *ioim; u16 iotag; iotag = bfa_os_ntohs(rsp->io_tag); ioim = BFA_IOIM_FROM_TAG(fcpim, iotag); bfa_assert(ioim->iotag == iotag); bfa_trc_fp(ioim->bfa, ioim->iotag); bfa_sm_send_event(ioim, BFA_IOIM_SM_COMP_GOOD); } /** * Called by itnim to clean up IO while going offline. */ void bfa_ioim_cleanup(struct bfa_ioim_s *ioim) { bfa_trc(ioim->bfa, ioim->iotag); bfa_fcpim_stats(ioim->fcpim, io_cleanups); ioim->iosp->tskim = NULL; bfa_sm_send_event(ioim, BFA_IOIM_SM_CLEANUP); } void bfa_ioim_cleanup_tm(struct bfa_ioim_s *ioim, struct bfa_tskim_s *tskim) { bfa_trc(ioim->bfa, ioim->iotag); bfa_fcpim_stats(ioim->fcpim, io_tmaborts); ioim->iosp->tskim = tskim; bfa_sm_send_event(ioim, BFA_IOIM_SM_CLEANUP); } /** * IOC failure handling. */ void bfa_ioim_iocdisable(struct bfa_ioim_s *ioim) { bfa_sm_send_event(ioim, BFA_IOIM_SM_HWFAIL); } /** * IO offline TOV popped. Fail the pending IO. */ void bfa_ioim_tov(struct bfa_ioim_s *ioim) { bfa_sm_send_event(ioim, BFA_IOIM_SM_IOTOV); } /** * bfa_ioim_api */ /** * Allocate IOIM resource for initiator mode I/O request. */ struct bfa_ioim_s * bfa_ioim_alloc(struct bfa_s *bfa, struct bfad_ioim_s *dio, struct bfa_itnim_s *itnim, u16 nsges) { struct bfa_fcpim_mod_s *fcpim = BFA_FCPIM_MOD(bfa); struct bfa_ioim_s *ioim; /** * alocate IOIM resource */ bfa_q_deq(&fcpim->ioim_free_q, &ioim); if (!ioim) { bfa_fcpim_stats(fcpim, no_iotags); return NULL; } ioim->dio = dio; ioim->itnim = itnim; ioim->nsges = nsges; ioim->nsgpgs = 0; bfa_stats(fcpim, total_ios); bfa_stats(itnim, ios); fcpim->ios_active++; list_add_tail(&ioim->qe, &itnim->io_q); bfa_trc_fp(ioim->bfa, ioim->iotag); return ioim; } void bfa_ioim_free(struct bfa_ioim_s *ioim) { struct bfa_fcpim_mod_s *fcpim = ioim->fcpim; bfa_trc_fp(ioim->bfa, ioim->iotag); bfa_assert_fp(bfa_sm_cmp_state(ioim, bfa_ioim_sm_uninit)); bfa_assert_fp(list_empty(&ioim->sgpg_q) || (ioim->nsges > BFI_SGE_INLINE)); if (ioim->nsgpgs > 0) bfa_sgpg_mfree(ioim->bfa, &ioim->sgpg_q, ioim->nsgpgs); bfa_stats(ioim->itnim, io_comps); fcpim->ios_active--; list_del(&ioim->qe); list_add_tail(&ioim->qe, &fcpim->ioim_free_q); } void bfa_ioim_start(struct bfa_ioim_s *ioim) { bfa_trc_fp(ioim->bfa, ioim->iotag); bfa_sm_send_event(ioim, BFA_IOIM_SM_START); } /** * Driver I/O abort request. */ void bfa_ioim_abort(struct bfa_ioim_s *ioim) { bfa_trc(ioim->bfa, ioim->iotag); bfa_fcpim_stats(ioim->fcpim, io_aborts); bfa_sm_send_event(ioim, BFA_IOIM_SM_ABORT); }
gpl-2.0
13hakta/source
tools/firmware-utils/src/sha1.c
767
11110
/* * FIPS-180-1 compliant SHA-1 implementation * * Copyright (C) 2003-2006 Christophe Devine * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License, version 2.1 as published by the Free Software Foundation. * * 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 */ /* * The SHA-1 standard was published by NIST in 1993. * * http://www.itl.nist.gov/fipspubs/fip180-1.htm */ #ifndef _CRT_SECURE_NO_DEPRECATE #define _CRT_SECURE_NO_DEPRECATE 1 #endif #include <string.h> #include <stdio.h> #include "sha1.h" /* * 32-bit integer manipulation macros (big endian) */ #ifndef GET_UINT32_BE #define GET_UINT32_BE(n,b,i) \ { \ (n) = ( (ulong) (b)[(i) ] << 24 ) \ | ( (ulong) (b)[(i) + 1] << 16 ) \ | ( (ulong) (b)[(i) + 2] << 8 ) \ | ( (ulong) (b)[(i) + 3] ); \ } #endif #ifndef PUT_UINT32_BE #define PUT_UINT32_BE(n,b,i) \ { \ (b)[(i) ] = (uchar) ( (n) >> 24 ); \ (b)[(i) + 1] = (uchar) ( (n) >> 16 ); \ (b)[(i) + 2] = (uchar) ( (n) >> 8 ); \ (b)[(i) + 3] = (uchar) ( (n) ); \ } #endif /* * Core SHA-1 functions */ void sha1_starts( sha1_context *ctx ) { ctx->total[0] = 0; ctx->total[1] = 0; ctx->state[0] = 0x67452301; ctx->state[1] = 0xEFCDAB89; ctx->state[2] = 0x98BADCFE; ctx->state[3] = 0x10325476; ctx->state[4] = 0xC3D2E1F0; } void sha1_process( sha1_context *ctx, uchar data[64] ) { ulong temp, W[16], A, B, C, D, E; GET_UINT32_BE( W[0], data, 0 ); GET_UINT32_BE( W[1], data, 4 ); GET_UINT32_BE( W[2], data, 8 ); GET_UINT32_BE( W[3], data, 12 ); GET_UINT32_BE( W[4], data, 16 ); GET_UINT32_BE( W[5], data, 20 ); GET_UINT32_BE( W[6], data, 24 ); GET_UINT32_BE( W[7], data, 28 ); GET_UINT32_BE( W[8], data, 32 ); GET_UINT32_BE( W[9], data, 36 ); GET_UINT32_BE( W[10], data, 40 ); GET_UINT32_BE( W[11], data, 44 ); GET_UINT32_BE( W[12], data, 48 ); GET_UINT32_BE( W[13], data, 52 ); GET_UINT32_BE( W[14], data, 56 ); GET_UINT32_BE( W[15], data, 60 ); #define S(x,n) ((x << n) | ((x & 0xFFFFFFFF) >> (32 - n))) #define R(t) \ ( \ temp = W[(t - 3) & 0x0F] ^ W[(t - 8) & 0x0F] ^ \ W[(t - 14) & 0x0F] ^ W[ t & 0x0F], \ ( W[t & 0x0F] = S(temp,1) ) \ ) #define P(a,b,c,d,e,x) \ { \ e += S(a,5) + F(b,c,d) + K + x; b = S(b,30); \ } A = ctx->state[0]; B = ctx->state[1]; C = ctx->state[2]; D = ctx->state[3]; E = ctx->state[4]; #define F(x,y,z) (z ^ (x & (y ^ z))) #define K 0x5A827999 P( A, B, C, D, E, W[0] ); P( E, A, B, C, D, W[1] ); P( D, E, A, B, C, W[2] ); P( C, D, E, A, B, W[3] ); P( B, C, D, E, A, W[4] ); P( A, B, C, D, E, W[5] ); P( E, A, B, C, D, W[6] ); P( D, E, A, B, C, W[7] ); P( C, D, E, A, B, W[8] ); P( B, C, D, E, A, W[9] ); P( A, B, C, D, E, W[10] ); P( E, A, B, C, D, W[11] ); P( D, E, A, B, C, W[12] ); P( C, D, E, A, B, W[13] ); P( B, C, D, E, A, W[14] ); P( A, B, C, D, E, W[15] ); P( E, A, B, C, D, R(16) ); P( D, E, A, B, C, R(17) ); P( C, D, E, A, B, R(18) ); P( B, C, D, E, A, R(19) ); #undef K #undef F #define F(x,y,z) (x ^ y ^ z) #define K 0x6ED9EBA1 P( A, B, C, D, E, R(20) ); P( E, A, B, C, D, R(21) ); P( D, E, A, B, C, R(22) ); P( C, D, E, A, B, R(23) ); P( B, C, D, E, A, R(24) ); P( A, B, C, D, E, R(25) ); P( E, A, B, C, D, R(26) ); P( D, E, A, B, C, R(27) ); P( C, D, E, A, B, R(28) ); P( B, C, D, E, A, R(29) ); P( A, B, C, D, E, R(30) ); P( E, A, B, C, D, R(31) ); P( D, E, A, B, C, R(32) ); P( C, D, E, A, B, R(33) ); P( B, C, D, E, A, R(34) ); P( A, B, C, D, E, R(35) ); P( E, A, B, C, D, R(36) ); P( D, E, A, B, C, R(37) ); P( C, D, E, A, B, R(38) ); P( B, C, D, E, A, R(39) ); #undef K #undef F #define F(x,y,z) ((x & y) | (z & (x | y))) #define K 0x8F1BBCDC P( A, B, C, D, E, R(40) ); P( E, A, B, C, D, R(41) ); P( D, E, A, B, C, R(42) ); P( C, D, E, A, B, R(43) ); P( B, C, D, E, A, R(44) ); P( A, B, C, D, E, R(45) ); P( E, A, B, C, D, R(46) ); P( D, E, A, B, C, R(47) ); P( C, D, E, A, B, R(48) ); P( B, C, D, E, A, R(49) ); P( A, B, C, D, E, R(50) ); P( E, A, B, C, D, R(51) ); P( D, E, A, B, C, R(52) ); P( C, D, E, A, B, R(53) ); P( B, C, D, E, A, R(54) ); P( A, B, C, D, E, R(55) ); P( E, A, B, C, D, R(56) ); P( D, E, A, B, C, R(57) ); P( C, D, E, A, B, R(58) ); P( B, C, D, E, A, R(59) ); #undef K #undef F #define F(x,y,z) (x ^ y ^ z) #define K 0xCA62C1D6 P( A, B, C, D, E, R(60) ); P( E, A, B, C, D, R(61) ); P( D, E, A, B, C, R(62) ); P( C, D, E, A, B, R(63) ); P( B, C, D, E, A, R(64) ); P( A, B, C, D, E, R(65) ); P( E, A, B, C, D, R(66) ); P( D, E, A, B, C, R(67) ); P( C, D, E, A, B, R(68) ); P( B, C, D, E, A, R(69) ); P( A, B, C, D, E, R(70) ); P( E, A, B, C, D, R(71) ); P( D, E, A, B, C, R(72) ); P( C, D, E, A, B, R(73) ); P( B, C, D, E, A, R(74) ); P( A, B, C, D, E, R(75) ); P( E, A, B, C, D, R(76) ); P( D, E, A, B, C, R(77) ); P( C, D, E, A, B, R(78) ); P( B, C, D, E, A, R(79) ); #undef K #undef F ctx->state[0] += A; ctx->state[1] += B; ctx->state[2] += C; ctx->state[3] += D; ctx->state[4] += E; } void sha1_update( sha1_context *ctx, uchar *input, uint length ) { ulong left, fill; if( ! length ) return; left = ctx->total[0] & 0x3F; fill = 64 - left; ctx->total[0] += length; ctx->total[0] &= 0xFFFFFFFF; if( ctx->total[0] < length ) ctx->total[1]++; if( left && length >= fill ) { memcpy( (void *) (ctx->buffer + left), (void *) input, fill ); sha1_process( ctx, ctx->buffer ); length -= fill; input += fill; left = 0; } while( length >= 64 ) { sha1_process( ctx, input ); length -= 64; input += 64; } if( length ) { memcpy( (void *) (ctx->buffer + left), (void *) input, length ); } } static uchar sha1_padding[64] = { 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; void sha1_finish( sha1_context *ctx, uchar digest[20] ) { ulong last, padn; ulong high, low; uchar msglen[8]; high = ( ctx->total[0] >> 29 ) | ( ctx->total[1] << 3 ); low = ( ctx->total[0] << 3 ); PUT_UINT32_BE( high, msglen, 0 ); PUT_UINT32_BE( low, msglen, 4 ); last = ctx->total[0] & 0x3F; padn = ( last < 56 ) ? ( 56 - last ) : ( 120 - last ); sha1_update( ctx, sha1_padding, padn ); sha1_update( ctx, msglen, 8 ); PUT_UINT32_BE( ctx->state[0], digest, 0 ); PUT_UINT32_BE( ctx->state[1], digest, 4 ); PUT_UINT32_BE( ctx->state[2], digest, 8 ); PUT_UINT32_BE( ctx->state[3], digest, 12 ); PUT_UINT32_BE( ctx->state[4], digest, 16 ); } /* * Output SHA-1(file contents), returns 0 if successful. */ int sha1_file( char *filename, uchar digest[20] ) { FILE *f; size_t n; sha1_context ctx; uchar buf[1024]; if( ( f = fopen( filename, "rb" ) ) == NULL ) return( 1 ); sha1_starts( &ctx ); while( ( n = fread( buf, 1, sizeof( buf ), f ) ) > 0 ) sha1_update( &ctx, buf, (uint) n ); sha1_finish( &ctx, digest ); fclose( f ); return( 0 ); } /* * Output SHA-1(buf) */ void sha1_csum( uchar *buf, uint buflen, uchar digest[20] ) { sha1_context ctx; sha1_starts( &ctx ); sha1_update( &ctx, buf, buflen ); sha1_finish( &ctx, digest ); } /* * Output HMAC-SHA-1(key,buf) */ void sha1_hmac( uchar *key, uint keylen, uchar *buf, uint buflen, uchar digest[20] ) { uint i; sha1_context ctx; uchar k_ipad[64]; uchar k_opad[64]; uchar tmpbuf[20]; memset( k_ipad, 0x36, 64 ); memset( k_opad, 0x5C, 64 ); for( i = 0; i < keylen; i++ ) { if( i >= 64 ) break; k_ipad[i] ^= key[i]; k_opad[i] ^= key[i]; } sha1_starts( &ctx ); sha1_update( &ctx, k_ipad, 64 ); sha1_update( &ctx, buf, buflen ); sha1_finish( &ctx, tmpbuf ); sha1_starts( &ctx ); sha1_update( &ctx, k_opad, 64 ); sha1_update( &ctx, tmpbuf, 20 ); sha1_finish( &ctx, digest ); memset( k_ipad, 0, 64 ); memset( k_opad, 0, 64 ); memset( tmpbuf, 0, 20 ); memset( &ctx, 0, sizeof( sha1_context ) ); } #ifdef SELF_TEST /* * FIPS-180-1 test vectors */ static char *sha1_test_str[3] = { "abc", "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", NULL }; static uchar sha1_test_sum[3][20] = { { 0xA9, 0x99, 0x3E, 0x36, 0x47, 0x06, 0x81, 0x6A, 0xBA, 0x3E, 0x25, 0x71, 0x78, 0x50, 0xC2, 0x6C, 0x9C, 0xD0, 0xD8, 0x9D }, { 0x84, 0x98, 0x3E, 0x44, 0x1C, 0x3B, 0xD2, 0x6E, 0xBA, 0xAE, 0x4A, 0xA1, 0xF9, 0x51, 0x29, 0xE5, 0xE5, 0x46, 0x70, 0xF1 }, { 0x34, 0xAA, 0x97, 0x3C, 0xD4, 0xC4, 0xDA, 0xA4, 0xF6, 0x1E, 0xEB, 0x2B, 0xDB, 0xAD, 0x27, 0x31, 0x65, 0x34, 0x01, 0x6F } }; /* * Checkup routine */ int sha1_self_test( void ) { int i, j; uchar buf[1000]; uchar sha1sum[20]; sha1_context ctx; for( i = 0; i < 3; i++ ) { printf( " SHA-1 test #%d: ", i + 1 ); sha1_starts( &ctx ); if( i < 2 ) sha1_update( &ctx, (uchar *) sha1_test_str[i], strlen( sha1_test_str[i] ) ); else { memset( buf, 'a', 1000 ); for( j = 0; j < 1000; j++ ) sha1_update( &ctx, (uchar *) buf, 1000 ); } sha1_finish( &ctx, sha1sum ); if( memcmp( sha1sum, sha1_test_sum[i], 20 ) != 0 ) { printf( "failed\n" ); return( 1 ); } printf( "passed\n" ); } printf( "\n" ); return( 0 ); } #else int sha1_self_test( void ) { printf( "SHA-1 self-test not available\n\n" ); return( 1 ); } #endif
gpl-2.0
L-Insomnia-P/kernel-msm
drivers/misc/mei/client.c
767
18022
/* * * Intel Management Engine Interface (Intel MEI) Linux driver * Copyright (c) 2003-2012, Intel Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * */ #include <linux/pci.h> #include <linux/sched.h> #include <linux/wait.h> #include <linux/delay.h> #include <linux/mei.h> #include "mei_dev.h" #include "hbm.h" #include "client.h" /** * mei_me_cl_by_uuid - locate index of me client * * @dev: mei device * returns me client index or -ENOENT if not found */ int mei_me_cl_by_uuid(const struct mei_device *dev, const uuid_le *uuid) { int i, res = -ENOENT; for (i = 0; i < dev->me_clients_num; ++i) if (uuid_le_cmp(*uuid, dev->me_clients[i].props.protocol_name) == 0) { res = i; break; } return res; } /** * mei_me_cl_by_id return index to me_clients for client_id * * @dev: the device structure * @client_id: me client id * * Locking: called under "dev->device_lock" lock * * returns index on success, -ENOENT on failure. */ int mei_me_cl_by_id(struct mei_device *dev, u8 client_id) { int i; for (i = 0; i < dev->me_clients_num; i++) if (dev->me_clients[i].client_id == client_id) break; if (WARN_ON(dev->me_clients[i].client_id != client_id)) return -ENOENT; if (i == dev->me_clients_num) return -ENOENT; return i; } /** * mei_io_list_flush - removes list entry belonging to cl. * * @list: An instance of our list structure * @cl: host client */ void mei_io_list_flush(struct mei_cl_cb *list, struct mei_cl *cl) { struct mei_cl_cb *cb; struct mei_cl_cb *next; list_for_each_entry_safe(cb, next, &list->list, list) { if (cb->cl && mei_cl_cmp_id(cl, cb->cl)) list_del(&cb->list); } } /** * mei_io_cb_free - free mei_cb_private related memory * * @cb: mei callback struct */ void mei_io_cb_free(struct mei_cl_cb *cb) { if (cb == NULL) return; kfree(cb->request_buffer.data); kfree(cb->response_buffer.data); kfree(cb); } /** * mei_io_cb_init - allocate and initialize io callback * * @cl - mei client * @fp: pointer to file structure * * returns mei_cl_cb pointer or NULL; */ struct mei_cl_cb *mei_io_cb_init(struct mei_cl *cl, struct file *fp) { struct mei_cl_cb *cb; cb = kzalloc(sizeof(struct mei_cl_cb), GFP_KERNEL); if (!cb) return NULL; mei_io_list_init(cb); cb->file_object = fp; cb->cl = cl; cb->buf_idx = 0; return cb; } /** * mei_io_cb_alloc_req_buf - allocate request buffer * * @cb: io callback structure * @length: size of the buffer * * returns 0 on success * -EINVAL if cb is NULL * -ENOMEM if allocation failed */ int mei_io_cb_alloc_req_buf(struct mei_cl_cb *cb, size_t length) { if (!cb) return -EINVAL; if (length == 0) return 0; cb->request_buffer.data = kmalloc(length, GFP_KERNEL); if (!cb->request_buffer.data) return -ENOMEM; cb->request_buffer.size = length; return 0; } /** * mei_io_cb_alloc_resp_buf - allocate respose buffer * * @cb: io callback structure * @length: size of the buffer * * returns 0 on success * -EINVAL if cb is NULL * -ENOMEM if allocation failed */ int mei_io_cb_alloc_resp_buf(struct mei_cl_cb *cb, size_t length) { if (!cb) return -EINVAL; if (length == 0) return 0; cb->response_buffer.data = kmalloc(length, GFP_KERNEL); if (!cb->response_buffer.data) return -ENOMEM; cb->response_buffer.size = length; return 0; } /** * mei_cl_flush_queues - flushes queue lists belonging to cl. * * @cl: host client */ int mei_cl_flush_queues(struct mei_cl *cl) { if (WARN_ON(!cl || !cl->dev)) return -EINVAL; dev_dbg(&cl->dev->pdev->dev, "remove list entry belonging to cl\n"); mei_io_list_flush(&cl->dev->read_list, cl); mei_io_list_flush(&cl->dev->write_list, cl); mei_io_list_flush(&cl->dev->write_waiting_list, cl); mei_io_list_flush(&cl->dev->ctrl_wr_list, cl); mei_io_list_flush(&cl->dev->ctrl_rd_list, cl); mei_io_list_flush(&cl->dev->amthif_cmd_list, cl); mei_io_list_flush(&cl->dev->amthif_rd_complete_list, cl); return 0; } /** * mei_cl_init - initializes intialize cl. * * @cl: host client to be initialized * @dev: mei device */ void mei_cl_init(struct mei_cl *cl, struct mei_device *dev) { memset(cl, 0, sizeof(struct mei_cl)); init_waitqueue_head(&cl->wait); init_waitqueue_head(&cl->rx_wait); init_waitqueue_head(&cl->tx_wait); INIT_LIST_HEAD(&cl->link); INIT_LIST_HEAD(&cl->device_link); cl->reading_state = MEI_IDLE; cl->writing_state = MEI_IDLE; cl->dev = dev; } /** * mei_cl_allocate - allocates cl structure and sets it up. * * @dev: mei device * returns The allocated file or NULL on failure */ struct mei_cl *mei_cl_allocate(struct mei_device *dev) { struct mei_cl *cl; cl = kmalloc(sizeof(struct mei_cl), GFP_KERNEL); if (!cl) return NULL; mei_cl_init(cl, dev); return cl; } /** * mei_cl_find_read_cb - find this cl's callback in the read list * * @cl: host client * * returns cb on success, NULL on error */ struct mei_cl_cb *mei_cl_find_read_cb(struct mei_cl *cl) { struct mei_device *dev = cl->dev; struct mei_cl_cb *cb = NULL; struct mei_cl_cb *next = NULL; list_for_each_entry_safe(cb, next, &dev->read_list.list, list) if (mei_cl_cmp_id(cl, cb->cl)) return cb; return NULL; } /** mei_cl_link: allocte host id in the host map * * @cl - host client * @id - fixed host id or -1 for genereting one * * returns 0 on success * -EINVAL on incorrect values * -ENONET if client not found */ int mei_cl_link(struct mei_cl *cl, int id) { struct mei_device *dev; if (WARN_ON(!cl || !cl->dev)) return -EINVAL; dev = cl->dev; /* If Id is not asigned get one*/ if (id == MEI_HOST_CLIENT_ID_ANY) id = find_first_zero_bit(dev->host_clients_map, MEI_CLIENTS_MAX); if (id >= MEI_CLIENTS_MAX) { dev_err(&dev->pdev->dev, "id exceded %d", MEI_CLIENTS_MAX) ; return -ENOENT; } dev->open_handle_count++; cl->host_client_id = id; list_add_tail(&cl->link, &dev->file_list); set_bit(id, dev->host_clients_map); cl->state = MEI_FILE_INITIALIZING; dev_dbg(&dev->pdev->dev, "link cl host id = %d\n", cl->host_client_id); return 0; } /** * mei_cl_unlink - remove me_cl from the list * * @cl: host client */ int mei_cl_unlink(struct mei_cl *cl) { struct mei_device *dev; struct mei_cl *pos, *next; /* don't shout on error exit path */ if (!cl) return 0; /* wd and amthif might not be initialized */ if (!cl->dev) return 0; dev = cl->dev; list_for_each_entry_safe(pos, next, &dev->file_list, link) { if (cl->host_client_id == pos->host_client_id) { dev_dbg(&dev->pdev->dev, "remove host client = %d, ME client = %d\n", pos->host_client_id, pos->me_client_id); list_del_init(&pos->link); break; } } return 0; } void mei_host_client_init(struct work_struct *work) { struct mei_device *dev = container_of(work, struct mei_device, init_work); struct mei_client_properties *client_props; int i; mutex_lock(&dev->device_lock); bitmap_zero(dev->host_clients_map, MEI_CLIENTS_MAX); dev->open_handle_count = 0; /* * Reserving the first three client IDs * 0: Reserved for MEI Bus Message communications * 1: Reserved for Watchdog * 2: Reserved for AMTHI */ bitmap_set(dev->host_clients_map, 0, 3); for (i = 0; i < dev->me_clients_num; i++) { client_props = &dev->me_clients[i].props; if (!uuid_le_cmp(client_props->protocol_name, mei_amthif_guid)) mei_amthif_host_init(dev); else if (!uuid_le_cmp(client_props->protocol_name, mei_wd_guid)) mei_wd_host_init(dev); else if (!uuid_le_cmp(client_props->protocol_name, mei_nfc_guid)) mei_nfc_host_init(dev); } dev->dev_state = MEI_DEV_ENABLED; mutex_unlock(&dev->device_lock); } /** * mei_cl_disconnect - disconnect host clinet form the me one * * @cl: host client * * Locking: called under "dev->device_lock" lock * * returns 0 on success, <0 on failure. */ int mei_cl_disconnect(struct mei_cl *cl) { struct mei_device *dev; struct mei_cl_cb *cb; int rets, err; if (WARN_ON(!cl || !cl->dev)) return -ENODEV; dev = cl->dev; if (cl->state != MEI_FILE_DISCONNECTING) return 0; cb = mei_io_cb_init(cl, NULL); if (!cb) return -ENOMEM; cb->fop_type = MEI_FOP_CLOSE; if (dev->hbuf_is_ready) { dev->hbuf_is_ready = false; if (mei_hbm_cl_disconnect_req(dev, cl)) { rets = -ENODEV; dev_err(&dev->pdev->dev, "failed to disconnect.\n"); goto free; } mdelay(10); /* Wait for hardware disconnection ready */ list_add_tail(&cb->list, &dev->ctrl_rd_list.list); } else { dev_dbg(&dev->pdev->dev, "add disconnect cb to control write list\n"); list_add_tail(&cb->list, &dev->ctrl_wr_list.list); } mutex_unlock(&dev->device_lock); err = wait_event_timeout(dev->wait_recvd_msg, MEI_FILE_DISCONNECTED == cl->state, mei_secs_to_jiffies(MEI_CL_CONNECT_TIMEOUT)); mutex_lock(&dev->device_lock); if (MEI_FILE_DISCONNECTED == cl->state) { rets = 0; dev_dbg(&dev->pdev->dev, "successfully disconnected from FW client.\n"); } else { rets = -ENODEV; if (MEI_FILE_DISCONNECTED != cl->state) dev_dbg(&dev->pdev->dev, "wrong status client disconnect.\n"); if (err) dev_dbg(&dev->pdev->dev, "wait failed disconnect err=%08x\n", err); dev_dbg(&dev->pdev->dev, "failed to disconnect from FW client.\n"); } mei_io_list_flush(&dev->ctrl_rd_list, cl); mei_io_list_flush(&dev->ctrl_wr_list, cl); free: mei_io_cb_free(cb); return rets; } /** * mei_cl_is_other_connecting - checks if other * client with the same me client id is connecting * * @cl: private data of the file object * * returns ture if other client is connected, 0 - otherwise. */ bool mei_cl_is_other_connecting(struct mei_cl *cl) { struct mei_device *dev; struct mei_cl *pos; struct mei_cl *next; if (WARN_ON(!cl || !cl->dev)) return false; dev = cl->dev; list_for_each_entry_safe(pos, next, &dev->file_list, link) { if ((pos->state == MEI_FILE_CONNECTING) && (pos != cl) && cl->me_client_id == pos->me_client_id) return true; } return false; } /** * mei_cl_connect - connect host clinet to the me one * * @cl: host client * * Locking: called under "dev->device_lock" lock * * returns 0 on success, <0 on failure. */ int mei_cl_connect(struct mei_cl *cl, struct file *file) { struct mei_device *dev; struct mei_cl_cb *cb; long timeout = mei_secs_to_jiffies(MEI_CL_CONNECT_TIMEOUT); int rets; if (WARN_ON(!cl || !cl->dev)) return -ENODEV; dev = cl->dev; cb = mei_io_cb_init(cl, file); if (!cb) { rets = -ENOMEM; goto out; } cb->fop_type = MEI_FOP_IOCTL; if (dev->hbuf_is_ready && !mei_cl_is_other_connecting(cl)) { dev->hbuf_is_ready = false; if (mei_hbm_cl_connect_req(dev, cl)) { rets = -ENODEV; goto out; } cl->timer_count = MEI_CONNECT_TIMEOUT; list_add_tail(&cb->list, &dev->ctrl_rd_list.list); } else { list_add_tail(&cb->list, &dev->ctrl_wr_list.list); } mutex_unlock(&dev->device_lock); rets = wait_event_timeout(dev->wait_recvd_msg, (cl->state == MEI_FILE_CONNECTED || cl->state == MEI_FILE_DISCONNECTED), timeout * HZ); mutex_lock(&dev->device_lock); if (cl->state != MEI_FILE_CONNECTED) { rets = -EFAULT; mei_io_list_flush(&dev->ctrl_rd_list, cl); mei_io_list_flush(&dev->ctrl_wr_list, cl); goto out; } rets = cl->status; out: mei_io_cb_free(cb); return rets; } /** * mei_cl_flow_ctrl_creds - checks flow_control credits for cl. * * @cl: private data of the file object * * returns 1 if mei_flow_ctrl_creds >0, 0 - otherwise. * -ENOENT if mei_cl is not present * -EINVAL if single_recv_buf == 0 */ int mei_cl_flow_ctrl_creds(struct mei_cl *cl) { struct mei_device *dev; int i; if (WARN_ON(!cl || !cl->dev)) return -EINVAL; dev = cl->dev; if (!dev->me_clients_num) return 0; if (cl->mei_flow_ctrl_creds > 0) return 1; for (i = 0; i < dev->me_clients_num; i++) { struct mei_me_client *me_cl = &dev->me_clients[i]; if (me_cl->client_id == cl->me_client_id) { if (me_cl->mei_flow_ctrl_creds) { if (WARN_ON(me_cl->props.single_recv_buf == 0)) return -EINVAL; return 1; } else { return 0; } } } return -ENOENT; } /** * mei_cl_flow_ctrl_reduce - reduces flow_control. * * @cl: private data of the file object * * @returns * 0 on success * -ENOENT when me client is not found * -EINVAL when ctrl credits are <= 0 */ int mei_cl_flow_ctrl_reduce(struct mei_cl *cl) { struct mei_device *dev; int i; if (WARN_ON(!cl || !cl->dev)) return -EINVAL; dev = cl->dev; if (!dev->me_clients_num) return -ENOENT; for (i = 0; i < dev->me_clients_num; i++) { struct mei_me_client *me_cl = &dev->me_clients[i]; if (me_cl->client_id == cl->me_client_id) { if (me_cl->props.single_recv_buf != 0) { if (WARN_ON(me_cl->mei_flow_ctrl_creds <= 0)) return -EINVAL; dev->me_clients[i].mei_flow_ctrl_creds--; } else { if (WARN_ON(cl->mei_flow_ctrl_creds <= 0)) return -EINVAL; cl->mei_flow_ctrl_creds--; } return 0; } } return -ENOENT; } /** * mei_cl_read_start - the start read client message function. * * @cl: host client * * returns 0 on success, <0 on failure. */ int mei_cl_read_start(struct mei_cl *cl, size_t length) { struct mei_device *dev; struct mei_cl_cb *cb; int rets; int i; if (WARN_ON(!cl || !cl->dev)) return -ENODEV; dev = cl->dev; if (cl->state != MEI_FILE_CONNECTED) return -ENODEV; if (dev->dev_state != MEI_DEV_ENABLED) return -ENODEV; if (cl->read_cb) { dev_dbg(&dev->pdev->dev, "read is pending.\n"); return -EBUSY; } i = mei_me_cl_by_id(dev, cl->me_client_id); if (i < 0) { dev_err(&dev->pdev->dev, "no such me client %d\n", cl->me_client_id); return -ENODEV; } cb = mei_io_cb_init(cl, NULL); if (!cb) return -ENOMEM; /* always allocate at least client max message */ length = max_t(size_t, length, dev->me_clients[i].props.max_msg_length); rets = mei_io_cb_alloc_resp_buf(cb, length); if (rets) goto err; cb->fop_type = MEI_FOP_READ; if (dev->hbuf_is_ready) { dev->hbuf_is_ready = false; if (mei_hbm_cl_flow_control_req(dev, cl)) { rets = -ENODEV; goto err; } list_add_tail(&cb->list, &dev->read_list.list); } else { list_add_tail(&cb->list, &dev->ctrl_wr_list.list); } cl->read_cb = cb; return rets; err: mei_io_cb_free(cb); return rets; } /** * mei_cl_write - submit a write cb to mei device assumes device_lock is locked * * @cl: host client * @cl: write callback with filled data * * returns numbe of bytes sent on success, <0 on failure. */ int mei_cl_write(struct mei_cl *cl, struct mei_cl_cb *cb, bool blocking) { struct mei_device *dev; struct mei_msg_data *buf; struct mei_msg_hdr mei_hdr; int rets; if (WARN_ON(!cl || !cl->dev)) return -ENODEV; if (WARN_ON(!cb)) return -EINVAL; dev = cl->dev; buf = &cb->request_buffer; dev_dbg(&dev->pdev->dev, "mei_cl_write %d\n", buf->size); cb->fop_type = MEI_FOP_WRITE; rets = mei_cl_flow_ctrl_creds(cl); if (rets < 0) goto err; /* Host buffer is not ready, we queue the request */ if (rets == 0 || !dev->hbuf_is_ready) { cb->buf_idx = 0; /* unseting complete will enqueue the cb for write */ mei_hdr.msg_complete = 0; cl->writing_state = MEI_WRITING; rets = buf->size; goto out; } dev->hbuf_is_ready = false; /* Check for a maximum length */ if (buf->size > mei_hbuf_max_len(dev)) { mei_hdr.length = mei_hbuf_max_len(dev); mei_hdr.msg_complete = 0; } else { mei_hdr.length = buf->size; mei_hdr.msg_complete = 1; } mei_hdr.host_addr = cl->host_client_id; mei_hdr.me_addr = cl->me_client_id; mei_hdr.reserved = 0; dev_dbg(&dev->pdev->dev, "write " MEI_HDR_FMT "\n", MEI_HDR_PRM(&mei_hdr)); if (mei_write_message(dev, &mei_hdr, buf->data)) { rets = -EIO; goto err; } cl->writing_state = MEI_WRITING; cb->buf_idx = mei_hdr.length; rets = buf->size; out: if (mei_hdr.msg_complete) { if (mei_cl_flow_ctrl_reduce(cl)) { rets = -ENODEV; goto err; } list_add_tail(&cb->list, &dev->write_waiting_list.list); } else { list_add_tail(&cb->list, &dev->write_list.list); } if (blocking && cl->writing_state != MEI_WRITE_COMPLETE) { mutex_unlock(&dev->device_lock); if (wait_event_interruptible(cl->tx_wait, cl->writing_state == MEI_WRITE_COMPLETE)) { if (signal_pending(current)) rets = -EINTR; else rets = -ERESTARTSYS; } mutex_lock(&dev->device_lock); } err: return rets; } /** * mei_cl_all_disconnect - disconnect forcefully all connected clients * * @dev - mei device */ void mei_cl_all_disconnect(struct mei_device *dev) { struct mei_cl *cl, *next; list_for_each_entry_safe(cl, next, &dev->file_list, link) { cl->state = MEI_FILE_DISCONNECTED; cl->mei_flow_ctrl_creds = 0; cl->timer_count = 0; } } /** * mei_cl_all_read_wakeup - wake up all readings so they can be interrupted * * @dev - mei device */ void mei_cl_all_read_wakeup(struct mei_device *dev) { struct mei_cl *cl, *next; list_for_each_entry_safe(cl, next, &dev->file_list, link) { if (waitqueue_active(&cl->rx_wait)) { dev_dbg(&dev->pdev->dev, "Waking up client!\n"); wake_up_interruptible(&cl->rx_wait); } } } /** * mei_cl_all_write_clear - clear all pending writes * @dev - mei device */ void mei_cl_all_write_clear(struct mei_device *dev) { struct mei_cl_cb *cb, *next; struct list_head *list; list = &dev->write_list.list; list_for_each_entry_safe(cb, next, list, list) { list_del(&cb->list); mei_io_cb_free(cb); } list = &dev->write_waiting_list.list; list_for_each_entry_safe(cb, next, list, list) { list_del(&cb->list); mei_io_cb_free(cb); } }
gpl-2.0
chunyeow/ath
drivers/gpu/host1x/cdma.c
1023
12750
/* * Tegra host1x Command DMA * * Copyright (c) 2010-2013, NVIDIA Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <asm/cacheflush.h> #include <linux/device.h> #include <linux/dma-mapping.h> #include <linux/host1x.h> #include <linux/interrupt.h> #include <linux/kernel.h> #include <linux/kfifo.h> #include <linux/slab.h> #include <trace/events/host1x.h> #include "cdma.h" #include "channel.h" #include "dev.h" #include "debug.h" #include "job.h" /* * push_buffer * * The push buffer is a circular array of words to be fetched by command DMA. * Note that it works slightly differently to the sync queue; fence == pos * means that the push buffer is full, not empty. */ #define HOST1X_PUSHBUFFER_SLOTS 512 /* * Clean up push buffer resources */ static void host1x_pushbuffer_destroy(struct push_buffer *pb) { struct host1x_cdma *cdma = pb_to_cdma(pb); struct host1x *host1x = cdma_to_host1x(cdma); if (pb->phys != 0) dma_free_writecombine(host1x->dev, pb->size_bytes + 4, pb->mapped, pb->phys); pb->mapped = NULL; pb->phys = 0; } /* * Init push buffer resources */ static int host1x_pushbuffer_init(struct push_buffer *pb) { struct host1x_cdma *cdma = pb_to_cdma(pb); struct host1x *host1x = cdma_to_host1x(cdma); pb->mapped = NULL; pb->phys = 0; pb->size_bytes = HOST1X_PUSHBUFFER_SLOTS * 8; /* initialize buffer pointers */ pb->fence = pb->size_bytes - 8; pb->pos = 0; /* allocate and map pushbuffer memory */ pb->mapped = dma_alloc_writecombine(host1x->dev, pb->size_bytes + 4, &pb->phys, GFP_KERNEL); if (!pb->mapped) goto fail; host1x_hw_pushbuffer_init(host1x, pb); return 0; fail: host1x_pushbuffer_destroy(pb); return -ENOMEM; } /* * Push two words to the push buffer * Caller must ensure push buffer is not full */ static void host1x_pushbuffer_push(struct push_buffer *pb, u32 op1, u32 op2) { u32 pos = pb->pos; u32 *p = (u32 *)((void *)pb->mapped + pos); WARN_ON(pos == pb->fence); *(p++) = op1; *(p++) = op2; pb->pos = (pos + 8) & (pb->size_bytes - 1); } /* * Pop a number of two word slots from the push buffer * Caller must ensure push buffer is not empty */ static void host1x_pushbuffer_pop(struct push_buffer *pb, unsigned int slots) { /* Advance the next write position */ pb->fence = (pb->fence + slots * 8) & (pb->size_bytes - 1); } /* * Return the number of two word slots free in the push buffer */ static u32 host1x_pushbuffer_space(struct push_buffer *pb) { return ((pb->fence - pb->pos) & (pb->size_bytes - 1)) / 8; } /* * Sleep (if necessary) until the requested event happens * - CDMA_EVENT_SYNC_QUEUE_EMPTY : sync queue is completely empty. * - Returns 1 * - CDMA_EVENT_PUSH_BUFFER_SPACE : there is space in the push buffer * - Return the amount of space (> 0) * Must be called with the cdma lock held. */ unsigned int host1x_cdma_wait_locked(struct host1x_cdma *cdma, enum cdma_event event) { for (;;) { unsigned int space; if (event == CDMA_EVENT_SYNC_QUEUE_EMPTY) space = list_empty(&cdma->sync_queue) ? 1 : 0; else if (event == CDMA_EVENT_PUSH_BUFFER_SPACE) { struct push_buffer *pb = &cdma->push_buffer; space = host1x_pushbuffer_space(pb); } else { WARN_ON(1); return -EINVAL; } if (space) return space; trace_host1x_wait_cdma(dev_name(cdma_to_channel(cdma)->dev), event); /* If somebody has managed to already start waiting, yield */ if (cdma->event != CDMA_EVENT_NONE) { mutex_unlock(&cdma->lock); schedule(); mutex_lock(&cdma->lock); continue; } cdma->event = event; mutex_unlock(&cdma->lock); down(&cdma->sem); mutex_lock(&cdma->lock); } return 0; } /* * Start timer that tracks the time spent by the job. * Must be called with the cdma lock held. */ static void cdma_start_timer_locked(struct host1x_cdma *cdma, struct host1x_job *job) { struct host1x *host = cdma_to_host1x(cdma); if (cdma->timeout.client) { /* timer already started */ return; } cdma->timeout.client = job->client; cdma->timeout.syncpt = host1x_syncpt_get(host, job->syncpt_id); cdma->timeout.syncpt_val = job->syncpt_end; cdma->timeout.start_ktime = ktime_get(); schedule_delayed_work(&cdma->timeout.wq, msecs_to_jiffies(job->timeout)); } /* * Stop timer when a buffer submission completes. * Must be called with the cdma lock held. */ static void stop_cdma_timer_locked(struct host1x_cdma *cdma) { cancel_delayed_work(&cdma->timeout.wq); cdma->timeout.client = 0; } /* * For all sync queue entries that have already finished according to the * current sync point registers: * - unpin & unref their mems * - pop their push buffer slots * - remove them from the sync queue * This is normally called from the host code's worker thread, but can be * called manually if necessary. * Must be called with the cdma lock held. */ static void update_cdma_locked(struct host1x_cdma *cdma) { bool signal = false; struct host1x *host1x = cdma_to_host1x(cdma); struct host1x_job *job, *n; /* If CDMA is stopped, queue is cleared and we can return */ if (!cdma->running) return; /* * Walk the sync queue, reading the sync point registers as necessary, * to consume as many sync queue entries as possible without blocking */ list_for_each_entry_safe(job, n, &cdma->sync_queue, list) { struct host1x_syncpt *sp = host1x_syncpt_get(host1x, job->syncpt_id); /* Check whether this syncpt has completed, and bail if not */ if (!host1x_syncpt_is_expired(sp, job->syncpt_end)) { /* Start timer on next pending syncpt */ if (job->timeout) cdma_start_timer_locked(cdma, job); break; } /* Cancel timeout, when a buffer completes */ if (cdma->timeout.client) stop_cdma_timer_locked(cdma); /* Unpin the memory */ host1x_job_unpin(job); /* Pop push buffer slots */ if (job->num_slots) { struct push_buffer *pb = &cdma->push_buffer; host1x_pushbuffer_pop(pb, job->num_slots); if (cdma->event == CDMA_EVENT_PUSH_BUFFER_SPACE) signal = true; } list_del(&job->list); host1x_job_put(job); } if (cdma->event == CDMA_EVENT_SYNC_QUEUE_EMPTY && list_empty(&cdma->sync_queue)) signal = true; if (signal) { cdma->event = CDMA_EVENT_NONE; up(&cdma->sem); } } void host1x_cdma_update_sync_queue(struct host1x_cdma *cdma, struct device *dev) { u32 restart_addr; u32 syncpt_incrs; struct host1x_job *job = NULL; u32 syncpt_val; struct host1x *host1x = cdma_to_host1x(cdma); syncpt_val = host1x_syncpt_load(cdma->timeout.syncpt); dev_dbg(dev, "%s: starting cleanup (thresh %d)\n", __func__, syncpt_val); /* * Move the sync_queue read pointer to the first entry that hasn't * completed based on the current HW syncpt value. It's likely there * won't be any (i.e. we're still at the head), but covers the case * where a syncpt incr happens just prior/during the teardown. */ dev_dbg(dev, "%s: skip completed buffers still in sync_queue\n", __func__); list_for_each_entry(job, &cdma->sync_queue, list) { if (syncpt_val < job->syncpt_end) break; host1x_job_dump(dev, job); } /* * Walk the sync_queue, first incrementing with the CPU syncpts that * are partially executed (the first buffer) or fully skipped while * still in the current context (slots are also NOP-ed). * * At the point contexts are interleaved, syncpt increments must be * done inline with the pushbuffer from a GATHER buffer to maintain * the order (slots are modified to be a GATHER of syncpt incrs). * * Note: save in restart_addr the location where the timed out buffer * started in the PB, so we can start the refetch from there (with the * modified NOP-ed PB slots). This lets things appear to have completed * properly for this buffer and resources are freed. */ dev_dbg(dev, "%s: perform CPU incr on pending same ctx buffers\n", __func__); if (!list_empty(&cdma->sync_queue)) restart_addr = job->first_get; else restart_addr = cdma->last_pos; /* do CPU increments as long as this context continues */ list_for_each_entry_from(job, &cdma->sync_queue, list) { /* different context, gets us out of this loop */ if (job->client != cdma->timeout.client) break; /* won't need a timeout when replayed */ job->timeout = 0; syncpt_incrs = job->syncpt_end - syncpt_val; dev_dbg(dev, "%s: CPU incr (%d)\n", __func__, syncpt_incrs); host1x_job_dump(dev, job); /* safe to use CPU to incr syncpts */ host1x_hw_cdma_timeout_cpu_incr(host1x, cdma, job->first_get, syncpt_incrs, job->syncpt_end, job->num_slots); syncpt_val += syncpt_incrs; } /* The following sumbits from the same client may be dependent on the * failed submit and therefore they may fail. Force a small timeout * to make the queue cleanup faster */ list_for_each_entry_from(job, &cdma->sync_queue, list) if (job->client == cdma->timeout.client) job->timeout = min_t(unsigned int, job->timeout, 500); dev_dbg(dev, "%s: finished sync_queue modification\n", __func__); /* roll back DMAGET and start up channel again */ host1x_hw_cdma_resume(host1x, cdma, restart_addr); } /* * Create a cdma */ int host1x_cdma_init(struct host1x_cdma *cdma) { int err; mutex_init(&cdma->lock); sema_init(&cdma->sem, 0); INIT_LIST_HEAD(&cdma->sync_queue); cdma->event = CDMA_EVENT_NONE; cdma->running = false; cdma->torndown = false; err = host1x_pushbuffer_init(&cdma->push_buffer); if (err) return err; return 0; } /* * Destroy a cdma */ int host1x_cdma_deinit(struct host1x_cdma *cdma) { struct push_buffer *pb = &cdma->push_buffer; struct host1x *host1x = cdma_to_host1x(cdma); if (cdma->running) { pr_warn("%s: CDMA still running\n", __func__); return -EBUSY; } host1x_pushbuffer_destroy(pb); host1x_hw_cdma_timeout_destroy(host1x, cdma); return 0; } /* * Begin a cdma submit */ int host1x_cdma_begin(struct host1x_cdma *cdma, struct host1x_job *job) { struct host1x *host1x = cdma_to_host1x(cdma); mutex_lock(&cdma->lock); if (job->timeout) { /* init state on first submit with timeout value */ if (!cdma->timeout.initialized) { int err; err = host1x_hw_cdma_timeout_init(host1x, cdma, job->syncpt_id); if (err) { mutex_unlock(&cdma->lock); return err; } } } if (!cdma->running) host1x_hw_cdma_start(host1x, cdma); cdma->slots_free = 0; cdma->slots_used = 0; cdma->first_get = cdma->push_buffer.pos; trace_host1x_cdma_begin(dev_name(job->channel->dev)); return 0; } /* * Push two words into a push buffer slot * Blocks as necessary if the push buffer is full. */ void host1x_cdma_push(struct host1x_cdma *cdma, u32 op1, u32 op2) { struct host1x *host1x = cdma_to_host1x(cdma); struct push_buffer *pb = &cdma->push_buffer; u32 slots_free = cdma->slots_free; if (host1x_debug_trace_cmdbuf) trace_host1x_cdma_push(dev_name(cdma_to_channel(cdma)->dev), op1, op2); if (slots_free == 0) { host1x_hw_cdma_flush(host1x, cdma); slots_free = host1x_cdma_wait_locked(cdma, CDMA_EVENT_PUSH_BUFFER_SPACE); } cdma->slots_free = slots_free - 1; cdma->slots_used++; host1x_pushbuffer_push(pb, op1, op2); } /* * End a cdma submit * Kick off DMA, add job to the sync queue, and a number of slots to be freed * from the pushbuffer. The handles for a submit must all be pinned at the same * time, but they can be unpinned in smaller chunks. */ void host1x_cdma_end(struct host1x_cdma *cdma, struct host1x_job *job) { struct host1x *host1x = cdma_to_host1x(cdma); bool idle = list_empty(&cdma->sync_queue); host1x_hw_cdma_flush(host1x, cdma); job->first_get = cdma->first_get; job->num_slots = cdma->slots_used; host1x_job_get(job); list_add_tail(&job->list, &cdma->sync_queue); /* start timer on idle -> active transitions */ if (job->timeout && idle) cdma_start_timer_locked(cdma, job); trace_host1x_cdma_end(dev_name(job->channel->dev)); mutex_unlock(&cdma->lock); } /* * Update cdma state according to current sync point values */ void host1x_cdma_update(struct host1x_cdma *cdma) { mutex_lock(&cdma->lock); update_cdma_locked(cdma); mutex_unlock(&cdma->lock); }
gpl-2.0
placiano/NBKernel_N4
arch/arm/mach-davinci/devices-tnetv107x.c
2047
10001
/* * Texas Instruments TNETV107X SoC devices * * Copyright (C) 2010 Texas Instruments * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation version 2. * * This program is distributed "as is" WITHOUT ANY WARRANTY of any * kind, whether express or implied; 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/dma-mapping.h> #include <linux/clk.h> #include <linux/slab.h> #include <mach/common.h> #include <mach/irqs.h> #include <mach/edma.h> #include <mach/tnetv107x.h> #include "clock.h" /* Base addresses for on-chip devices */ #define TNETV107X_TPCC_BASE 0x01c00000 #define TNETV107X_TPTC0_BASE 0x01c10000 #define TNETV107X_TPTC1_BASE 0x01c10400 #define TNETV107X_WDOG_BASE 0x08086700 #define TNETV107X_TSC_BASE 0x08088500 #define TNETV107X_SDIO0_BASE 0x08088700 #define TNETV107X_SDIO1_BASE 0x08088800 #define TNETV107X_KEYPAD_BASE 0x08088a00 #define TNETV107X_SSP_BASE 0x08088c00 #define TNETV107X_ASYNC_EMIF_CNTRL_BASE 0x08200000 #define TNETV107X_ASYNC_EMIF_DATA_CE0_BASE 0x30000000 #define TNETV107X_ASYNC_EMIF_DATA_CE1_BASE 0x40000000 #define TNETV107X_ASYNC_EMIF_DATA_CE2_BASE 0x44000000 #define TNETV107X_ASYNC_EMIF_DATA_CE3_BASE 0x48000000 /* TNETV107X specific EDMA3 information */ #define EDMA_TNETV107X_NUM_DMACH 64 #define EDMA_TNETV107X_NUM_TCC 64 #define EDMA_TNETV107X_NUM_PARAMENTRY 128 #define EDMA_TNETV107X_NUM_EVQUE 2 #define EDMA_TNETV107X_NUM_TC 2 #define EDMA_TNETV107X_CHMAP_EXIST 0 #define EDMA_TNETV107X_NUM_REGIONS 4 #define TNETV107X_DMACH2EVENT_MAP0 0x3C0CE000u #define TNETV107X_DMACH2EVENT_MAP1 0x000FFFFFu #define TNETV107X_DMACH_SDIO0_RX 26 #define TNETV107X_DMACH_SDIO0_TX 27 #define TNETV107X_DMACH_SDIO1_RX 28 #define TNETV107X_DMACH_SDIO1_TX 29 static const s8 edma_tc_mapping[][2] = { /* event queue no TC no */ { 0, 0 }, { 1, 1 }, { -1, -1 } }; static const s8 edma_priority_mapping[][2] = { /* event queue no Prio */ { 0, 3 }, { 1, 7 }, { -1, -1 } }; static struct edma_soc_info edma_cc0_info = { .n_channel = EDMA_TNETV107X_NUM_DMACH, .n_region = EDMA_TNETV107X_NUM_REGIONS, .n_slot = EDMA_TNETV107X_NUM_PARAMENTRY, .n_tc = EDMA_TNETV107X_NUM_TC, .n_cc = 1, .queue_tc_mapping = edma_tc_mapping, .queue_priority_mapping = edma_priority_mapping, .default_queue = EVENTQ_1, }; static struct edma_soc_info *tnetv107x_edma_info[EDMA_MAX_CC] = { &edma_cc0_info, }; static struct resource edma_resources[] = { { .name = "edma_cc0", .start = TNETV107X_TPCC_BASE, .end = TNETV107X_TPCC_BASE + SZ_32K - 1, .flags = IORESOURCE_MEM, }, { .name = "edma_tc0", .start = TNETV107X_TPTC0_BASE, .end = TNETV107X_TPTC0_BASE + SZ_1K - 1, .flags = IORESOURCE_MEM, }, { .name = "edma_tc1", .start = TNETV107X_TPTC1_BASE, .end = TNETV107X_TPTC1_BASE + SZ_1K - 1, .flags = IORESOURCE_MEM, }, { .name = "edma0", .start = IRQ_TNETV107X_TPCC, .flags = IORESOURCE_IRQ, }, { .name = "edma0_err", .start = IRQ_TNETV107X_TPCC_ERR, .flags = IORESOURCE_IRQ, }, }; static struct platform_device edma_device = { .name = "edma", .id = -1, .num_resources = ARRAY_SIZE(edma_resources), .resource = edma_resources, .dev.platform_data = tnetv107x_edma_info, }; static struct plat_serial8250_port serial_data[] = { { .mapbase = TNETV107X_UART0_BASE, .irq = IRQ_TNETV107X_UART0, .flags = UPF_BOOT_AUTOCONF | UPF_SKIP_TEST | UPF_FIXED_TYPE | UPF_IOREMAP, .type = PORT_AR7, .iotype = UPIO_MEM32, .regshift = 2, }, { .mapbase = TNETV107X_UART1_BASE, .irq = IRQ_TNETV107X_UART1, .flags = UPF_BOOT_AUTOCONF | UPF_SKIP_TEST | UPF_FIXED_TYPE | UPF_IOREMAP, .type = PORT_AR7, .iotype = UPIO_MEM32, .regshift = 2, }, { .mapbase = TNETV107X_UART2_BASE, .irq = IRQ_TNETV107X_UART2, .flags = UPF_BOOT_AUTOCONF | UPF_SKIP_TEST | UPF_FIXED_TYPE | UPF_IOREMAP, .type = PORT_AR7, .iotype = UPIO_MEM32, .regshift = 2, }, { .flags = 0, }, }; struct platform_device tnetv107x_serial_device = { .name = "serial8250", .id = PLAT8250_DEV_PLATFORM, .dev.platform_data = serial_data, }; static struct resource mmc0_resources[] = { { /* Memory mapped registers */ .start = TNETV107X_SDIO0_BASE, .end = TNETV107X_SDIO0_BASE + 0x0ff, .flags = IORESOURCE_MEM }, { /* MMC interrupt */ .start = IRQ_TNETV107X_MMC0, .flags = IORESOURCE_IRQ }, { /* SDIO interrupt */ .start = IRQ_TNETV107X_SDIO0, .flags = IORESOURCE_IRQ }, { /* DMA RX */ .start = EDMA_CTLR_CHAN(0, TNETV107X_DMACH_SDIO0_RX), .flags = IORESOURCE_DMA }, { /* DMA TX */ .start = EDMA_CTLR_CHAN(0, TNETV107X_DMACH_SDIO0_TX), .flags = IORESOURCE_DMA }, }; static struct resource mmc1_resources[] = { { /* Memory mapped registers */ .start = TNETV107X_SDIO1_BASE, .end = TNETV107X_SDIO1_BASE + 0x0ff, .flags = IORESOURCE_MEM }, { /* MMC interrupt */ .start = IRQ_TNETV107X_MMC1, .flags = IORESOURCE_IRQ }, { /* SDIO interrupt */ .start = IRQ_TNETV107X_SDIO1, .flags = IORESOURCE_IRQ }, { /* DMA RX */ .start = EDMA_CTLR_CHAN(0, TNETV107X_DMACH_SDIO1_RX), .flags = IORESOURCE_DMA }, { /* DMA TX */ .start = EDMA_CTLR_CHAN(0, TNETV107X_DMACH_SDIO1_TX), .flags = IORESOURCE_DMA }, }; static u64 mmc0_dma_mask = DMA_BIT_MASK(32); static u64 mmc1_dma_mask = DMA_BIT_MASK(32); static struct platform_device mmc_devices[2] = { { .name = "dm6441-mmc", .id = 0, .dev = { .dma_mask = &mmc0_dma_mask, .coherent_dma_mask = DMA_BIT_MASK(32), }, .num_resources = ARRAY_SIZE(mmc0_resources), .resource = mmc0_resources }, { .name = "dm6441-mmc", .id = 1, .dev = { .dma_mask = &mmc1_dma_mask, .coherent_dma_mask = DMA_BIT_MASK(32), }, .num_resources = ARRAY_SIZE(mmc1_resources), .resource = mmc1_resources }, }; static const u32 emif_windows[] = { TNETV107X_ASYNC_EMIF_DATA_CE0_BASE, TNETV107X_ASYNC_EMIF_DATA_CE1_BASE, TNETV107X_ASYNC_EMIF_DATA_CE2_BASE, TNETV107X_ASYNC_EMIF_DATA_CE3_BASE, }; static const u32 emif_window_sizes[] = { SZ_256M, SZ_64M, SZ_64M, SZ_64M }; static struct resource wdt_resources[] = { { .start = TNETV107X_WDOG_BASE, .end = TNETV107X_WDOG_BASE + SZ_4K - 1, .flags = IORESOURCE_MEM, }, }; struct platform_device tnetv107x_wdt_device = { .name = "tnetv107x_wdt", .id = 0, .num_resources = ARRAY_SIZE(wdt_resources), .resource = wdt_resources, }; static int __init nand_init(int chipsel, struct davinci_nand_pdata *data) { struct resource res[2]; struct platform_device *pdev; u32 range; int ret; /* Figure out the resource range from the ale/cle masks */ range = max(data->mask_cle, data->mask_ale); range = PAGE_ALIGN(range + 4) - 1; if (range >= emif_window_sizes[chipsel]) return -EINVAL; pdev = kzalloc(sizeof(*pdev), GFP_KERNEL); if (!pdev) return -ENOMEM; pdev->name = "davinci_nand"; pdev->id = chipsel; pdev->dev.platform_data = data; memset(res, 0, sizeof(res)); res[0].start = emif_windows[chipsel]; res[0].end = res[0].start + range; res[0].flags = IORESOURCE_MEM; res[1].start = TNETV107X_ASYNC_EMIF_CNTRL_BASE; res[1].end = res[1].start + SZ_4K - 1; res[1].flags = IORESOURCE_MEM; ret = platform_device_add_resources(pdev, res, ARRAY_SIZE(res)); if (ret < 0) { kfree(pdev); return ret; } return platform_device_register(pdev); } static struct resource keypad_resources[] = { { .start = TNETV107X_KEYPAD_BASE, .end = TNETV107X_KEYPAD_BASE + 0xff, .flags = IORESOURCE_MEM, }, { .start = IRQ_TNETV107X_KEYPAD, .flags = IORESOURCE_IRQ, .name = "press", }, { .start = IRQ_TNETV107X_KEYPAD_FREE, .flags = IORESOURCE_IRQ, .name = "release", }, }; static struct platform_device keypad_device = { .name = "tnetv107x-keypad", .num_resources = ARRAY_SIZE(keypad_resources), .resource = keypad_resources, }; static struct resource tsc_resources[] = { { .start = TNETV107X_TSC_BASE, .end = TNETV107X_TSC_BASE + 0xff, .flags = IORESOURCE_MEM, }, { .start = IRQ_TNETV107X_TSC, .flags = IORESOURCE_IRQ, }, }; static struct platform_device tsc_device = { .name = "tnetv107x-ts", .num_resources = ARRAY_SIZE(tsc_resources), .resource = tsc_resources, }; static struct resource ssp_resources[] = { { .start = TNETV107X_SSP_BASE, .end = TNETV107X_SSP_BASE + 0x1ff, .flags = IORESOURCE_MEM, }, { .start = IRQ_TNETV107X_SSP, .flags = IORESOURCE_IRQ, }, }; static struct platform_device ssp_device = { .name = "ti-ssp", .id = -1, .num_resources = ARRAY_SIZE(ssp_resources), .resource = ssp_resources, }; void __init tnetv107x_devices_init(struct tnetv107x_device_info *info) { int i, error; struct clk *tsc_clk; /* * The reset defaults for tnetv107x tsc clock divider is set too high. * This forces the clock down to a range that allows the ADC to * complete sample conversion in time. */ tsc_clk = clk_get(NULL, "sys_tsc_clk"); if (!IS_ERR(tsc_clk)) { error = clk_set_rate(tsc_clk, 5000000); WARN_ON(error < 0); clk_put(tsc_clk); } platform_device_register(&edma_device); platform_device_register(&tnetv107x_wdt_device); platform_device_register(&tsc_device); if (info->serial_config) davinci_serial_init(info->serial_config); for (i = 0; i < 2; i++) if (info->mmc_config[i]) { mmc_devices[i].dev.platform_data = info->mmc_config[i]; platform_device_register(&mmc_devices[i]); } for (i = 0; i < 4; i++) if (info->nand_config[i]) nand_init(i, info->nand_config[i]); if (info->keypad_config) { keypad_device.dev.platform_data = info->keypad_config; platform_device_register(&keypad_device); } if (info->ssp_config) { ssp_device.dev.platform_data = info->ssp_config; platform_device_register(&ssp_device); } }
gpl-2.0
MR64/android_kernel_htc_flounder
arch/arm/mach-prima2/common.c
2047
2474
/* * Defines machines for CSR SiRFprimaII * * Copyright (c) 2011 Cambridge Silicon Radio Limited, a CSR plc group company. * * Licensed under GPLv2 or later. */ #include <linux/clocksource.h> #include <linux/init.h> #include <linux/kernel.h> #include <linux/irqchip.h> #include <asm/sizes.h> #include <asm/mach-types.h> #include <asm/mach/arch.h> #include <linux/of.h> #include <linux/of_platform.h> #include "common.h" static struct of_device_id sirfsoc_of_bus_ids[] __initdata = { { .compatible = "simple-bus", }, {}, }; void __init sirfsoc_mach_init(void) { of_platform_bus_probe(NULL, sirfsoc_of_bus_ids, NULL); } void __init sirfsoc_init_late(void) { sirfsoc_pm_init(); } static __init void sirfsoc_init_time(void) { /* initialize clocking early, we want to set the OS timer */ sirfsoc_of_clk_init(); clocksource_of_init(); } static __init void sirfsoc_map_io(void) { sirfsoc_map_lluart(); sirfsoc_map_scu(); } #ifdef CONFIG_ARCH_ATLAS6 static const char *atlas6_dt_match[] __initdata = { "sirf,atlas6", NULL }; DT_MACHINE_START(ATLAS6_DT, "Generic ATLAS6 (Flattened Device Tree)") /* Maintainer: Barry Song <baohua.song@csr.com> */ .nr_irqs = 128, .map_io = sirfsoc_map_io, .init_irq = irqchip_init, .init_time = sirfsoc_init_time, .init_machine = sirfsoc_mach_init, .init_late = sirfsoc_init_late, .dt_compat = atlas6_dt_match, .restart = sirfsoc_restart, MACHINE_END #endif #ifdef CONFIG_ARCH_PRIMA2 static const char *prima2_dt_match[] __initdata = { "sirf,prima2", NULL }; DT_MACHINE_START(PRIMA2_DT, "Generic PRIMA2 (Flattened Device Tree)") /* Maintainer: Barry Song <baohua.song@csr.com> */ .nr_irqs = 128, .map_io = sirfsoc_map_io, .init_irq = irqchip_init, .init_time = sirfsoc_init_time, .dma_zone_size = SZ_256M, .init_machine = sirfsoc_mach_init, .init_late = sirfsoc_init_late, .dt_compat = prima2_dt_match, .restart = sirfsoc_restart, MACHINE_END #endif #ifdef CONFIG_ARCH_MARCO static const char *marco_dt_match[] __initdata = { "sirf,marco", NULL }; DT_MACHINE_START(MARCO_DT, "Generic MARCO (Flattened Device Tree)") /* Maintainer: Barry Song <baohua.song@csr.com> */ .smp = smp_ops(sirfsoc_smp_ops), .map_io = sirfsoc_map_io, .init_irq = irqchip_init, .init_time = sirfsoc_init_time, .init_machine = sirfsoc_mach_init, .init_late = sirfsoc_init_late, .dt_compat = marco_dt_match, .restart = sirfsoc_restart, MACHINE_END #endif
gpl-2.0
xiaowei942/Tiny210-kernel-2.6.35.7
drivers/ide/ide-scan-pci.c
2047
2763
/* * support for probing IDE PCI devices in the PCI bus order * * Copyright (c) 1998-2000 Andre Hedrick <andre@linux-ide.org> * Copyright (c) 1995-1998 Mark Lord * * May be copied or modified under the terms of the GNU General Public License */ #include <linux/kernel.h> #include <linux/init.h> #include <linux/module.h> #include <linux/ide.h> /* * Module interfaces */ static int pre_init = 1; /* Before first ordered IDE scan */ static LIST_HEAD(ide_pci_drivers); /* * __ide_pci_register_driver - attach IDE driver * @driver: pci driver * @module: owner module of the driver * * Registers a driver with the IDE layer. The IDE layer arranges that * boot time setup is done in the expected device order and then * hands the controllers off to the core PCI code to do the rest of * the work. * * Returns are the same as for pci_register_driver */ int __ide_pci_register_driver(struct pci_driver *driver, struct module *module, const char *mod_name) { if (!pre_init) return __pci_register_driver(driver, module, mod_name); driver->driver.owner = module; list_add_tail(&driver->node, &ide_pci_drivers); return 0; } EXPORT_SYMBOL_GPL(__ide_pci_register_driver); /** * ide_scan_pcidev - find an IDE driver for a device * @dev: PCI device to check * * Look for an IDE driver to handle the device we are considering. * This is only used during boot up to get the ordering correct. After * boot up the pci layer takes over the job. */ static int __init ide_scan_pcidev(struct pci_dev *dev) { struct list_head *l; struct pci_driver *d; list_for_each(l, &ide_pci_drivers) { d = list_entry(l, struct pci_driver, node); if (d->id_table) { const struct pci_device_id *id = pci_match_id(d->id_table, dev); if (id != NULL && d->probe(dev, id) >= 0) { dev->driver = d; pci_dev_get(dev); return 1; } } } return 0; } /** * ide_scan_pcibus - perform the initial IDE driver scan * * Perform the initial bus rather than driver ordered scan of the * PCI drivers. After this all IDE pci handling becomes standard * module ordering not traditionally ordered. */ static int __init ide_scan_pcibus(void) { struct pci_dev *dev = NULL; struct pci_driver *d; struct list_head *l, *n; pre_init = 0; while ((dev = pci_get_device(PCI_ANY_ID, PCI_ANY_ID, dev))) ide_scan_pcidev(dev); /* * Hand the drivers over to the PCI layer now we * are post init. */ list_for_each_safe(l, n, &ide_pci_drivers) { list_del(l); d = list_entry(l, struct pci_driver, node); if (__pci_register_driver(d, d->driver.owner, d->driver.mod_name)) printk(KERN_ERR "%s: failed to register %s driver\n", __func__, d->driver.mod_name); } return 0; } module_init(ide_scan_pcibus);
gpl-2.0
MoKee/android_kernel_zte_msm8994
kernel/kallsyms.c
2559
15401
/* * kallsyms.c: in-kernel printing of symbolic oopses and stack traces. * * Rewritten and vastly simplified by Rusty Russell for in-kernel * module loader: * Copyright 2002 Rusty Russell <rusty@rustcorp.com.au> IBM Corporation * * ChangeLog: * * (25/Aug/2004) Paulo Marques <pmarques@grupopie.com> * Changed the compression method from stem compression to "table lookup" * compression (see scripts/kallsyms.c for a more complete description) */ #include <linux/kallsyms.h> #include <linux/module.h> #include <linux/init.h> #include <linux/seq_file.h> #include <linux/fs.h> #include <linux/kdb.h> #include <linux/err.h> #include <linux/proc_fs.h> #include <linux/sched.h> /* for cond_resched */ #include <linux/mm.h> #include <linux/ctype.h> #include <linux/slab.h> #include <asm/sections.h> #ifdef CONFIG_KALLSYMS_ALL #define all_var 1 #else #define all_var 0 #endif /* * These will be re-linked against their real values * during the second link stage. */ extern const unsigned long kallsyms_addresses[] __attribute__((weak)); extern const u8 kallsyms_names[] __attribute__((weak)); /* * Tell the compiler that the count isn't in the small data section if the arch * has one (eg: FRV). */ extern const unsigned long kallsyms_num_syms __attribute__((weak, section(".rodata"))); extern const u8 kallsyms_token_table[] __attribute__((weak)); extern const u16 kallsyms_token_index[] __attribute__((weak)); extern const unsigned long kallsyms_markers[] __attribute__((weak)); static inline int is_kernel_inittext(unsigned long addr) { if (addr >= (unsigned long)_sinittext && addr <= (unsigned long)_einittext) return 1; return 0; } static inline int is_kernel_text(unsigned long addr) { if ((addr >= (unsigned long)_stext && addr <= (unsigned long)_etext) || arch_is_kernel_text(addr)) return 1; return in_gate_area_no_mm(addr); } static inline int is_kernel(unsigned long addr) { if (addr >= (unsigned long)_stext && addr <= (unsigned long)_end) return 1; return in_gate_area_no_mm(addr); } static int is_ksym_addr(unsigned long addr) { if (all_var) return is_kernel(addr); return is_kernel_text(addr) || is_kernel_inittext(addr); } /* * Expand a compressed symbol data into the resulting uncompressed string, * if uncompressed string is too long (>= maxlen), it will be truncated, * given the offset to where the symbol is in the compressed stream. */ static unsigned int kallsyms_expand_symbol(unsigned int off, char *result, size_t maxlen) { int len, skipped_first = 0; const u8 *tptr, *data; /* Get the compressed symbol length from the first symbol byte. */ data = &kallsyms_names[off]; len = *data; data++; /* * Update the offset to return the offset for the next symbol on * the compressed stream. */ off += len + 1; /* * For every byte on the compressed symbol data, copy the table * entry for that byte. */ while (len) { tptr = &kallsyms_token_table[kallsyms_token_index[*data]]; data++; len--; while (*tptr) { if (skipped_first) { if (maxlen <= 1) goto tail; *result = *tptr; result++; maxlen--; } else skipped_first = 1; tptr++; } } tail: if (maxlen) *result = '\0'; /* Return to offset to the next symbol. */ return off; } /* * Get symbol type information. This is encoded as a single char at the * beginning of the symbol name. */ static char kallsyms_get_symbol_type(unsigned int off) { /* * Get just the first code, look it up in the token table, * and return the first char from this token. */ return kallsyms_token_table[kallsyms_token_index[kallsyms_names[off + 1]]]; } /* * Find the offset on the compressed stream given and index in the * kallsyms array. */ static unsigned int get_symbol_offset(unsigned long pos) { const u8 *name; int i; /* * Use the closest marker we have. We have markers every 256 positions, * so that should be close enough. */ name = &kallsyms_names[kallsyms_markers[pos >> 8]]; /* * Sequentially scan all the symbols up to the point we're searching * for. Every symbol is stored in a [<len>][<len> bytes of data] format, * so we just need to add the len to the current pointer for every * symbol we wish to skip. */ for (i = 0; i < (pos & 0xFF); i++) name = name + (*name) + 1; return name - kallsyms_names; } /* Lookup the address for this symbol. Returns 0 if not found. */ unsigned long kallsyms_lookup_name(const char *name) { char namebuf[KSYM_NAME_LEN]; unsigned long i; unsigned int off; for (i = 0, off = 0; i < kallsyms_num_syms; i++) { off = kallsyms_expand_symbol(off, namebuf, ARRAY_SIZE(namebuf)); if (strcmp(namebuf, name) == 0) return kallsyms_addresses[i]; } return module_kallsyms_lookup_name(name); } EXPORT_SYMBOL_GPL(kallsyms_lookup_name); int kallsyms_on_each_symbol(int (*fn)(void *, const char *, struct module *, unsigned long), void *data) { char namebuf[KSYM_NAME_LEN]; unsigned long i; unsigned int off; int ret; for (i = 0, off = 0; i < kallsyms_num_syms; i++) { off = kallsyms_expand_symbol(off, namebuf, ARRAY_SIZE(namebuf)); ret = fn(data, namebuf, NULL, kallsyms_addresses[i]); if (ret != 0) return ret; } return module_kallsyms_on_each_symbol(fn, data); } EXPORT_SYMBOL_GPL(kallsyms_on_each_symbol); static unsigned long get_symbol_pos(unsigned long addr, unsigned long *symbolsize, unsigned long *offset) { unsigned long symbol_start = 0, symbol_end = 0; unsigned long i, low, high, mid; /* This kernel should never had been booted. */ BUG_ON(!kallsyms_addresses); /* Do a binary search on the sorted kallsyms_addresses array. */ low = 0; high = kallsyms_num_syms; while (high - low > 1) { mid = low + (high - low) / 2; if (kallsyms_addresses[mid] <= addr) low = mid; else high = mid; } /* * Search for the first aliased symbol. Aliased * symbols are symbols with the same address. */ while (low && kallsyms_addresses[low-1] == kallsyms_addresses[low]) --low; symbol_start = kallsyms_addresses[low]; /* Search for next non-aliased symbol. */ for (i = low + 1; i < kallsyms_num_syms; i++) { if (kallsyms_addresses[i] > symbol_start) { symbol_end = kallsyms_addresses[i]; break; } } /* If we found no next symbol, we use the end of the section. */ if (!symbol_end) { if (is_kernel_inittext(addr)) symbol_end = (unsigned long)_einittext; else if (all_var) symbol_end = (unsigned long)_end; else symbol_end = (unsigned long)_etext; } if (symbolsize) *symbolsize = symbol_end - symbol_start; if (offset) *offset = addr - symbol_start; return low; } /* * Lookup an address but don't bother to find any names. */ int kallsyms_lookup_size_offset(unsigned long addr, unsigned long *symbolsize, unsigned long *offset) { char namebuf[KSYM_NAME_LEN]; if (is_ksym_addr(addr)) return !!get_symbol_pos(addr, symbolsize, offset); return !!module_address_lookup(addr, symbolsize, offset, NULL, namebuf); } /* * Lookup an address * - modname is set to NULL if it's in the kernel. * - We guarantee that the returned name is valid until we reschedule even if. * It resides in a module. * - We also guarantee that modname will be valid until rescheduled. */ const char *kallsyms_lookup(unsigned long addr, unsigned long *symbolsize, unsigned long *offset, char **modname, char *namebuf) { namebuf[KSYM_NAME_LEN - 1] = 0; namebuf[0] = 0; if (is_ksym_addr(addr)) { unsigned long pos; pos = get_symbol_pos(addr, symbolsize, offset); /* Grab name */ kallsyms_expand_symbol(get_symbol_offset(pos), namebuf, KSYM_NAME_LEN); if (modname) *modname = NULL; return namebuf; } /* See if it's in a module. */ return module_address_lookup(addr, symbolsize, offset, modname, namebuf); } int lookup_symbol_name(unsigned long addr, char *symname) { symname[0] = '\0'; symname[KSYM_NAME_LEN - 1] = '\0'; if (is_ksym_addr(addr)) { unsigned long pos; pos = get_symbol_pos(addr, NULL, NULL); /* Grab name */ kallsyms_expand_symbol(get_symbol_offset(pos), symname, KSYM_NAME_LEN); return 0; } /* See if it's in a module. */ return lookup_module_symbol_name(addr, symname); } int lookup_symbol_attrs(unsigned long addr, unsigned long *size, unsigned long *offset, char *modname, char *name) { name[0] = '\0'; name[KSYM_NAME_LEN - 1] = '\0'; if (is_ksym_addr(addr)) { unsigned long pos; pos = get_symbol_pos(addr, size, offset); /* Grab name */ kallsyms_expand_symbol(get_symbol_offset(pos), name, KSYM_NAME_LEN); modname[0] = '\0'; return 0; } /* See if it's in a module. */ return lookup_module_symbol_attrs(addr, size, offset, modname, name); } /* Look up a kernel symbol and return it in a text buffer. */ static int __sprint_symbol(char *buffer, unsigned long address, int symbol_offset, int add_offset) { char *modname; const char *name; unsigned long offset, size; int len; address += symbol_offset; name = kallsyms_lookup(address, &size, &offset, &modname, buffer); if (!name) return sprintf(buffer, "0x%lx", address); if (name != buffer) strcpy(buffer, name); len = strlen(buffer); offset -= symbol_offset; if (add_offset) len += sprintf(buffer + len, "+%#lx/%#lx", offset, size); if (modname) len += sprintf(buffer + len, " [%s]", modname); return len; } /** * sprint_symbol - Look up a kernel symbol and return it in a text buffer * @buffer: buffer to be stored * @address: address to lookup * * This function looks up a kernel symbol with @address and stores its name, * offset, size and module name to @buffer if possible. If no symbol was found, * just saves its @address as is. * * This function returns the number of bytes stored in @buffer. */ int sprint_symbol(char *buffer, unsigned long address) { return __sprint_symbol(buffer, address, 0, 1); } EXPORT_SYMBOL_GPL(sprint_symbol); /** * sprint_symbol_no_offset - Look up a kernel symbol and return it in a text buffer * @buffer: buffer to be stored * @address: address to lookup * * This function looks up a kernel symbol with @address and stores its name * and module name to @buffer if possible. If no symbol was found, just saves * its @address as is. * * This function returns the number of bytes stored in @buffer. */ int sprint_symbol_no_offset(char *buffer, unsigned long address) { return __sprint_symbol(buffer, address, 0, 0); } EXPORT_SYMBOL_GPL(sprint_symbol_no_offset); /** * sprint_backtrace - Look up a backtrace symbol and return it in a text buffer * @buffer: buffer to be stored * @address: address to lookup * * This function is for stack backtrace and does the same thing as * sprint_symbol() but with modified/decreased @address. If there is a * tail-call to the function marked "noreturn", gcc optimized out code after * the call so that the stack-saved return address could point outside of the * caller. This function ensures that kallsyms will find the original caller * by decreasing @address. * * This function returns the number of bytes stored in @buffer. */ int sprint_backtrace(char *buffer, unsigned long address) { return __sprint_symbol(buffer, address, -1, 1); } /* Look up a kernel symbol and print it to the kernel messages. */ void __print_symbol(const char *fmt, unsigned long address) { char buffer[KSYM_SYMBOL_LEN]; sprint_symbol(buffer, address); printk(fmt, buffer); } EXPORT_SYMBOL(__print_symbol); /* To avoid using get_symbol_offset for every symbol, we carry prefix along. */ struct kallsym_iter { loff_t pos; unsigned long value; unsigned int nameoff; /* If iterating in core kernel symbols. */ char type; char name[KSYM_NAME_LEN]; char module_name[MODULE_NAME_LEN]; int exported; }; static int get_ksymbol_mod(struct kallsym_iter *iter) { if (module_get_kallsym(iter->pos - kallsyms_num_syms, &iter->value, &iter->type, iter->name, iter->module_name, &iter->exported) < 0) return 0; return 1; } /* Returns space to next name. */ static unsigned long get_ksymbol_core(struct kallsym_iter *iter) { unsigned off = iter->nameoff; iter->module_name[0] = '\0'; iter->value = kallsyms_addresses[iter->pos]; iter->type = kallsyms_get_symbol_type(off); off = kallsyms_expand_symbol(off, iter->name, ARRAY_SIZE(iter->name)); return off - iter->nameoff; } static void reset_iter(struct kallsym_iter *iter, loff_t new_pos) { iter->name[0] = '\0'; iter->nameoff = get_symbol_offset(new_pos); iter->pos = new_pos; } /* Returns false if pos at or past end of file. */ static int update_iter(struct kallsym_iter *iter, loff_t pos) { /* Module symbols can be accessed randomly. */ if (pos >= kallsyms_num_syms) { iter->pos = pos; return get_ksymbol_mod(iter); } /* If we're not on the desired position, reset to new position. */ if (pos != iter->pos) reset_iter(iter, pos); iter->nameoff += get_ksymbol_core(iter); iter->pos++; return 1; } static void *s_next(struct seq_file *m, void *p, loff_t *pos) { (*pos)++; if (!update_iter(m->private, *pos)) return NULL; return p; } static void *s_start(struct seq_file *m, loff_t *pos) { if (!update_iter(m->private, *pos)) return NULL; return m->private; } static void s_stop(struct seq_file *m, void *p) { } static int s_show(struct seq_file *m, void *p) { struct kallsym_iter *iter = m->private; /* Some debugging symbols have no name. Ignore them. */ if (!iter->name[0]) return 0; if (iter->module_name[0]) { char type; /* * Label it "global" if it is exported, * "local" if not exported. */ type = iter->exported ? toupper(iter->type) : tolower(iter->type); seq_printf(m, "%pK %c %s\t[%s]\n", (void *)iter->value, type, iter->name, iter->module_name); } else seq_printf(m, "%pK %c %s\n", (void *)iter->value, iter->type, iter->name); return 0; } static const struct seq_operations kallsyms_op = { .start = s_start, .next = s_next, .stop = s_stop, .show = s_show }; static int kallsyms_open(struct inode *inode, struct file *file) { /* * We keep iterator in m->private, since normal case is to * s_start from where we left off, so we avoid doing * using get_symbol_offset for every symbol. */ struct kallsym_iter *iter; int ret; iter = kmalloc(sizeof(*iter), GFP_KERNEL); if (!iter) return -ENOMEM; reset_iter(iter, 0); ret = seq_open(file, &kallsyms_op); if (ret == 0) ((struct seq_file *)file->private_data)->private = iter; else kfree(iter); return ret; } #ifdef CONFIG_KGDB_KDB const char *kdb_walk_kallsyms(loff_t *pos) { static struct kallsym_iter kdb_walk_kallsyms_iter; if (*pos == 0) { memset(&kdb_walk_kallsyms_iter, 0, sizeof(kdb_walk_kallsyms_iter)); reset_iter(&kdb_walk_kallsyms_iter, 0); } while (1) { if (!update_iter(&kdb_walk_kallsyms_iter, *pos)) return NULL; ++*pos; /* Some debugging symbols have no name. Ignore them. */ if (kdb_walk_kallsyms_iter.name[0]) return kdb_walk_kallsyms_iter.name; } } #endif /* CONFIG_KGDB_KDB */ static const struct file_operations kallsyms_operations = { .open = kallsyms_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release_private, }; static int __init kallsyms_init(void) { proc_create("kallsyms", 0444, NULL, &kallsyms_operations); return 0; } device_initcall(kallsyms_init);
gpl-2.0
holyangel/DesireEye
drivers/scsi/hosts.c
2815
14289
/* * hosts.c Copyright (C) 1992 Drew Eckhardt * Copyright (C) 1993, 1994, 1995 Eric Youngdale * Copyright (C) 2002-2003 Christoph Hellwig * * mid to lowlevel SCSI driver interface * Initial versions: Drew Eckhardt * Subsequent revisions: Eric Youngdale * * <drew@colorado.edu> * * Jiffies wrap fixes (host->resetting), 3 Dec 1998 Andrea Arcangeli * Added QLOGIC QLA1280 SCSI controller kernel host support. * August 4, 1999 Fred Lewis, Intel DuPont * * Updated to reflect the new initialization scheme for the higher * level of scsi drivers (sd/sr/st) * September 17, 2000 Torben Mathiasen <tmm@image.dk> * * Restructured scsi_host lists and associated functions. * September 04, 2002 Mike Anderson (andmike@us.ibm.com) */ #include <linux/module.h> #include <linux/blkdev.h> #include <linux/kernel.h> #include <linux/slab.h> #include <linux/kthread.h> #include <linux/string.h> #include <linux/mm.h> #include <linux/init.h> #include <linux/completion.h> #include <linux/transport_class.h> #include <linux/platform_device.h> #include <linux/pm_runtime.h> #include <scsi/scsi_device.h> #include <scsi/scsi_host.h> #include <scsi/scsi_transport.h> #include "scsi_priv.h" #include "scsi_logging.h" static atomic_t scsi_host_next_hn; /* host_no for next new host */ static void scsi_host_cls_release(struct device *dev) { put_device(&class_to_shost(dev)->shost_gendev); } static struct class shost_class = { .name = "scsi_host", .dev_release = scsi_host_cls_release, }; /** * scsi_host_set_state - Take the given host through the host state model. * @shost: scsi host to change the state of. * @state: state to change to. * * Returns zero if unsuccessful or an error if the requested * transition is illegal. **/ int scsi_host_set_state(struct Scsi_Host *shost, enum scsi_host_state state) { enum scsi_host_state oldstate = shost->shost_state; if (state == oldstate) return 0; switch (state) { case SHOST_CREATED: /* There are no legal states that come back to * created. This is the manually initialised start * state */ goto illegal; case SHOST_RUNNING: switch (oldstate) { case SHOST_CREATED: case SHOST_RECOVERY: break; default: goto illegal; } break; case SHOST_RECOVERY: switch (oldstate) { case SHOST_RUNNING: break; default: goto illegal; } break; case SHOST_CANCEL: switch (oldstate) { case SHOST_CREATED: case SHOST_RUNNING: case SHOST_CANCEL_RECOVERY: break; default: goto illegal; } break; case SHOST_DEL: switch (oldstate) { case SHOST_CANCEL: case SHOST_DEL_RECOVERY: break; default: goto illegal; } break; case SHOST_CANCEL_RECOVERY: switch (oldstate) { case SHOST_CANCEL: case SHOST_RECOVERY: break; default: goto illegal; } break; case SHOST_DEL_RECOVERY: switch (oldstate) { case SHOST_CANCEL_RECOVERY: break; default: goto illegal; } break; } shost->shost_state = state; return 0; illegal: SCSI_LOG_ERROR_RECOVERY(1, shost_printk(KERN_ERR, shost, "Illegal host state transition" "%s->%s\n", scsi_host_state_name(oldstate), scsi_host_state_name(state))); return -EINVAL; } EXPORT_SYMBOL(scsi_host_set_state); /** * scsi_remove_host - remove a scsi host * @shost: a pointer to a scsi host to remove **/ void scsi_remove_host(struct Scsi_Host *shost) { unsigned long flags; mutex_lock(&shost->scan_mutex); spin_lock_irqsave(shost->host_lock, flags); if (scsi_host_set_state(shost, SHOST_CANCEL)) if (scsi_host_set_state(shost, SHOST_CANCEL_RECOVERY)) { spin_unlock_irqrestore(shost->host_lock, flags); mutex_unlock(&shost->scan_mutex); return; } spin_unlock_irqrestore(shost->host_lock, flags); scsi_autopm_get_host(shost); scsi_forget_host(shost); mutex_unlock(&shost->scan_mutex); scsi_proc_host_rm(shost); spin_lock_irqsave(shost->host_lock, flags); if (scsi_host_set_state(shost, SHOST_DEL)) BUG_ON(scsi_host_set_state(shost, SHOST_DEL_RECOVERY)); spin_unlock_irqrestore(shost->host_lock, flags); transport_unregister_device(&shost->shost_gendev); device_unregister(&shost->shost_dev); device_del(&shost->shost_gendev); } EXPORT_SYMBOL(scsi_remove_host); /** * scsi_add_host_with_dma - add a scsi host with dma device * @shost: scsi host pointer to add * @dev: a struct device of type scsi class * @dma_dev: dma device for the host * * Note: You rarely need to worry about this unless you're in a * virtualised host environments, so use the simpler scsi_add_host() * function instead. * * Return value: * 0 on success / != 0 for error **/ int scsi_add_host_with_dma(struct Scsi_Host *shost, struct device *dev, struct device *dma_dev) { struct scsi_host_template *sht = shost->hostt; int error = -EINVAL; printk(KERN_INFO "scsi%d : %s\n", shost->host_no, sht->info ? sht->info(shost) : sht->name); if (!shost->can_queue) { printk(KERN_ERR "%s: can_queue = 0 no longer supported\n", sht->name); goto fail; } error = scsi_setup_command_freelist(shost); if (error) goto fail; if (!shost->shost_gendev.parent) shost->shost_gendev.parent = dev ? dev : &platform_bus; if (!dma_dev) dma_dev = shost->shost_gendev.parent; shost->dma_dev = dma_dev; error = device_add(&shost->shost_gendev); if (error) goto out; pm_runtime_set_active(&shost->shost_gendev); pm_runtime_enable(&shost->shost_gendev); device_enable_async_suspend(&shost->shost_gendev); scsi_host_set_state(shost, SHOST_RUNNING); get_device(shost->shost_gendev.parent); device_enable_async_suspend(&shost->shost_dev); error = device_add(&shost->shost_dev); if (error) goto out_del_gendev; get_device(&shost->shost_gendev); if (shost->transportt->host_size) { shost->shost_data = kzalloc(shost->transportt->host_size, GFP_KERNEL); if (shost->shost_data == NULL) { error = -ENOMEM; goto out_del_dev; } } if (shost->transportt->create_work_queue) { snprintf(shost->work_q_name, sizeof(shost->work_q_name), "scsi_wq_%d", shost->host_no); shost->work_q = create_singlethread_workqueue( shost->work_q_name); if (!shost->work_q) { error = -EINVAL; goto out_free_shost_data; } } error = scsi_sysfs_add_host(shost); if (error) goto out_destroy_host; scsi_proc_host_add(shost); return error; out_destroy_host: if (shost->work_q) destroy_workqueue(shost->work_q); out_free_shost_data: kfree(shost->shost_data); out_del_dev: device_del(&shost->shost_dev); out_del_gendev: device_del(&shost->shost_gendev); out: scsi_destroy_command_freelist(shost); fail: return error; } EXPORT_SYMBOL(scsi_add_host_with_dma); static void scsi_host_dev_release(struct device *dev) { struct Scsi_Host *shost = dev_to_shost(dev); struct device *parent = dev->parent; struct request_queue *q; scsi_proc_hostdir_rm(shost->hostt); if (shost->ehandler) kthread_stop(shost->ehandler); if (shost->work_q) destroy_workqueue(shost->work_q); q = shost->uspace_req_q; if (q) { kfree(q->queuedata); q->queuedata = NULL; scsi_free_queue(q); } scsi_destroy_command_freelist(shost); if (shost->bqt) blk_free_tags(shost->bqt); kfree(shost->shost_data); if (parent) put_device(parent); kfree(shost); } static struct device_type scsi_host_type = { .name = "scsi_host", .release = scsi_host_dev_release, }; /** * scsi_host_alloc - register a scsi host adapter instance. * @sht: pointer to scsi host template * @privsize: extra bytes to allocate for driver * * Note: * Allocate a new Scsi_Host and perform basic initialization. * The host is not published to the scsi midlayer until scsi_add_host * is called. * * Return value: * Pointer to a new Scsi_Host **/ struct Scsi_Host *scsi_host_alloc(struct scsi_host_template *sht, int privsize) { struct Scsi_Host *shost; gfp_t gfp_mask = GFP_KERNEL; if (sht->unchecked_isa_dma && privsize) gfp_mask |= __GFP_DMA; shost = kzalloc(sizeof(struct Scsi_Host) + privsize, gfp_mask); if (!shost) return NULL; shost->host_lock = &shost->default_lock; spin_lock_init(shost->host_lock); shost->shost_state = SHOST_CREATED; INIT_LIST_HEAD(&shost->__devices); INIT_LIST_HEAD(&shost->__targets); INIT_LIST_HEAD(&shost->eh_cmd_q); INIT_LIST_HEAD(&shost->starved_list); init_waitqueue_head(&shost->host_wait); mutex_init(&shost->scan_mutex); /* * subtract one because we increment first then return, but we need to * know what the next host number was before increment */ shost->host_no = atomic_inc_return(&scsi_host_next_hn) - 1; shost->dma_channel = 0xff; /* These three are default values which can be overridden */ shost->max_channel = 0; shost->max_id = 8; shost->max_lun = 8; /* Give each shost a default transportt */ shost->transportt = &blank_transport_template; /* * All drivers right now should be able to handle 12 byte * commands. Every so often there are requests for 16 byte * commands, but individual low-level drivers need to certify that * they actually do something sensible with such commands. */ shost->max_cmd_len = 12; shost->hostt = sht; shost->this_id = sht->this_id; shost->can_queue = sht->can_queue; shost->sg_tablesize = sht->sg_tablesize; shost->sg_prot_tablesize = sht->sg_prot_tablesize; shost->cmd_per_lun = sht->cmd_per_lun; shost->unchecked_isa_dma = sht->unchecked_isa_dma; shost->use_clustering = sht->use_clustering; shost->ordered_tag = sht->ordered_tag; if (sht->supported_mode == MODE_UNKNOWN) /* means we didn't set it ... default to INITIATOR */ shost->active_mode = MODE_INITIATOR; else shost->active_mode = sht->supported_mode; if (sht->max_host_blocked) shost->max_host_blocked = sht->max_host_blocked; else shost->max_host_blocked = SCSI_DEFAULT_HOST_BLOCKED; /* * If the driver imposes no hard sector transfer limit, start at * machine infinity initially. */ if (sht->max_sectors) shost->max_sectors = sht->max_sectors; else shost->max_sectors = SCSI_DEFAULT_MAX_SECTORS; /* * assume a 4GB boundary, if not set */ if (sht->dma_boundary) shost->dma_boundary = sht->dma_boundary; else shost->dma_boundary = 0xffffffff; device_initialize(&shost->shost_gendev); dev_set_name(&shost->shost_gendev, "host%d", shost->host_no); shost->shost_gendev.bus = &scsi_bus_type; shost->shost_gendev.type = &scsi_host_type; device_initialize(&shost->shost_dev); shost->shost_dev.parent = &shost->shost_gendev; shost->shost_dev.class = &shost_class; dev_set_name(&shost->shost_dev, "host%d", shost->host_no); shost->shost_dev.groups = scsi_sysfs_shost_attr_groups; shost->ehandler = kthread_run(scsi_error_handler, shost, "scsi_eh_%d", shost->host_no); if (IS_ERR(shost->ehandler)) { printk(KERN_WARNING "scsi%d: error handler thread failed to spawn, error = %ld\n", shost->host_no, PTR_ERR(shost->ehandler)); goto fail_kfree; } scsi_proc_hostdir_add(shost->hostt); return shost; fail_kfree: kfree(shost); return NULL; } EXPORT_SYMBOL(scsi_host_alloc); struct Scsi_Host *scsi_register(struct scsi_host_template *sht, int privsize) { struct Scsi_Host *shost = scsi_host_alloc(sht, privsize); if (!sht->detect) { printk(KERN_WARNING "scsi_register() called on new-style " "template for driver %s\n", sht->name); dump_stack(); } if (shost) list_add_tail(&shost->sht_legacy_list, &sht->legacy_hosts); return shost; } EXPORT_SYMBOL(scsi_register); void scsi_unregister(struct Scsi_Host *shost) { list_del(&shost->sht_legacy_list); scsi_host_put(shost); } EXPORT_SYMBOL(scsi_unregister); static int __scsi_host_match(struct device *dev, void *data) { struct Scsi_Host *p; unsigned short *hostnum = (unsigned short *)data; p = class_to_shost(dev); return p->host_no == *hostnum; } /** * scsi_host_lookup - get a reference to a Scsi_Host by host no * @hostnum: host number to locate * * Return value: * A pointer to located Scsi_Host or NULL. * * The caller must do a scsi_host_put() to drop the reference * that scsi_host_get() took. The put_device() below dropped * the reference from class_find_device(). **/ struct Scsi_Host *scsi_host_lookup(unsigned short hostnum) { struct device *cdev; struct Scsi_Host *shost = NULL; cdev = class_find_device(&shost_class, NULL, &hostnum, __scsi_host_match); if (cdev) { shost = scsi_host_get(class_to_shost(cdev)); put_device(cdev); } return shost; } EXPORT_SYMBOL(scsi_host_lookup); /** * scsi_host_get - inc a Scsi_Host ref count * @shost: Pointer to Scsi_Host to inc. **/ struct Scsi_Host *scsi_host_get(struct Scsi_Host *shost) { if ((shost->shost_state == SHOST_DEL) || !get_device(&shost->shost_gendev)) return NULL; return shost; } EXPORT_SYMBOL(scsi_host_get); /** * scsi_host_put - dec a Scsi_Host ref count * @shost: Pointer to Scsi_Host to dec. **/ void scsi_host_put(struct Scsi_Host *shost) { put_device(&shost->shost_gendev); } EXPORT_SYMBOL(scsi_host_put); int scsi_init_hosts(void) { return class_register(&shost_class); } void scsi_exit_hosts(void) { class_unregister(&shost_class); } int scsi_is_host_device(const struct device *dev) { return dev->type == &scsi_host_type; } EXPORT_SYMBOL(scsi_is_host_device); /** * scsi_queue_work - Queue work to the Scsi_Host workqueue. * @shost: Pointer to Scsi_Host. * @work: Work to queue for execution. * * Return value: * 1 - work queued for execution * 0 - work is already queued * -EINVAL - work queue doesn't exist **/ int scsi_queue_work(struct Scsi_Host *shost, struct work_struct *work) { if (unlikely(!shost->work_q)) { printk(KERN_ERR "ERROR: Scsi host '%s' attempted to queue scsi-work, " "when no workqueue created.\n", shost->hostt->name); dump_stack(); return -EINVAL; } return queue_work(shost->work_q, work); } EXPORT_SYMBOL_GPL(scsi_queue_work); /** * scsi_flush_work - Flush a Scsi_Host's workqueue. * @shost: Pointer to Scsi_Host. **/ void scsi_flush_work(struct Scsi_Host *shost) { if (!shost->work_q) { printk(KERN_ERR "ERROR: Scsi host '%s' attempted to flush scsi-work, " "when no workqueue created.\n", shost->hostt->name); dump_stack(); return; } flush_workqueue(shost->work_q); } EXPORT_SYMBOL_GPL(scsi_flush_work);
gpl-2.0
rukin5197/android_kernel_htc_msm7x30
arch/x86/boot/string.c
3327
2179
/* -*- linux-c -*- ------------------------------------------------------- * * * Copyright (C) 1991, 1992 Linus Torvalds * Copyright 2007 rPath, Inc. - All Rights Reserved * * This file is part of the Linux kernel, and is made available under * the terms of the GNU General Public License version 2. * * ----------------------------------------------------------------------- */ /* * Very basic string functions */ #include "boot.h" int strcmp(const char *str1, const char *str2) { const unsigned char *s1 = (const unsigned char *)str1; const unsigned char *s2 = (const unsigned char *)str2; int delta = 0; while (*s1 || *s2) { delta = *s2 - *s1; if (delta) return delta; s1++; s2++; } return 0; } int strncmp(const char *cs, const char *ct, size_t count) { unsigned char c1, c2; while (count) { c1 = *cs++; c2 = *ct++; if (c1 != c2) return c1 < c2 ? -1 : 1; if (!c1) break; count--; } return 0; } size_t strnlen(const char *s, size_t maxlen) { const char *es = s; while (*es && maxlen) { es++; maxlen--; } return (es - s); } unsigned int atou(const char *s) { unsigned int i = 0; while (isdigit(*s)) i = i * 10 + (*s++ - '0'); return i; } /* Works only for digits and letters, but small and fast */ #define TOLOWER(x) ((x) | 0x20) static unsigned int simple_guess_base(const char *cp) { if (cp[0] == '0') { if (TOLOWER(cp[1]) == 'x' && isxdigit(cp[2])) return 16; else return 8; } else { return 10; } } /** * simple_strtoull - convert a string to an unsigned long long * @cp: The start of the string * @endp: A pointer to the end of the parsed string will be placed here * @base: The number base to use */ unsigned long long simple_strtoull(const char *cp, char **endp, unsigned int base) { unsigned long long result = 0; if (!base) base = simple_guess_base(cp); if (base == 16 && cp[0] == '0' && TOLOWER(cp[1]) == 'x') cp += 2; while (isxdigit(*cp)) { unsigned int value; value = isdigit(*cp) ? *cp - '0' : TOLOWER(*cp) - 'a' + 10; if (value >= base) break; result = result * base + value; cp++; } if (endp) *endp = (char *)cp; return result; }
gpl-2.0
yaymalaga/TaurusPrime_Kernel
fs/fat/file.c
3327
11218
/* * linux/fs/fat/file.c * * Written 1992,1993 by Werner Almesberger * * regular file handling primitives for fat-based filesystems */ #include <linux/capability.h> #include <linux/module.h> #include <linux/compat.h> #include <linux/mount.h> #include <linux/time.h> #include <linux/buffer_head.h> #include <linux/writeback.h> #include <linux/backing-dev.h> #include <linux/blkdev.h> #include <linux/fsnotify.h> #include <linux/security.h> #include "fat.h" static int fat_ioctl_get_attributes(struct inode *inode, u32 __user *user_attr) { u32 attr; mutex_lock(&inode->i_mutex); attr = fat_make_attrs(inode); mutex_unlock(&inode->i_mutex); return put_user(attr, user_attr); } static int fat_ioctl_set_attributes(struct file *file, u32 __user *user_attr) { struct inode *inode = file->f_path.dentry->d_inode; struct msdos_sb_info *sbi = MSDOS_SB(inode->i_sb); int is_dir = S_ISDIR(inode->i_mode); u32 attr, oldattr; struct iattr ia; int err; err = get_user(attr, user_attr); if (err) goto out; mutex_lock(&inode->i_mutex); err = mnt_want_write_file(file); if (err) goto out_unlock_inode; /* * ATTR_VOLUME and ATTR_DIR cannot be changed; this also * prevents the user from turning us into a VFAT * longname entry. Also, we obviously can't set * any of the NTFS attributes in the high 24 bits. */ attr &= 0xff & ~(ATTR_VOLUME | ATTR_DIR); /* Merge in ATTR_VOLUME and ATTR_DIR */ attr |= (MSDOS_I(inode)->i_attrs & ATTR_VOLUME) | (is_dir ? ATTR_DIR : 0); oldattr = fat_make_attrs(inode); /* Equivalent to a chmod() */ ia.ia_valid = ATTR_MODE | ATTR_CTIME; ia.ia_ctime = current_fs_time(inode->i_sb); if (is_dir) ia.ia_mode = fat_make_mode(sbi, attr, S_IRWXUGO); else { ia.ia_mode = fat_make_mode(sbi, attr, S_IRUGO | S_IWUGO | (inode->i_mode & S_IXUGO)); } /* The root directory has no attributes */ if (inode->i_ino == MSDOS_ROOT_INO && attr != ATTR_DIR) { err = -EINVAL; goto out_drop_write; } if (sbi->options.sys_immutable && ((attr | oldattr) & ATTR_SYS) && !capable(CAP_LINUX_IMMUTABLE)) { err = -EPERM; goto out_drop_write; } /* * The security check is questionable... We single * out the RO attribute for checking by the security * module, just because it maps to a file mode. */ err = security_inode_setattr(file->f_path.dentry, &ia); if (err) goto out_drop_write; /* This MUST be done before doing anything irreversible... */ err = fat_setattr(file->f_path.dentry, &ia); if (err) goto out_drop_write; fsnotify_change(file->f_path.dentry, ia.ia_valid); if (sbi->options.sys_immutable) { if (attr & ATTR_SYS) inode->i_flags |= S_IMMUTABLE; else inode->i_flags &= ~S_IMMUTABLE; } fat_save_attrs(inode, attr); mark_inode_dirty(inode); out_drop_write: mnt_drop_write_file(file); out_unlock_inode: mutex_unlock(&inode->i_mutex); out: return err; } long fat_generic_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) { struct inode *inode = filp->f_path.dentry->d_inode; u32 __user *user_attr = (u32 __user *)arg; switch (cmd) { case FAT_IOCTL_GET_ATTRIBUTES: return fat_ioctl_get_attributes(inode, user_attr); case FAT_IOCTL_SET_ATTRIBUTES: return fat_ioctl_set_attributes(filp, user_attr); default: return -ENOTTY; /* Inappropriate ioctl for device */ } } #ifdef CONFIG_COMPAT static long fat_generic_compat_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) { return fat_generic_ioctl(filp, cmd, (unsigned long)compat_ptr(arg)); } #endif static int fat_file_release(struct inode *inode, struct file *filp) { if ((filp->f_mode & FMODE_WRITE) && MSDOS_SB(inode->i_sb)->options.flush) { fat_flush_inodes(inode->i_sb, inode, NULL); congestion_wait(BLK_RW_ASYNC, HZ/10); } return 0; } int fat_file_fsync(struct file *filp, loff_t start, loff_t end, int datasync) { struct inode *inode = filp->f_mapping->host; int res, err; res = generic_file_fsync(filp, start, end, datasync); err = sync_mapping_buffers(MSDOS_SB(inode->i_sb)->fat_inode->i_mapping); return res ? res : err; } const struct file_operations fat_file_operations = { .llseek = generic_file_llseek, .read = do_sync_read, .write = do_sync_write, .aio_read = generic_file_aio_read, .aio_write = generic_file_aio_write, .mmap = generic_file_mmap, .release = fat_file_release, .unlocked_ioctl = fat_generic_ioctl, #ifdef CONFIG_COMPAT .compat_ioctl = fat_generic_compat_ioctl, #endif .fsync = fat_file_fsync, .splice_read = generic_file_splice_read, }; static int fat_cont_expand(struct inode *inode, loff_t size) { struct address_space *mapping = inode->i_mapping; loff_t start = inode->i_size, count = size - inode->i_size; int err; err = generic_cont_expand_simple(inode, size); if (err) goto out; inode->i_ctime = inode->i_mtime = CURRENT_TIME_SEC; mark_inode_dirty(inode); if (IS_SYNC(inode)) { int err2; /* * Opencode syncing since we don't have a file open to use * standard fsync path. */ err = filemap_fdatawrite_range(mapping, start, start + count - 1); err2 = sync_mapping_buffers(mapping); if (!err) err = err2; err2 = write_inode_now(inode, 1); if (!err) err = err2; if (!err) { err = filemap_fdatawait_range(mapping, start, start + count - 1); } } out: return err; } /* Free all clusters after the skip'th cluster. */ static int fat_free(struct inode *inode, int skip) { struct super_block *sb = inode->i_sb; int err, wait, free_start, i_start, i_logstart; if (MSDOS_I(inode)->i_start == 0) return 0; fat_cache_inval_inode(inode); wait = IS_DIRSYNC(inode); i_start = free_start = MSDOS_I(inode)->i_start; i_logstart = MSDOS_I(inode)->i_logstart; /* First, we write the new file size. */ if (!skip) { MSDOS_I(inode)->i_start = 0; MSDOS_I(inode)->i_logstart = 0; } MSDOS_I(inode)->i_attrs |= ATTR_ARCH; inode->i_ctime = inode->i_mtime = CURRENT_TIME_SEC; if (wait) { err = fat_sync_inode(inode); if (err) { MSDOS_I(inode)->i_start = i_start; MSDOS_I(inode)->i_logstart = i_logstart; return err; } } else mark_inode_dirty(inode); /* Write a new EOF, and get the remaining cluster chain for freeing. */ if (skip) { struct fat_entry fatent; int ret, fclus, dclus; ret = fat_get_cluster(inode, skip - 1, &fclus, &dclus); if (ret < 0) return ret; else if (ret == FAT_ENT_EOF) return 0; fatent_init(&fatent); ret = fat_ent_read(inode, &fatent, dclus); if (ret == FAT_ENT_EOF) { fatent_brelse(&fatent); return 0; } else if (ret == FAT_ENT_FREE) { fat_fs_error(sb, "%s: invalid cluster chain (i_pos %lld)", __func__, MSDOS_I(inode)->i_pos); ret = -EIO; } else if (ret > 0) { err = fat_ent_write(inode, &fatent, FAT_ENT_EOF, wait); if (err) ret = err; } fatent_brelse(&fatent); if (ret < 0) return ret; free_start = ret; } inode->i_blocks = skip << (MSDOS_SB(sb)->cluster_bits - 9); /* Freeing the remained cluster chain */ return fat_free_clusters(inode, free_start); } void fat_truncate_blocks(struct inode *inode, loff_t offset) { struct msdos_sb_info *sbi = MSDOS_SB(inode->i_sb); const unsigned int cluster_size = sbi->cluster_size; int nr_clusters; /* * This protects against truncating a file bigger than it was then * trying to write into the hole. */ if (MSDOS_I(inode)->mmu_private > offset) MSDOS_I(inode)->mmu_private = offset; nr_clusters = (offset + (cluster_size - 1)) >> sbi->cluster_bits; fat_free(inode, nr_clusters); fat_flush_inodes(inode->i_sb, inode, NULL); } int fat_getattr(struct vfsmount *mnt, struct dentry *dentry, struct kstat *stat) { struct inode *inode = dentry->d_inode; generic_fillattr(inode, stat); stat->blksize = MSDOS_SB(inode->i_sb)->cluster_size; return 0; } EXPORT_SYMBOL_GPL(fat_getattr); static int fat_sanitize_mode(const struct msdos_sb_info *sbi, struct inode *inode, umode_t *mode_ptr) { umode_t mask, perm; /* * Note, the basic check is already done by a caller of * (attr->ia_mode & ~FAT_VALID_MODE) */ if (S_ISREG(inode->i_mode)) mask = sbi->options.fs_fmask; else mask = sbi->options.fs_dmask; perm = *mode_ptr & ~(S_IFMT | mask); /* * Of the r and x bits, all (subject to umask) must be present. Of the * w bits, either all (subject to umask) or none must be present. * * If fat_mode_can_hold_ro(inode) is false, can't change w bits. */ if ((perm & (S_IRUGO | S_IXUGO)) != (inode->i_mode & (S_IRUGO|S_IXUGO))) return -EPERM; if (fat_mode_can_hold_ro(inode)) { if ((perm & S_IWUGO) && ((perm & S_IWUGO) != (S_IWUGO & ~mask))) return -EPERM; } else { if ((perm & S_IWUGO) != (S_IWUGO & ~mask)) return -EPERM; } *mode_ptr &= S_IFMT | perm; return 0; } static int fat_allow_set_time(struct msdos_sb_info *sbi, struct inode *inode) { umode_t allow_utime = sbi->options.allow_utime; if (current_fsuid() != inode->i_uid) { if (in_group_p(inode->i_gid)) allow_utime >>= 3; if (allow_utime & MAY_WRITE) return 1; } /* use a default check */ return 0; } #define TIMES_SET_FLAGS (ATTR_MTIME_SET | ATTR_ATIME_SET | ATTR_TIMES_SET) /* valid file mode bits */ #define FAT_VALID_MODE (S_IFREG | S_IFDIR | S_IRWXUGO) int fat_setattr(struct dentry *dentry, struct iattr *attr) { struct msdos_sb_info *sbi = MSDOS_SB(dentry->d_sb); struct inode *inode = dentry->d_inode; unsigned int ia_valid; int error; /* Check for setting the inode time. */ ia_valid = attr->ia_valid; if (ia_valid & TIMES_SET_FLAGS) { if (fat_allow_set_time(sbi, inode)) attr->ia_valid &= ~TIMES_SET_FLAGS; } error = inode_change_ok(inode, attr); attr->ia_valid = ia_valid; if (error) { if (sbi->options.quiet) error = 0; goto out; } /* * Expand the file. Since inode_setattr() updates ->i_size * before calling the ->truncate(), but FAT needs to fill the * hole before it. XXX: this is no longer true with new truncate * sequence. */ if (attr->ia_valid & ATTR_SIZE) { inode_dio_wait(inode); if (attr->ia_size > inode->i_size) { error = fat_cont_expand(inode, attr->ia_size); if (error || attr->ia_valid == ATTR_SIZE) goto out; attr->ia_valid &= ~ATTR_SIZE; } } if (((attr->ia_valid & ATTR_UID) && (attr->ia_uid != sbi->options.fs_uid)) || ((attr->ia_valid & ATTR_GID) && (attr->ia_gid != sbi->options.fs_gid)) || ((attr->ia_valid & ATTR_MODE) && (attr->ia_mode & ~FAT_VALID_MODE))) error = -EPERM; if (error) { if (sbi->options.quiet) error = 0; goto out; } /* * We don't return -EPERM here. Yes, strange, but this is too * old behavior. */ if (attr->ia_valid & ATTR_MODE) { if (fat_sanitize_mode(sbi, inode, &attr->ia_mode) < 0) attr->ia_valid &= ~ATTR_MODE; } if (attr->ia_valid & ATTR_SIZE) { down_write(&MSDOS_I(inode)->truncate_lock); truncate_setsize(inode, attr->ia_size); fat_truncate_blocks(inode, attr->ia_size); up_write(&MSDOS_I(inode)->truncate_lock); } setattr_copy(inode, attr); mark_inode_dirty(inode); out: return error; } EXPORT_SYMBOL_GPL(fat_setattr); const struct inode_operations fat_file_inode_operations = { .setattr = fat_setattr, .getattr = fat_getattr, };
gpl-2.0
vyatta/linux-vyatta
arch/um/kernel/ksyms.c
3583
1159
/* * Copyright (C) 2001 - 2007 Jeff Dike (jdike@{addtoit,linux.intel}.com) * Licensed under the GPL */ #include <linux/module.h> #include <os.h> EXPORT_SYMBOL(set_signals); EXPORT_SYMBOL(get_signals); EXPORT_SYMBOL(os_stat_fd); EXPORT_SYMBOL(os_stat_file); EXPORT_SYMBOL(os_access); EXPORT_SYMBOL(os_set_exec_close); EXPORT_SYMBOL(os_getpid); EXPORT_SYMBOL(os_open_file); EXPORT_SYMBOL(os_read_file); EXPORT_SYMBOL(os_write_file); EXPORT_SYMBOL(os_seek_file); EXPORT_SYMBOL(os_lock_file); EXPORT_SYMBOL(os_ioctl_generic); EXPORT_SYMBOL(os_pipe); EXPORT_SYMBOL(os_file_type); EXPORT_SYMBOL(os_file_mode); EXPORT_SYMBOL(os_file_size); EXPORT_SYMBOL(os_flush_stdout); EXPORT_SYMBOL(os_close_file); EXPORT_SYMBOL(os_set_fd_async); EXPORT_SYMBOL(os_set_fd_block); EXPORT_SYMBOL(helper_wait); EXPORT_SYMBOL(os_shutdown_socket); EXPORT_SYMBOL(os_create_unix_socket); EXPORT_SYMBOL(os_connect_socket); EXPORT_SYMBOL(os_accept_connection); EXPORT_SYMBOL(os_rcv_fd); EXPORT_SYMBOL(run_helper); EXPORT_SYMBOL(os_major); EXPORT_SYMBOL(os_minor); EXPORT_SYMBOL(os_makedev); EXPORT_SYMBOL(add_sigio_fd); EXPORT_SYMBOL(ignore_sigio_fd); EXPORT_SYMBOL(sigio_broken);
gpl-2.0
javilonas/Enki-GT-I9300
sound/pci/rme9652/rme9652.c
3583
76074
/* * ALSA driver for RME Digi9652 audio interfaces * * Copyright (c) 1999 IEM - Winfried Ritsch * Copyright (c) 1999-2001 Paul 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ #include <linux/delay.h> #include <linux/init.h> #include <linux/interrupt.h> #include <linux/pci.h> #include <linux/moduleparam.h> #include <sound/core.h> #include <sound/control.h> #include <sound/pcm.h> #include <sound/info.h> #include <sound/asoundef.h> #include <sound/initval.h> #include <asm/current.h> #include <asm/io.h> static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX; /* Index 0-MAX */ static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR; /* ID for this card */ static int enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_PNP; /* Enable this card */ static int precise_ptr[SNDRV_CARDS]; /* Enable precise pointer */ module_param_array(index, int, NULL, 0444); MODULE_PARM_DESC(index, "Index value for RME Digi9652 (Hammerfall) soundcard."); module_param_array(id, charp, NULL, 0444); MODULE_PARM_DESC(id, "ID string for RME Digi9652 (Hammerfall) soundcard."); module_param_array(enable, bool, NULL, 0444); MODULE_PARM_DESC(enable, "Enable/disable specific RME96{52,36} soundcards."); module_param_array(precise_ptr, bool, NULL, 0444); MODULE_PARM_DESC(precise_ptr, "Enable precise pointer (doesn't work reliably)."); MODULE_AUTHOR("Paul Davis <pbd@op.net>, Winfried Ritsch"); MODULE_DESCRIPTION("RME Digi9652/Digi9636"); MODULE_LICENSE("GPL"); MODULE_SUPPORTED_DEVICE("{{RME,Hammerfall}," "{RME,Hammerfall-Light}}"); /* The Hammerfall has two sets of 24 ADAT + 2 S/PDIF channels, one for capture, one for playback. Both the ADAT and S/PDIF channels appear to the host CPU in the same block of memory. There is no functional difference between them in terms of access. The Hammerfall Light is identical to the Hammerfall, except that it has 2 sets 18 channels (16 ADAT + 2 S/PDIF) for capture and playback. */ #define RME9652_NCHANNELS 26 #define RME9636_NCHANNELS 18 /* Preferred sync source choices - used by "sync_pref" control switch */ #define RME9652_SYNC_FROM_SPDIF 0 #define RME9652_SYNC_FROM_ADAT1 1 #define RME9652_SYNC_FROM_ADAT2 2 #define RME9652_SYNC_FROM_ADAT3 3 /* Possible sources of S/PDIF input */ #define RME9652_SPDIFIN_OPTICAL 0 /* optical (ADAT1) */ #define RME9652_SPDIFIN_COAXIAL 1 /* coaxial (RCA) */ #define RME9652_SPDIFIN_INTERN 2 /* internal (CDROM) */ /* ------------- Status-Register bits --------------------- */ #define RME9652_IRQ (1<<0) /* IRQ is High if not reset by irq_clear */ #define RME9652_lock_2 (1<<1) /* ADAT 3-PLL: 1=locked, 0=unlocked */ #define RME9652_lock_1 (1<<2) /* ADAT 2-PLL: 1=locked, 0=unlocked */ #define RME9652_lock_0 (1<<3) /* ADAT 1-PLL: 1=locked, 0=unlocked */ #define RME9652_fs48 (1<<4) /* sample rate is 0=44.1/88.2,1=48/96 Khz */ #define RME9652_wsel_rd (1<<5) /* if Word-Clock is used and valid then 1 */ /* bits 6-15 encode h/w buffer pointer position */ #define RME9652_sync_2 (1<<16) /* if ADAT-IN 3 in sync to system clock */ #define RME9652_sync_1 (1<<17) /* if ADAT-IN 2 in sync to system clock */ #define RME9652_sync_0 (1<<18) /* if ADAT-IN 1 in sync to system clock */ #define RME9652_DS_rd (1<<19) /* 1=Double Speed Mode, 0=Normal Speed */ #define RME9652_tc_busy (1<<20) /* 1=time-code copy in progress (960ms) */ #define RME9652_tc_out (1<<21) /* time-code out bit */ #define RME9652_F_0 (1<<22) /* 000=64kHz, 100=88.2kHz, 011=96kHz */ #define RME9652_F_1 (1<<23) /* 111=32kHz, 110=44.1kHz, 101=48kHz, */ #define RME9652_F_2 (1<<24) /* external Crystal Chip if ERF=1 */ #define RME9652_ERF (1<<25) /* Error-Flag of SDPIF Receiver (1=No Lock) */ #define RME9652_buffer_id (1<<26) /* toggles by each interrupt on rec/play */ #define RME9652_tc_valid (1<<27) /* 1 = a signal is detected on time-code input */ #define RME9652_SPDIF_READ (1<<28) /* byte available from Rev 1.5+ S/PDIF interface */ #define RME9652_sync (RME9652_sync_0|RME9652_sync_1|RME9652_sync_2) #define RME9652_lock (RME9652_lock_0|RME9652_lock_1|RME9652_lock_2) #define RME9652_F (RME9652_F_0|RME9652_F_1|RME9652_F_2) #define rme9652_decode_spdif_rate(x) ((x)>>22) /* Bit 6..15 : h/w buffer pointer */ #define RME9652_buf_pos 0x000FFC0 /* Bits 31,30,29 are bits 5,4,3 of h/w pointer position on later Rev G EEPROMS and Rev 1.5 cards or later. */ #define RME9652_REV15_buf_pos(x) ((((x)&0xE0000000)>>26)|((x)&RME9652_buf_pos)) /* amount of io space we remap for register access. i'm not sure we even need this much, but 1K is nice round number :) */ #define RME9652_IO_EXTENT 1024 #define RME9652_init_buffer 0 #define RME9652_play_buffer 32 /* holds ptr to 26x64kBit host RAM */ #define RME9652_rec_buffer 36 /* holds ptr to 26x64kBit host RAM */ #define RME9652_control_register 64 #define RME9652_irq_clear 96 #define RME9652_time_code 100 /* useful if used with alesis adat */ #define RME9652_thru_base 128 /* 132...228 Thru for 26 channels */ /* Read-only registers */ /* Writing to any of the register locations writes to the status register. We'll use the first location as our point of access. */ #define RME9652_status_register 0 /* --------- Control-Register Bits ---------------- */ #define RME9652_start_bit (1<<0) /* start record/play */ /* bits 1-3 encode buffersize/latency */ #define RME9652_Master (1<<4) /* Clock Mode Master=1,Slave/Auto=0 */ #define RME9652_IE (1<<5) /* Interrupt Enable */ #define RME9652_freq (1<<6) /* samplerate 0=44.1/88.2, 1=48/96 kHz */ #define RME9652_freq1 (1<<7) /* if 0, 32kHz, else always 1 */ #define RME9652_DS (1<<8) /* Doule Speed 0=44.1/48, 1=88.2/96 Khz */ #define RME9652_PRO (1<<9) /* S/PDIF out: 0=consumer, 1=professional */ #define RME9652_EMP (1<<10) /* Emphasis 0=None, 1=ON */ #define RME9652_Dolby (1<<11) /* Non-audio bit 1=set, 0=unset */ #define RME9652_opt_out (1<<12) /* Use 1st optical OUT as SPDIF: 1=yes,0=no */ #define RME9652_wsel (1<<13) /* use Wordclock as sync (overwrites master) */ #define RME9652_inp_0 (1<<14) /* SPDIF-IN: 00=optical (ADAT1), */ #define RME9652_inp_1 (1<<15) /* 01=koaxial (Cinch), 10=Internal CDROM */ #define RME9652_SyncPref_ADAT2 (1<<16) #define RME9652_SyncPref_ADAT3 (1<<17) #define RME9652_SPDIF_RESET (1<<18) /* Rev 1.5+: h/w S/PDIF receiver */ #define RME9652_SPDIF_SELECT (1<<19) #define RME9652_SPDIF_CLOCK (1<<20) #define RME9652_SPDIF_WRITE (1<<21) #define RME9652_ADAT1_INTERNAL (1<<22) /* Rev 1.5+: if set, internal CD connector carries ADAT */ /* buffersize = 512Bytes * 2^n, where n is made from Bit2 ... Bit0 */ #define RME9652_latency 0x0e #define rme9652_encode_latency(x) (((x)&0x7)<<1) #define rme9652_decode_latency(x) (((x)>>1)&0x7) #define rme9652_running_double_speed(s) ((s)->control_register & RME9652_DS) #define RME9652_inp (RME9652_inp_0|RME9652_inp_1) #define rme9652_encode_spdif_in(x) (((x)&0x3)<<14) #define rme9652_decode_spdif_in(x) (((x)>>14)&0x3) #define RME9652_SyncPref_Mask (RME9652_SyncPref_ADAT2|RME9652_SyncPref_ADAT3) #define RME9652_SyncPref_ADAT1 0 #define RME9652_SyncPref_SPDIF (RME9652_SyncPref_ADAT2|RME9652_SyncPref_ADAT3) /* the size of a substream (1 mono data stream) */ #define RME9652_CHANNEL_BUFFER_SAMPLES (16*1024) #define RME9652_CHANNEL_BUFFER_BYTES (4*RME9652_CHANNEL_BUFFER_SAMPLES) /* the size of the area we need to allocate for DMA transfers. the size is the same regardless of the number of channels - the 9636 still uses the same memory area. Note that we allocate 1 more channel than is apparently needed because the h/w seems to write 1 byte beyond the end of the last page. Sigh. */ #define RME9652_DMA_AREA_BYTES ((RME9652_NCHANNELS+1) * RME9652_CHANNEL_BUFFER_BYTES) #define RME9652_DMA_AREA_KILOBYTES (RME9652_DMA_AREA_BYTES/1024) struct snd_rme9652 { int dev; spinlock_t lock; int irq; unsigned long port; void __iomem *iobase; int precise_ptr; u32 control_register; /* cached value */ u32 thru_bits; /* thru 1=on, 0=off channel 1=Bit1... channel 26= Bit26 */ u32 creg_spdif; u32 creg_spdif_stream; char *card_name; /* hammerfall or hammerfall light names */ size_t hw_offsetmask; /* &-with status register to get real hw_offset */ size_t prev_hw_offset; /* previous hw offset */ size_t max_jitter; /* maximum jitter in frames for hw pointer */ size_t period_bytes; /* guess what this is */ unsigned char ds_channels; unsigned char ss_channels; /* different for hammerfall/hammerfall-light */ struct snd_dma_buffer playback_dma_buf; struct snd_dma_buffer capture_dma_buf; unsigned char *capture_buffer; /* suitably aligned address */ unsigned char *playback_buffer; /* suitably aligned address */ pid_t capture_pid; pid_t playback_pid; struct snd_pcm_substream *capture_substream; struct snd_pcm_substream *playback_substream; int running; int passthru; /* non-zero if doing pass-thru */ int hw_rev; /* h/w rev * 10 (i.e. 1.5 has hw_rev = 15) */ int last_spdif_sample_rate; /* so that we can catch externally ... */ int last_adat_sample_rate; /* ... induced rate changes */ char *channel_map; struct snd_card *card; struct snd_pcm *pcm; struct pci_dev *pci; struct snd_kcontrol *spdif_ctl; }; /* These tables map the ALSA channels 1..N to the channels that we need to use in order to find the relevant channel buffer. RME refer to this kind of mapping as between "the ADAT channel and the DMA channel." We index it using the logical audio channel, and the value is the DMA channel (i.e. channel buffer number) where the data for that channel can be read/written from/to. */ static char channel_map_9652_ss[26] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25 }; static char channel_map_9636_ss[26] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, /* channels 16 and 17 are S/PDIF */ 24, 25, /* channels 18-25 don't exist */ -1, -1, -1, -1, -1, -1, -1, -1 }; static char channel_map_9652_ds[26] = { /* ADAT channels are remapped */ 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, /* channels 12 and 13 are S/PDIF */ 24, 25, /* others don't exist */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }; static char channel_map_9636_ds[26] = { /* ADAT channels are remapped */ 1, 3, 5, 7, 9, 11, 13, 15, /* channels 8 and 9 are S/PDIF */ 24, 25 /* others don't exist */ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }; static int snd_hammerfall_get_buffer(struct pci_dev *pci, struct snd_dma_buffer *dmab, size_t size) { dmab->dev.type = SNDRV_DMA_TYPE_DEV; dmab->dev.dev = snd_dma_pci_data(pci); if (snd_dma_get_reserved_buf(dmab, snd_dma_pci_buf_id(pci))) { if (dmab->bytes >= size) return 0; } if (snd_dma_alloc_pages(SNDRV_DMA_TYPE_DEV, snd_dma_pci_data(pci), size, dmab) < 0) return -ENOMEM; return 0; } static void snd_hammerfall_free_buffer(struct snd_dma_buffer *dmab, struct pci_dev *pci) { if (dmab->area) { dmab->dev.dev = NULL; /* make it anonymous */ snd_dma_reserve_buf(dmab, snd_dma_pci_buf_id(pci)); } } static DEFINE_PCI_DEVICE_TABLE(snd_rme9652_ids) = { { .vendor = 0x10ee, .device = 0x3fc4, .subvendor = PCI_ANY_ID, .subdevice = PCI_ANY_ID, }, /* RME Digi9652 */ { 0, }, }; MODULE_DEVICE_TABLE(pci, snd_rme9652_ids); static inline void rme9652_write(struct snd_rme9652 *rme9652, int reg, int val) { writel(val, rme9652->iobase + reg); } static inline unsigned int rme9652_read(struct snd_rme9652 *rme9652, int reg) { return readl(rme9652->iobase + reg); } static inline int snd_rme9652_use_is_exclusive(struct snd_rme9652 *rme9652) { unsigned long flags; int ret = 1; spin_lock_irqsave(&rme9652->lock, flags); if ((rme9652->playback_pid != rme9652->capture_pid) && (rme9652->playback_pid >= 0) && (rme9652->capture_pid >= 0)) { ret = 0; } spin_unlock_irqrestore(&rme9652->lock, flags); return ret; } static inline int rme9652_adat_sample_rate(struct snd_rme9652 *rme9652) { if (rme9652_running_double_speed(rme9652)) { return (rme9652_read(rme9652, RME9652_status_register) & RME9652_fs48) ? 96000 : 88200; } else { return (rme9652_read(rme9652, RME9652_status_register) & RME9652_fs48) ? 48000 : 44100; } } static inline void rme9652_compute_period_size(struct snd_rme9652 *rme9652) { unsigned int i; i = rme9652->control_register & RME9652_latency; rme9652->period_bytes = 1 << ((rme9652_decode_latency(i) + 8)); rme9652->hw_offsetmask = (rme9652->period_bytes * 2 - 1) & RME9652_buf_pos; rme9652->max_jitter = 80; } static snd_pcm_uframes_t rme9652_hw_pointer(struct snd_rme9652 *rme9652) { int status; unsigned int offset, frag; snd_pcm_uframes_t period_size = rme9652->period_bytes / 4; snd_pcm_sframes_t delta; status = rme9652_read(rme9652, RME9652_status_register); if (!rme9652->precise_ptr) return (status & RME9652_buffer_id) ? period_size : 0; offset = status & RME9652_buf_pos; /* The hardware may give a backward movement for up to 80 frames Martin Kirst <martin.kirst@freenet.de> knows the details. */ delta = rme9652->prev_hw_offset - offset; delta &= 0xffff; if (delta <= (snd_pcm_sframes_t)rme9652->max_jitter * 4) offset = rme9652->prev_hw_offset; else rme9652->prev_hw_offset = offset; offset &= rme9652->hw_offsetmask; offset /= 4; frag = status & RME9652_buffer_id; if (offset < period_size) { if (offset > rme9652->max_jitter) { if (frag) printk(KERN_ERR "Unexpected hw_pointer position (bufid == 0): status: %x offset: %d\n", status, offset); } else if (!frag) return 0; offset -= rme9652->max_jitter; if ((int)offset < 0) offset += period_size * 2; } else { if (offset > period_size + rme9652->max_jitter) { if (!frag) printk(KERN_ERR "Unexpected hw_pointer position (bufid == 1): status: %x offset: %d\n", status, offset); } else if (frag) return period_size; offset -= rme9652->max_jitter; } return offset; } static inline void rme9652_reset_hw_pointer(struct snd_rme9652 *rme9652) { int i; /* reset the FIFO pointer to zero. We do this by writing to 8 registers, each of which is a 32bit wide register, and set them all to zero. Note that s->iobase is a pointer to int32, not pointer to char. */ for (i = 0; i < 8; i++) { rme9652_write(rme9652, i * 4, 0); udelay(10); } rme9652->prev_hw_offset = 0; } static inline void rme9652_start(struct snd_rme9652 *s) { s->control_register |= (RME9652_IE | RME9652_start_bit); rme9652_write(s, RME9652_control_register, s->control_register); } static inline void rme9652_stop(struct snd_rme9652 *s) { s->control_register &= ~(RME9652_start_bit | RME9652_IE); rme9652_write(s, RME9652_control_register, s->control_register); } static int rme9652_set_interrupt_interval(struct snd_rme9652 *s, unsigned int frames) { int restart = 0; int n; spin_lock_irq(&s->lock); if ((restart = s->running)) { rme9652_stop(s); } frames >>= 7; n = 0; while (frames) { n++; frames >>= 1; } s->control_register &= ~RME9652_latency; s->control_register |= rme9652_encode_latency(n); rme9652_write(s, RME9652_control_register, s->control_register); rme9652_compute_period_size(s); if (restart) rme9652_start(s); spin_unlock_irq(&s->lock); return 0; } static int rme9652_set_rate(struct snd_rme9652 *rme9652, int rate) { int restart; int reject_if_open = 0; int xrate; if (!snd_rme9652_use_is_exclusive (rme9652)) { return -EBUSY; } /* Changing from a "single speed" to a "double speed" rate is not allowed if any substreams are open. This is because such a change causes a shift in the location of the DMA buffers and a reduction in the number of available buffers. Note that a similar but essentially insoluble problem exists for externally-driven rate changes. All we can do is to flag rate changes in the read/write routines. */ spin_lock_irq(&rme9652->lock); xrate = rme9652_adat_sample_rate(rme9652); switch (rate) { case 44100: if (xrate > 48000) { reject_if_open = 1; } rate = 0; break; case 48000: if (xrate > 48000) { reject_if_open = 1; } rate = RME9652_freq; break; case 88200: if (xrate < 48000) { reject_if_open = 1; } rate = RME9652_DS; break; case 96000: if (xrate < 48000) { reject_if_open = 1; } rate = RME9652_DS | RME9652_freq; break; default: spin_unlock_irq(&rme9652->lock); return -EINVAL; } if (reject_if_open && (rme9652->capture_pid >= 0 || rme9652->playback_pid >= 0)) { spin_unlock_irq(&rme9652->lock); return -EBUSY; } if ((restart = rme9652->running)) { rme9652_stop(rme9652); } rme9652->control_register &= ~(RME9652_freq | RME9652_DS); rme9652->control_register |= rate; rme9652_write(rme9652, RME9652_control_register, rme9652->control_register); if (restart) { rme9652_start(rme9652); } if (rate & RME9652_DS) { if (rme9652->ss_channels == RME9652_NCHANNELS) { rme9652->channel_map = channel_map_9652_ds; } else { rme9652->channel_map = channel_map_9636_ds; } } else { if (rme9652->ss_channels == RME9652_NCHANNELS) { rme9652->channel_map = channel_map_9652_ss; } else { rme9652->channel_map = channel_map_9636_ss; } } spin_unlock_irq(&rme9652->lock); return 0; } static void rme9652_set_thru(struct snd_rme9652 *rme9652, int channel, int enable) { int i; rme9652->passthru = 0; if (channel < 0) { /* set thru for all channels */ if (enable) { for (i = 0; i < RME9652_NCHANNELS; i++) { rme9652->thru_bits |= (1 << i); rme9652_write(rme9652, RME9652_thru_base + i * 4, 1); } } else { for (i = 0; i < RME9652_NCHANNELS; i++) { rme9652->thru_bits &= ~(1 << i); rme9652_write(rme9652, RME9652_thru_base + i * 4, 0); } } } else { int mapped_channel; mapped_channel = rme9652->channel_map[channel]; if (enable) { rme9652->thru_bits |= (1 << mapped_channel); } else { rme9652->thru_bits &= ~(1 << mapped_channel); } rme9652_write(rme9652, RME9652_thru_base + mapped_channel * 4, enable ? 1 : 0); } } static int rme9652_set_passthru(struct snd_rme9652 *rme9652, int onoff) { if (onoff) { rme9652_set_thru(rme9652, -1, 1); /* we don't want interrupts, so do a custom version of rme9652_start(). */ rme9652->control_register = RME9652_inp_0 | rme9652_encode_latency(7) | RME9652_start_bit; rme9652_reset_hw_pointer(rme9652); rme9652_write(rme9652, RME9652_control_register, rme9652->control_register); rme9652->passthru = 1; } else { rme9652_set_thru(rme9652, -1, 0); rme9652_stop(rme9652); rme9652->passthru = 0; } return 0; } static void rme9652_spdif_set_bit (struct snd_rme9652 *rme9652, int mask, int onoff) { if (onoff) rme9652->control_register |= mask; else rme9652->control_register &= ~mask; rme9652_write(rme9652, RME9652_control_register, rme9652->control_register); } static void rme9652_spdif_write_byte (struct snd_rme9652 *rme9652, const int val) { long mask; long i; for (i = 0, mask = 0x80; i < 8; i++, mask >>= 1) { if (val & mask) rme9652_spdif_set_bit (rme9652, RME9652_SPDIF_WRITE, 1); else rme9652_spdif_set_bit (rme9652, RME9652_SPDIF_WRITE, 0); rme9652_spdif_set_bit (rme9652, RME9652_SPDIF_CLOCK, 1); rme9652_spdif_set_bit (rme9652, RME9652_SPDIF_CLOCK, 0); } } static int rme9652_spdif_read_byte (struct snd_rme9652 *rme9652) { long mask; long val; long i; val = 0; for (i = 0, mask = 0x80; i < 8; i++, mask >>= 1) { rme9652_spdif_set_bit (rme9652, RME9652_SPDIF_CLOCK, 1); if (rme9652_read (rme9652, RME9652_status_register) & RME9652_SPDIF_READ) val |= mask; rme9652_spdif_set_bit (rme9652, RME9652_SPDIF_CLOCK, 0); } return val; } static void rme9652_write_spdif_codec (struct snd_rme9652 *rme9652, const int address, const int data) { rme9652_spdif_set_bit (rme9652, RME9652_SPDIF_SELECT, 1); rme9652_spdif_write_byte (rme9652, 0x20); rme9652_spdif_write_byte (rme9652, address); rme9652_spdif_write_byte (rme9652, data); rme9652_spdif_set_bit (rme9652, RME9652_SPDIF_SELECT, 0); } static int rme9652_spdif_read_codec (struct snd_rme9652 *rme9652, const int address) { int ret; rme9652_spdif_set_bit (rme9652, RME9652_SPDIF_SELECT, 1); rme9652_spdif_write_byte (rme9652, 0x20); rme9652_spdif_write_byte (rme9652, address); rme9652_spdif_set_bit (rme9652, RME9652_SPDIF_SELECT, 0); rme9652_spdif_set_bit (rme9652, RME9652_SPDIF_SELECT, 1); rme9652_spdif_write_byte (rme9652, 0x21); ret = rme9652_spdif_read_byte (rme9652); rme9652_spdif_set_bit (rme9652, RME9652_SPDIF_SELECT, 0); return ret; } static void rme9652_initialize_spdif_receiver (struct snd_rme9652 *rme9652) { /* XXX what unsets this ? */ rme9652->control_register |= RME9652_SPDIF_RESET; rme9652_write_spdif_codec (rme9652, 4, 0x40); rme9652_write_spdif_codec (rme9652, 17, 0x13); rme9652_write_spdif_codec (rme9652, 6, 0x02); } static inline int rme9652_spdif_sample_rate(struct snd_rme9652 *s) { unsigned int rate_bits; if (rme9652_read(s, RME9652_status_register) & RME9652_ERF) { return -1; /* error condition */ } if (s->hw_rev == 15) { int x, y, ret; x = rme9652_spdif_read_codec (s, 30); if (x != 0) y = 48000 * 64 / x; else y = 0; if (y > 30400 && y < 33600) ret = 32000; else if (y > 41900 && y < 46000) ret = 44100; else if (y > 46000 && y < 50400) ret = 48000; else if (y > 60800 && y < 67200) ret = 64000; else if (y > 83700 && y < 92000) ret = 88200; else if (y > 92000 && y < 100000) ret = 96000; else ret = 0; return ret; } rate_bits = rme9652_read(s, RME9652_status_register) & RME9652_F; switch (rme9652_decode_spdif_rate(rate_bits)) { case 0x7: return 32000; break; case 0x6: return 44100; break; case 0x5: return 48000; break; case 0x4: return 88200; break; case 0x3: return 96000; break; case 0x0: return 64000; break; default: snd_printk(KERN_ERR "%s: unknown S/PDIF input rate (bits = 0x%x)\n", s->card_name, rate_bits); return 0; break; } } /*----------------------------------------------------------------------------- Control Interface ----------------------------------------------------------------------------*/ static u32 snd_rme9652_convert_from_aes(struct snd_aes_iec958 *aes) { u32 val = 0; val |= (aes->status[0] & IEC958_AES0_PROFESSIONAL) ? RME9652_PRO : 0; val |= (aes->status[0] & IEC958_AES0_NONAUDIO) ? RME9652_Dolby : 0; if (val & RME9652_PRO) val |= (aes->status[0] & IEC958_AES0_PRO_EMPHASIS_5015) ? RME9652_EMP : 0; else val |= (aes->status[0] & IEC958_AES0_CON_EMPHASIS_5015) ? RME9652_EMP : 0; return val; } static void snd_rme9652_convert_to_aes(struct snd_aes_iec958 *aes, u32 val) { aes->status[0] = ((val & RME9652_PRO) ? IEC958_AES0_PROFESSIONAL : 0) | ((val & RME9652_Dolby) ? IEC958_AES0_NONAUDIO : 0); if (val & RME9652_PRO) aes->status[0] |= (val & RME9652_EMP) ? IEC958_AES0_PRO_EMPHASIS_5015 : 0; else aes->status[0] |= (val & RME9652_EMP) ? IEC958_AES0_CON_EMPHASIS_5015 : 0; } static int snd_rme9652_control_spdif_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo) { uinfo->type = SNDRV_CTL_ELEM_TYPE_IEC958; uinfo->count = 1; return 0; } static int snd_rme9652_control_spdif_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_rme9652 *rme9652 = snd_kcontrol_chip(kcontrol); snd_rme9652_convert_to_aes(&ucontrol->value.iec958, rme9652->creg_spdif); return 0; } static int snd_rme9652_control_spdif_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_rme9652 *rme9652 = snd_kcontrol_chip(kcontrol); int change; u32 val; val = snd_rme9652_convert_from_aes(&ucontrol->value.iec958); spin_lock_irq(&rme9652->lock); change = val != rme9652->creg_spdif; rme9652->creg_spdif = val; spin_unlock_irq(&rme9652->lock); return change; } static int snd_rme9652_control_spdif_stream_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo) { uinfo->type = SNDRV_CTL_ELEM_TYPE_IEC958; uinfo->count = 1; return 0; } static int snd_rme9652_control_spdif_stream_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_rme9652 *rme9652 = snd_kcontrol_chip(kcontrol); snd_rme9652_convert_to_aes(&ucontrol->value.iec958, rme9652->creg_spdif_stream); return 0; } static int snd_rme9652_control_spdif_stream_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_rme9652 *rme9652 = snd_kcontrol_chip(kcontrol); int change; u32 val; val = snd_rme9652_convert_from_aes(&ucontrol->value.iec958); spin_lock_irq(&rme9652->lock); change = val != rme9652->creg_spdif_stream; rme9652->creg_spdif_stream = val; rme9652->control_register &= ~(RME9652_PRO | RME9652_Dolby | RME9652_EMP); rme9652_write(rme9652, RME9652_control_register, rme9652->control_register |= val); spin_unlock_irq(&rme9652->lock); return change; } static int snd_rme9652_control_spdif_mask_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo) { uinfo->type = SNDRV_CTL_ELEM_TYPE_IEC958; uinfo->count = 1; return 0; } static int snd_rme9652_control_spdif_mask_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { ucontrol->value.iec958.status[0] = kcontrol->private_value; return 0; } #define RME9652_ADAT1_IN(xname, xindex) \ { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = xname, .index = xindex, \ .info = snd_rme9652_info_adat1_in, \ .get = snd_rme9652_get_adat1_in, \ .put = snd_rme9652_put_adat1_in } static unsigned int rme9652_adat1_in(struct snd_rme9652 *rme9652) { if (rme9652->control_register & RME9652_ADAT1_INTERNAL) return 1; return 0; } static int rme9652_set_adat1_input(struct snd_rme9652 *rme9652, int internal) { int restart = 0; if (internal) { rme9652->control_register |= RME9652_ADAT1_INTERNAL; } else { rme9652->control_register &= ~RME9652_ADAT1_INTERNAL; } /* XXX do we actually need to stop the card when we do this ? */ if ((restart = rme9652->running)) { rme9652_stop(rme9652); } rme9652_write(rme9652, RME9652_control_register, rme9652->control_register); if (restart) { rme9652_start(rme9652); } return 0; } static int snd_rme9652_info_adat1_in(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo) { static char *texts[2] = {"ADAT1", "Internal"}; uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED; uinfo->count = 1; uinfo->value.enumerated.items = 2; if (uinfo->value.enumerated.item > 1) uinfo->value.enumerated.item = 1; strcpy(uinfo->value.enumerated.name, texts[uinfo->value.enumerated.item]); return 0; } static int snd_rme9652_get_adat1_in(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_rme9652 *rme9652 = snd_kcontrol_chip(kcontrol); spin_lock_irq(&rme9652->lock); ucontrol->value.enumerated.item[0] = rme9652_adat1_in(rme9652); spin_unlock_irq(&rme9652->lock); return 0; } static int snd_rme9652_put_adat1_in(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_rme9652 *rme9652 = snd_kcontrol_chip(kcontrol); int change; unsigned int val; if (!snd_rme9652_use_is_exclusive(rme9652)) return -EBUSY; val = ucontrol->value.enumerated.item[0] % 2; spin_lock_irq(&rme9652->lock); change = val != rme9652_adat1_in(rme9652); if (change) rme9652_set_adat1_input(rme9652, val); spin_unlock_irq(&rme9652->lock); return change; } #define RME9652_SPDIF_IN(xname, xindex) \ { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = xname, .index = xindex, \ .info = snd_rme9652_info_spdif_in, \ .get = snd_rme9652_get_spdif_in, .put = snd_rme9652_put_spdif_in } static unsigned int rme9652_spdif_in(struct snd_rme9652 *rme9652) { return rme9652_decode_spdif_in(rme9652->control_register & RME9652_inp); } static int rme9652_set_spdif_input(struct snd_rme9652 *rme9652, int in) { int restart = 0; rme9652->control_register &= ~RME9652_inp; rme9652->control_register |= rme9652_encode_spdif_in(in); if ((restart = rme9652->running)) { rme9652_stop(rme9652); } rme9652_write(rme9652, RME9652_control_register, rme9652->control_register); if (restart) { rme9652_start(rme9652); } return 0; } static int snd_rme9652_info_spdif_in(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo) { static char *texts[3] = {"ADAT1", "Coaxial", "Internal"}; uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED; uinfo->count = 1; uinfo->value.enumerated.items = 3; if (uinfo->value.enumerated.item > 2) uinfo->value.enumerated.item = 2; strcpy(uinfo->value.enumerated.name, texts[uinfo->value.enumerated.item]); return 0; } static int snd_rme9652_get_spdif_in(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_rme9652 *rme9652 = snd_kcontrol_chip(kcontrol); spin_lock_irq(&rme9652->lock); ucontrol->value.enumerated.item[0] = rme9652_spdif_in(rme9652); spin_unlock_irq(&rme9652->lock); return 0; } static int snd_rme9652_put_spdif_in(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_rme9652 *rme9652 = snd_kcontrol_chip(kcontrol); int change; unsigned int val; if (!snd_rme9652_use_is_exclusive(rme9652)) return -EBUSY; val = ucontrol->value.enumerated.item[0] % 3; spin_lock_irq(&rme9652->lock); change = val != rme9652_spdif_in(rme9652); if (change) rme9652_set_spdif_input(rme9652, val); spin_unlock_irq(&rme9652->lock); return change; } #define RME9652_SPDIF_OUT(xname, xindex) \ { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = xname, .index = xindex, \ .info = snd_rme9652_info_spdif_out, \ .get = snd_rme9652_get_spdif_out, .put = snd_rme9652_put_spdif_out } static int rme9652_spdif_out(struct snd_rme9652 *rme9652) { return (rme9652->control_register & RME9652_opt_out) ? 1 : 0; } static int rme9652_set_spdif_output(struct snd_rme9652 *rme9652, int out) { int restart = 0; if (out) { rme9652->control_register |= RME9652_opt_out; } else { rme9652->control_register &= ~RME9652_opt_out; } if ((restart = rme9652->running)) { rme9652_stop(rme9652); } rme9652_write(rme9652, RME9652_control_register, rme9652->control_register); if (restart) { rme9652_start(rme9652); } return 0; } #define snd_rme9652_info_spdif_out snd_ctl_boolean_mono_info static int snd_rme9652_get_spdif_out(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_rme9652 *rme9652 = snd_kcontrol_chip(kcontrol); spin_lock_irq(&rme9652->lock); ucontrol->value.integer.value[0] = rme9652_spdif_out(rme9652); spin_unlock_irq(&rme9652->lock); return 0; } static int snd_rme9652_put_spdif_out(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_rme9652 *rme9652 = snd_kcontrol_chip(kcontrol); int change; unsigned int val; if (!snd_rme9652_use_is_exclusive(rme9652)) return -EBUSY; val = ucontrol->value.integer.value[0] & 1; spin_lock_irq(&rme9652->lock); change = (int)val != rme9652_spdif_out(rme9652); rme9652_set_spdif_output(rme9652, val); spin_unlock_irq(&rme9652->lock); return change; } #define RME9652_SYNC_MODE(xname, xindex) \ { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = xname, .index = xindex, \ .info = snd_rme9652_info_sync_mode, \ .get = snd_rme9652_get_sync_mode, .put = snd_rme9652_put_sync_mode } static int rme9652_sync_mode(struct snd_rme9652 *rme9652) { if (rme9652->control_register & RME9652_wsel) { return 2; } else if (rme9652->control_register & RME9652_Master) { return 1; } else { return 0; } } static int rme9652_set_sync_mode(struct snd_rme9652 *rme9652, int mode) { int restart = 0; switch (mode) { case 0: rme9652->control_register &= ~(RME9652_Master | RME9652_wsel); break; case 1: rme9652->control_register = (rme9652->control_register & ~RME9652_wsel) | RME9652_Master; break; case 2: rme9652->control_register |= (RME9652_Master | RME9652_wsel); break; } if ((restart = rme9652->running)) { rme9652_stop(rme9652); } rme9652_write(rme9652, RME9652_control_register, rme9652->control_register); if (restart) { rme9652_start(rme9652); } return 0; } static int snd_rme9652_info_sync_mode(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo) { static char *texts[3] = {"AutoSync", "Master", "Word Clock"}; uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED; uinfo->count = 1; uinfo->value.enumerated.items = 3; if (uinfo->value.enumerated.item > 2) uinfo->value.enumerated.item = 2; strcpy(uinfo->value.enumerated.name, texts[uinfo->value.enumerated.item]); return 0; } static int snd_rme9652_get_sync_mode(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_rme9652 *rme9652 = snd_kcontrol_chip(kcontrol); spin_lock_irq(&rme9652->lock); ucontrol->value.enumerated.item[0] = rme9652_sync_mode(rme9652); spin_unlock_irq(&rme9652->lock); return 0; } static int snd_rme9652_put_sync_mode(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_rme9652 *rme9652 = snd_kcontrol_chip(kcontrol); int change; unsigned int val; val = ucontrol->value.enumerated.item[0] % 3; spin_lock_irq(&rme9652->lock); change = (int)val != rme9652_sync_mode(rme9652); rme9652_set_sync_mode(rme9652, val); spin_unlock_irq(&rme9652->lock); return change; } #define RME9652_SYNC_PREF(xname, xindex) \ { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = xname, .index = xindex, \ .info = snd_rme9652_info_sync_pref, \ .get = snd_rme9652_get_sync_pref, .put = snd_rme9652_put_sync_pref } static int rme9652_sync_pref(struct snd_rme9652 *rme9652) { switch (rme9652->control_register & RME9652_SyncPref_Mask) { case RME9652_SyncPref_ADAT1: return RME9652_SYNC_FROM_ADAT1; case RME9652_SyncPref_ADAT2: return RME9652_SYNC_FROM_ADAT2; case RME9652_SyncPref_ADAT3: return RME9652_SYNC_FROM_ADAT3; case RME9652_SyncPref_SPDIF: return RME9652_SYNC_FROM_SPDIF; } /* Not reachable */ return 0; } static int rme9652_set_sync_pref(struct snd_rme9652 *rme9652, int pref) { int restart; rme9652->control_register &= ~RME9652_SyncPref_Mask; switch (pref) { case RME9652_SYNC_FROM_ADAT1: rme9652->control_register |= RME9652_SyncPref_ADAT1; break; case RME9652_SYNC_FROM_ADAT2: rme9652->control_register |= RME9652_SyncPref_ADAT2; break; case RME9652_SYNC_FROM_ADAT3: rme9652->control_register |= RME9652_SyncPref_ADAT3; break; case RME9652_SYNC_FROM_SPDIF: rme9652->control_register |= RME9652_SyncPref_SPDIF; break; } if ((restart = rme9652->running)) { rme9652_stop(rme9652); } rme9652_write(rme9652, RME9652_control_register, rme9652->control_register); if (restart) { rme9652_start(rme9652); } return 0; } static int snd_rme9652_info_sync_pref(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo) { static char *texts[4] = {"IEC958 In", "ADAT1 In", "ADAT2 In", "ADAT3 In"}; struct snd_rme9652 *rme9652 = snd_kcontrol_chip(kcontrol); uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED; uinfo->count = 1; uinfo->value.enumerated.items = rme9652->ss_channels == RME9652_NCHANNELS ? 4 : 3; if (uinfo->value.enumerated.item >= uinfo->value.enumerated.items) uinfo->value.enumerated.item = uinfo->value.enumerated.items - 1; strcpy(uinfo->value.enumerated.name, texts[uinfo->value.enumerated.item]); return 0; } static int snd_rme9652_get_sync_pref(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_rme9652 *rme9652 = snd_kcontrol_chip(kcontrol); spin_lock_irq(&rme9652->lock); ucontrol->value.enumerated.item[0] = rme9652_sync_pref(rme9652); spin_unlock_irq(&rme9652->lock); return 0; } static int snd_rme9652_put_sync_pref(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_rme9652 *rme9652 = snd_kcontrol_chip(kcontrol); int change, max; unsigned int val; if (!snd_rme9652_use_is_exclusive(rme9652)) return -EBUSY; max = rme9652->ss_channels == RME9652_NCHANNELS ? 4 : 3; val = ucontrol->value.enumerated.item[0] % max; spin_lock_irq(&rme9652->lock); change = (int)val != rme9652_sync_pref(rme9652); rme9652_set_sync_pref(rme9652, val); spin_unlock_irq(&rme9652->lock); return change; } static int snd_rme9652_info_thru(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo) { struct snd_rme9652 *rme9652 = snd_kcontrol_chip(kcontrol); uinfo->type = SNDRV_CTL_ELEM_TYPE_BOOLEAN; uinfo->count = rme9652->ss_channels; uinfo->value.integer.min = 0; uinfo->value.integer.max = 1; return 0; } static int snd_rme9652_get_thru(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_rme9652 *rme9652 = snd_kcontrol_chip(kcontrol); unsigned int k; u32 thru_bits = rme9652->thru_bits; for (k = 0; k < rme9652->ss_channels; ++k) { ucontrol->value.integer.value[k] = !!(thru_bits & (1 << k)); } return 0; } static int snd_rme9652_put_thru(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_rme9652 *rme9652 = snd_kcontrol_chip(kcontrol); int change; unsigned int chn; u32 thru_bits = 0; if (!snd_rme9652_use_is_exclusive(rme9652)) return -EBUSY; for (chn = 0; chn < rme9652->ss_channels; ++chn) { if (ucontrol->value.integer.value[chn]) thru_bits |= 1 << chn; } spin_lock_irq(&rme9652->lock); change = thru_bits ^ rme9652->thru_bits; if (change) { for (chn = 0; chn < rme9652->ss_channels; ++chn) { if (!(change & (1 << chn))) continue; rme9652_set_thru(rme9652,chn,thru_bits&(1<<chn)); } } spin_unlock_irq(&rme9652->lock); return !!change; } #define RME9652_PASSTHRU(xname, xindex) \ { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = xname, .index = xindex, \ .info = snd_rme9652_info_passthru, \ .put = snd_rme9652_put_passthru, \ .get = snd_rme9652_get_passthru } #define snd_rme9652_info_passthru snd_ctl_boolean_mono_info static int snd_rme9652_get_passthru(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_rme9652 *rme9652 = snd_kcontrol_chip(kcontrol); spin_lock_irq(&rme9652->lock); ucontrol->value.integer.value[0] = rme9652->passthru; spin_unlock_irq(&rme9652->lock); return 0; } static int snd_rme9652_put_passthru(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_rme9652 *rme9652 = snd_kcontrol_chip(kcontrol); int change; unsigned int val; int err = 0; if (!snd_rme9652_use_is_exclusive(rme9652)) return -EBUSY; val = ucontrol->value.integer.value[0] & 1; spin_lock_irq(&rme9652->lock); change = (ucontrol->value.integer.value[0] != rme9652->passthru); if (change) err = rme9652_set_passthru(rme9652, val); spin_unlock_irq(&rme9652->lock); return err ? err : change; } /* Read-only switches */ #define RME9652_SPDIF_RATE(xname, xindex) \ { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = xname, .index = xindex, \ .access = SNDRV_CTL_ELEM_ACCESS_READ | SNDRV_CTL_ELEM_ACCESS_VOLATILE, \ .info = snd_rme9652_info_spdif_rate, \ .get = snd_rme9652_get_spdif_rate } static int snd_rme9652_info_spdif_rate(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo) { uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER; uinfo->count = 1; uinfo->value.integer.min = 0; uinfo->value.integer.max = 96000; return 0; } static int snd_rme9652_get_spdif_rate(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_rme9652 *rme9652 = snd_kcontrol_chip(kcontrol); spin_lock_irq(&rme9652->lock); ucontrol->value.integer.value[0] = rme9652_spdif_sample_rate(rme9652); spin_unlock_irq(&rme9652->lock); return 0; } #define RME9652_ADAT_SYNC(xname, xindex, xidx) \ { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = xname, .index = xindex, \ .access = SNDRV_CTL_ELEM_ACCESS_READ | SNDRV_CTL_ELEM_ACCESS_VOLATILE, \ .info = snd_rme9652_info_adat_sync, \ .get = snd_rme9652_get_adat_sync, .private_value = xidx } static int snd_rme9652_info_adat_sync(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo) { static char *texts[4] = {"No Lock", "Lock", "No Lock Sync", "Lock Sync"}; uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED; uinfo->count = 1; uinfo->value.enumerated.items = 4; if (uinfo->value.enumerated.item >= uinfo->value.enumerated.items) uinfo->value.enumerated.item = uinfo->value.enumerated.items - 1; strcpy(uinfo->value.enumerated.name, texts[uinfo->value.enumerated.item]); return 0; } static int snd_rme9652_get_adat_sync(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_rme9652 *rme9652 = snd_kcontrol_chip(kcontrol); unsigned int mask1, mask2, val; switch (kcontrol->private_value) { case 0: mask1 = RME9652_lock_0; mask2 = RME9652_sync_0; break; case 1: mask1 = RME9652_lock_1; mask2 = RME9652_sync_1; break; case 2: mask1 = RME9652_lock_2; mask2 = RME9652_sync_2; break; default: return -EINVAL; } val = rme9652_read(rme9652, RME9652_status_register); ucontrol->value.enumerated.item[0] = (val & mask1) ? 1 : 0; ucontrol->value.enumerated.item[0] |= (val & mask2) ? 2 : 0; return 0; } #define RME9652_TC_VALID(xname, xindex) \ { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = xname, .index = xindex, \ .access = SNDRV_CTL_ELEM_ACCESS_READ | SNDRV_CTL_ELEM_ACCESS_VOLATILE, \ .info = snd_rme9652_info_tc_valid, \ .get = snd_rme9652_get_tc_valid } #define snd_rme9652_info_tc_valid snd_ctl_boolean_mono_info static int snd_rme9652_get_tc_valid(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_rme9652 *rme9652 = snd_kcontrol_chip(kcontrol); ucontrol->value.integer.value[0] = (rme9652_read(rme9652, RME9652_status_register) & RME9652_tc_valid) ? 1 : 0; return 0; } #ifdef ALSA_HAS_STANDARD_WAY_OF_RETURNING_TIMECODE /* FIXME: this routine needs a port to the new control API --jk */ static int snd_rme9652_get_tc_value(void *private_data, snd_kswitch_t *kswitch, snd_switch_t *uswitch) { struct snd_rme9652 *s = (struct snd_rme9652 *) private_data; u32 value; int i; uswitch->type = SNDRV_SW_TYPE_DWORD; if ((rme9652_read(s, RME9652_status_register) & RME9652_tc_valid) == 0) { uswitch->value.data32[0] = 0; return 0; } /* timecode request */ rme9652_write(s, RME9652_time_code, 0); /* XXX bug alert: loop-based timing !!!! */ for (i = 0; i < 50; i++) { if (!(rme9652_read(s, i * 4) & RME9652_tc_busy)) break; } if (!(rme9652_read(s, i * 4) & RME9652_tc_busy)) { return -EIO; } value = 0; for (i = 0; i < 32; i++) { value >>= 1; if (rme9652_read(s, i * 4) & RME9652_tc_out) value |= 0x80000000; } if (value > 2 * 60 * 48000) { value -= 2 * 60 * 48000; } else { value = 0; } uswitch->value.data32[0] = value; return 0; } #endif /* ALSA_HAS_STANDARD_WAY_OF_RETURNING_TIMECODE */ static struct snd_kcontrol_new snd_rme9652_controls[] = { { .iface = SNDRV_CTL_ELEM_IFACE_PCM, .name = SNDRV_CTL_NAME_IEC958("",PLAYBACK,DEFAULT), .info = snd_rme9652_control_spdif_info, .get = snd_rme9652_control_spdif_get, .put = snd_rme9652_control_spdif_put, }, { .access = SNDRV_CTL_ELEM_ACCESS_READWRITE | SNDRV_CTL_ELEM_ACCESS_INACTIVE, .iface = SNDRV_CTL_ELEM_IFACE_PCM, .name = SNDRV_CTL_NAME_IEC958("",PLAYBACK,PCM_STREAM), .info = snd_rme9652_control_spdif_stream_info, .get = snd_rme9652_control_spdif_stream_get, .put = snd_rme9652_control_spdif_stream_put, }, { .access = SNDRV_CTL_ELEM_ACCESS_READ, .iface = SNDRV_CTL_ELEM_IFACE_PCM, .name = SNDRV_CTL_NAME_IEC958("",PLAYBACK,CON_MASK), .info = snd_rme9652_control_spdif_mask_info, .get = snd_rme9652_control_spdif_mask_get, .private_value = IEC958_AES0_NONAUDIO | IEC958_AES0_PROFESSIONAL | IEC958_AES0_CON_EMPHASIS, }, { .access = SNDRV_CTL_ELEM_ACCESS_READ, .iface = SNDRV_CTL_ELEM_IFACE_PCM, .name = SNDRV_CTL_NAME_IEC958("",PLAYBACK,PRO_MASK), .info = snd_rme9652_control_spdif_mask_info, .get = snd_rme9652_control_spdif_mask_get, .private_value = IEC958_AES0_NONAUDIO | IEC958_AES0_PROFESSIONAL | IEC958_AES0_PRO_EMPHASIS, }, RME9652_SPDIF_IN("IEC958 Input Connector", 0), RME9652_SPDIF_OUT("IEC958 Output also on ADAT1", 0), RME9652_SYNC_MODE("Sync Mode", 0), RME9652_SYNC_PREF("Preferred Sync Source", 0), { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = "Channels Thru", .index = 0, .info = snd_rme9652_info_thru, .get = snd_rme9652_get_thru, .put = snd_rme9652_put_thru, }, RME9652_SPDIF_RATE("IEC958 Sample Rate", 0), RME9652_ADAT_SYNC("ADAT1 Sync Check", 0, 0), RME9652_ADAT_SYNC("ADAT2 Sync Check", 0, 1), RME9652_TC_VALID("Timecode Valid", 0), RME9652_PASSTHRU("Passthru", 0) }; static struct snd_kcontrol_new snd_rme9652_adat3_check = RME9652_ADAT_SYNC("ADAT3 Sync Check", 0, 2); static struct snd_kcontrol_new snd_rme9652_adat1_input = RME9652_ADAT1_IN("ADAT1 Input Source", 0); static int snd_rme9652_create_controls(struct snd_card *card, struct snd_rme9652 *rme9652) { unsigned int idx; int err; struct snd_kcontrol *kctl; for (idx = 0; idx < ARRAY_SIZE(snd_rme9652_controls); idx++) { if ((err = snd_ctl_add(card, kctl = snd_ctl_new1(&snd_rme9652_controls[idx], rme9652))) < 0) return err; if (idx == 1) /* IEC958 (S/PDIF) Stream */ rme9652->spdif_ctl = kctl; } if (rme9652->ss_channels == RME9652_NCHANNELS) if ((err = snd_ctl_add(card, kctl = snd_ctl_new1(&snd_rme9652_adat3_check, rme9652))) < 0) return err; if (rme9652->hw_rev >= 15) if ((err = snd_ctl_add(card, kctl = snd_ctl_new1(&snd_rme9652_adat1_input, rme9652))) < 0) return err; return 0; } /*------------------------------------------------------------ /proc interface ------------------------------------------------------------*/ static void snd_rme9652_proc_read(struct snd_info_entry *entry, struct snd_info_buffer *buffer) { struct snd_rme9652 *rme9652 = (struct snd_rme9652 *) entry->private_data; u32 thru_bits = rme9652->thru_bits; int show_auto_sync_source = 0; int i; unsigned int status; int x; status = rme9652_read(rme9652, RME9652_status_register); snd_iprintf(buffer, "%s (Card #%d)\n", rme9652->card_name, rme9652->card->number + 1); snd_iprintf(buffer, "Buffers: capture %p playback %p\n", rme9652->capture_buffer, rme9652->playback_buffer); snd_iprintf(buffer, "IRQ: %d Registers bus: 0x%lx VM: 0x%lx\n", rme9652->irq, rme9652->port, (unsigned long)rme9652->iobase); snd_iprintf(buffer, "Control register: %x\n", rme9652->control_register); snd_iprintf(buffer, "\n"); x = 1 << (6 + rme9652_decode_latency(rme9652->control_register & RME9652_latency)); snd_iprintf(buffer, "Latency: %d samples (2 periods of %lu bytes)\n", x, (unsigned long) rme9652->period_bytes); snd_iprintf(buffer, "Hardware pointer (frames): %ld\n", rme9652_hw_pointer(rme9652)); snd_iprintf(buffer, "Passthru: %s\n", rme9652->passthru ? "yes" : "no"); if ((rme9652->control_register & (RME9652_Master | RME9652_wsel)) == 0) { snd_iprintf(buffer, "Clock mode: autosync\n"); show_auto_sync_source = 1; } else if (rme9652->control_register & RME9652_wsel) { if (status & RME9652_wsel_rd) { snd_iprintf(buffer, "Clock mode: word clock\n"); } else { snd_iprintf(buffer, "Clock mode: word clock (no signal)\n"); } } else { snd_iprintf(buffer, "Clock mode: master\n"); } if (show_auto_sync_source) { switch (rme9652->control_register & RME9652_SyncPref_Mask) { case RME9652_SyncPref_ADAT1: snd_iprintf(buffer, "Pref. sync source: ADAT1\n"); break; case RME9652_SyncPref_ADAT2: snd_iprintf(buffer, "Pref. sync source: ADAT2\n"); break; case RME9652_SyncPref_ADAT3: snd_iprintf(buffer, "Pref. sync source: ADAT3\n"); break; case RME9652_SyncPref_SPDIF: snd_iprintf(buffer, "Pref. sync source: IEC958\n"); break; default: snd_iprintf(buffer, "Pref. sync source: ???\n"); } } if (rme9652->hw_rev >= 15) snd_iprintf(buffer, "\nADAT1 Input source: %s\n", (rme9652->control_register & RME9652_ADAT1_INTERNAL) ? "Internal" : "ADAT1 optical"); snd_iprintf(buffer, "\n"); switch (rme9652_decode_spdif_in(rme9652->control_register & RME9652_inp)) { case RME9652_SPDIFIN_OPTICAL: snd_iprintf(buffer, "IEC958 input: ADAT1\n"); break; case RME9652_SPDIFIN_COAXIAL: snd_iprintf(buffer, "IEC958 input: Coaxial\n"); break; case RME9652_SPDIFIN_INTERN: snd_iprintf(buffer, "IEC958 input: Internal\n"); break; default: snd_iprintf(buffer, "IEC958 input: ???\n"); break; } if (rme9652->control_register & RME9652_opt_out) { snd_iprintf(buffer, "IEC958 output: Coaxial & ADAT1\n"); } else { snd_iprintf(buffer, "IEC958 output: Coaxial only\n"); } if (rme9652->control_register & RME9652_PRO) { snd_iprintf(buffer, "IEC958 quality: Professional\n"); } else { snd_iprintf(buffer, "IEC958 quality: Consumer\n"); } if (rme9652->control_register & RME9652_EMP) { snd_iprintf(buffer, "IEC958 emphasis: on\n"); } else { snd_iprintf(buffer, "IEC958 emphasis: off\n"); } if (rme9652->control_register & RME9652_Dolby) { snd_iprintf(buffer, "IEC958 Dolby: on\n"); } else { snd_iprintf(buffer, "IEC958 Dolby: off\n"); } i = rme9652_spdif_sample_rate(rme9652); if (i < 0) { snd_iprintf(buffer, "IEC958 sample rate: error flag set\n"); } else if (i == 0) { snd_iprintf(buffer, "IEC958 sample rate: undetermined\n"); } else { snd_iprintf(buffer, "IEC958 sample rate: %d\n", i); } snd_iprintf(buffer, "\n"); snd_iprintf(buffer, "ADAT Sample rate: %dHz\n", rme9652_adat_sample_rate(rme9652)); /* Sync Check */ x = status & RME9652_sync_0; if (status & RME9652_lock_0) { snd_iprintf(buffer, "ADAT1: %s\n", x ? "Sync" : "Lock"); } else { snd_iprintf(buffer, "ADAT1: No Lock\n"); } x = status & RME9652_sync_1; if (status & RME9652_lock_1) { snd_iprintf(buffer, "ADAT2: %s\n", x ? "Sync" : "Lock"); } else { snd_iprintf(buffer, "ADAT2: No Lock\n"); } x = status & RME9652_sync_2; if (status & RME9652_lock_2) { snd_iprintf(buffer, "ADAT3: %s\n", x ? "Sync" : "Lock"); } else { snd_iprintf(buffer, "ADAT3: No Lock\n"); } snd_iprintf(buffer, "\n"); snd_iprintf(buffer, "Timecode signal: %s\n", (status & RME9652_tc_valid) ? "yes" : "no"); /* thru modes */ snd_iprintf(buffer, "Punch Status:\n\n"); for (i = 0; i < rme9652->ss_channels; i++) { if (thru_bits & (1 << i)) { snd_iprintf(buffer, "%2d: on ", i + 1); } else { snd_iprintf(buffer, "%2d: off ", i + 1); } if (((i + 1) % 8) == 0) { snd_iprintf(buffer, "\n"); } } snd_iprintf(buffer, "\n"); } static void __devinit snd_rme9652_proc_init(struct snd_rme9652 *rme9652) { struct snd_info_entry *entry; if (! snd_card_proc_new(rme9652->card, "rme9652", &entry)) snd_info_set_text_ops(entry, rme9652, snd_rme9652_proc_read); } static void snd_rme9652_free_buffers(struct snd_rme9652 *rme9652) { snd_hammerfall_free_buffer(&rme9652->capture_dma_buf, rme9652->pci); snd_hammerfall_free_buffer(&rme9652->playback_dma_buf, rme9652->pci); } static int snd_rme9652_free(struct snd_rme9652 *rme9652) { if (rme9652->irq >= 0) rme9652_stop(rme9652); snd_rme9652_free_buffers(rme9652); if (rme9652->irq >= 0) free_irq(rme9652->irq, (void *)rme9652); if (rme9652->iobase) iounmap(rme9652->iobase); if (rme9652->port) pci_release_regions(rme9652->pci); pci_disable_device(rme9652->pci); return 0; } static int __devinit snd_rme9652_initialize_memory(struct snd_rme9652 *rme9652) { unsigned long pb_bus, cb_bus; if (snd_hammerfall_get_buffer(rme9652->pci, &rme9652->capture_dma_buf, RME9652_DMA_AREA_BYTES) < 0 || snd_hammerfall_get_buffer(rme9652->pci, &rme9652->playback_dma_buf, RME9652_DMA_AREA_BYTES) < 0) { if (rme9652->capture_dma_buf.area) snd_dma_free_pages(&rme9652->capture_dma_buf); printk(KERN_ERR "%s: no buffers available\n", rme9652->card_name); return -ENOMEM; } /* Align to bus-space 64K boundary */ cb_bus = ALIGN(rme9652->capture_dma_buf.addr, 0x10000ul); pb_bus = ALIGN(rme9652->playback_dma_buf.addr, 0x10000ul); /* Tell the card where it is */ rme9652_write(rme9652, RME9652_rec_buffer, cb_bus); rme9652_write(rme9652, RME9652_play_buffer, pb_bus); rme9652->capture_buffer = rme9652->capture_dma_buf.area + (cb_bus - rme9652->capture_dma_buf.addr); rme9652->playback_buffer = rme9652->playback_dma_buf.area + (pb_bus - rme9652->playback_dma_buf.addr); return 0; } static void snd_rme9652_set_defaults(struct snd_rme9652 *rme9652) { unsigned int k; /* ASSUMPTION: rme9652->lock is either held, or there is no need to hold it (e.g. during module initialization). */ /* set defaults: SPDIF Input via Coax autosync clock mode maximum latency (7 = 8192 samples, 64Kbyte buffer, which implies 2 4096 sample, 32Kbyte periods). if rev 1.5, initialize the S/PDIF receiver. */ rme9652->control_register = RME9652_inp_0 | rme9652_encode_latency(7); rme9652_write(rme9652, RME9652_control_register, rme9652->control_register); rme9652_reset_hw_pointer(rme9652); rme9652_compute_period_size(rme9652); /* default: thru off for all channels */ for (k = 0; k < RME9652_NCHANNELS; ++k) rme9652_write(rme9652, RME9652_thru_base + k * 4, 0); rme9652->thru_bits = 0; rme9652->passthru = 0; /* set a default rate so that the channel map is set up */ rme9652_set_rate(rme9652, 48000); } static irqreturn_t snd_rme9652_interrupt(int irq, void *dev_id) { struct snd_rme9652 *rme9652 = (struct snd_rme9652 *) dev_id; if (!(rme9652_read(rme9652, RME9652_status_register) & RME9652_IRQ)) { return IRQ_NONE; } rme9652_write(rme9652, RME9652_irq_clear, 0); if (rme9652->capture_substream) { snd_pcm_period_elapsed(rme9652->pcm->streams[SNDRV_PCM_STREAM_CAPTURE].substream); } if (rme9652->playback_substream) { snd_pcm_period_elapsed(rme9652->pcm->streams[SNDRV_PCM_STREAM_PLAYBACK].substream); } return IRQ_HANDLED; } static snd_pcm_uframes_t snd_rme9652_hw_pointer(struct snd_pcm_substream *substream) { struct snd_rme9652 *rme9652 = snd_pcm_substream_chip(substream); return rme9652_hw_pointer(rme9652); } static char *rme9652_channel_buffer_location(struct snd_rme9652 *rme9652, int stream, int channel) { int mapped_channel; if (snd_BUG_ON(channel < 0 || channel >= RME9652_NCHANNELS)) return NULL; if ((mapped_channel = rme9652->channel_map[channel]) < 0) { return NULL; } if (stream == SNDRV_PCM_STREAM_CAPTURE) { return rme9652->capture_buffer + (mapped_channel * RME9652_CHANNEL_BUFFER_BYTES); } else { return rme9652->playback_buffer + (mapped_channel * RME9652_CHANNEL_BUFFER_BYTES); } } static int snd_rme9652_playback_copy(struct snd_pcm_substream *substream, int channel, snd_pcm_uframes_t pos, void __user *src, snd_pcm_uframes_t count) { struct snd_rme9652 *rme9652 = snd_pcm_substream_chip(substream); char *channel_buf; if (snd_BUG_ON(pos + count > RME9652_CHANNEL_BUFFER_BYTES / 4)) return -EINVAL; channel_buf = rme9652_channel_buffer_location (rme9652, substream->pstr->stream, channel); if (snd_BUG_ON(!channel_buf)) return -EIO; if (copy_from_user(channel_buf + pos * 4, src, count * 4)) return -EFAULT; return count; } static int snd_rme9652_capture_copy(struct snd_pcm_substream *substream, int channel, snd_pcm_uframes_t pos, void __user *dst, snd_pcm_uframes_t count) { struct snd_rme9652 *rme9652 = snd_pcm_substream_chip(substream); char *channel_buf; if (snd_BUG_ON(pos + count > RME9652_CHANNEL_BUFFER_BYTES / 4)) return -EINVAL; channel_buf = rme9652_channel_buffer_location (rme9652, substream->pstr->stream, channel); if (snd_BUG_ON(!channel_buf)) return -EIO; if (copy_to_user(dst, channel_buf + pos * 4, count * 4)) return -EFAULT; return count; } static int snd_rme9652_hw_silence(struct snd_pcm_substream *substream, int channel, snd_pcm_uframes_t pos, snd_pcm_uframes_t count) { struct snd_rme9652 *rme9652 = snd_pcm_substream_chip(substream); char *channel_buf; channel_buf = rme9652_channel_buffer_location (rme9652, substream->pstr->stream, channel); if (snd_BUG_ON(!channel_buf)) return -EIO; memset(channel_buf + pos * 4, 0, count * 4); return count; } static int snd_rme9652_reset(struct snd_pcm_substream *substream) { struct snd_pcm_runtime *runtime = substream->runtime; struct snd_rme9652 *rme9652 = snd_pcm_substream_chip(substream); struct snd_pcm_substream *other; if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) other = rme9652->capture_substream; else other = rme9652->playback_substream; if (rme9652->running) runtime->status->hw_ptr = rme9652_hw_pointer(rme9652); else runtime->status->hw_ptr = 0; if (other) { struct snd_pcm_substream *s; struct snd_pcm_runtime *oruntime = other->runtime; snd_pcm_group_for_each_entry(s, substream) { if (s == other) { oruntime->status->hw_ptr = runtime->status->hw_ptr; break; } } } return 0; } static int snd_rme9652_hw_params(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *params) { struct snd_rme9652 *rme9652 = snd_pcm_substream_chip(substream); int err; pid_t this_pid; pid_t other_pid; spin_lock_irq(&rme9652->lock); if (substream->pstr->stream == SNDRV_PCM_STREAM_PLAYBACK) { rme9652->control_register &= ~(RME9652_PRO | RME9652_Dolby | RME9652_EMP); rme9652_write(rme9652, RME9652_control_register, rme9652->control_register |= rme9652->creg_spdif_stream); this_pid = rme9652->playback_pid; other_pid = rme9652->capture_pid; } else { this_pid = rme9652->capture_pid; other_pid = rme9652->playback_pid; } if ((other_pid > 0) && (this_pid != other_pid)) { /* The other stream is open, and not by the same task as this one. Make sure that the parameters that matter are the same. */ if ((int)params_rate(params) != rme9652_adat_sample_rate(rme9652)) { spin_unlock_irq(&rme9652->lock); _snd_pcm_hw_param_setempty(params, SNDRV_PCM_HW_PARAM_RATE); return -EBUSY; } if (params_period_size(params) != rme9652->period_bytes / 4) { spin_unlock_irq(&rme9652->lock); _snd_pcm_hw_param_setempty(params, SNDRV_PCM_HW_PARAM_PERIOD_SIZE); return -EBUSY; } /* We're fine. */ spin_unlock_irq(&rme9652->lock); return 0; } else { spin_unlock_irq(&rme9652->lock); } /* how to make sure that the rate matches an externally-set one ? */ if ((err = rme9652_set_rate(rme9652, params_rate(params))) < 0) { _snd_pcm_hw_param_setempty(params, SNDRV_PCM_HW_PARAM_RATE); return err; } if ((err = rme9652_set_interrupt_interval(rme9652, params_period_size(params))) < 0) { _snd_pcm_hw_param_setempty(params, SNDRV_PCM_HW_PARAM_PERIOD_SIZE); return err; } return 0; } static int snd_rme9652_channel_info(struct snd_pcm_substream *substream, struct snd_pcm_channel_info *info) { struct snd_rme9652 *rme9652 = snd_pcm_substream_chip(substream); int chn; if (snd_BUG_ON(info->channel >= RME9652_NCHANNELS)) return -EINVAL; if ((chn = rme9652->channel_map[info->channel]) < 0) { return -EINVAL; } info->offset = chn * RME9652_CHANNEL_BUFFER_BYTES; info->first = 0; info->step = 32; return 0; } static int snd_rme9652_ioctl(struct snd_pcm_substream *substream, unsigned int cmd, void *arg) { switch (cmd) { case SNDRV_PCM_IOCTL1_RESET: { return snd_rme9652_reset(substream); } case SNDRV_PCM_IOCTL1_CHANNEL_INFO: { struct snd_pcm_channel_info *info = arg; return snd_rme9652_channel_info(substream, info); } default: break; } return snd_pcm_lib_ioctl(substream, cmd, arg); } static void rme9652_silence_playback(struct snd_rme9652 *rme9652) { memset(rme9652->playback_buffer, 0, RME9652_DMA_AREA_BYTES); } static int snd_rme9652_trigger(struct snd_pcm_substream *substream, int cmd) { struct snd_rme9652 *rme9652 = snd_pcm_substream_chip(substream); struct snd_pcm_substream *other; int running; spin_lock(&rme9652->lock); running = rme9652->running; switch (cmd) { case SNDRV_PCM_TRIGGER_START: running |= 1 << substream->stream; break; case SNDRV_PCM_TRIGGER_STOP: running &= ~(1 << substream->stream); break; default: snd_BUG(); spin_unlock(&rme9652->lock); return -EINVAL; } if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) other = rme9652->capture_substream; else other = rme9652->playback_substream; if (other) { struct snd_pcm_substream *s; snd_pcm_group_for_each_entry(s, substream) { if (s == other) { snd_pcm_trigger_done(s, substream); if (cmd == SNDRV_PCM_TRIGGER_START) running |= 1 << s->stream; else running &= ~(1 << s->stream); goto _ok; } } if (cmd == SNDRV_PCM_TRIGGER_START) { if (!(running & (1 << SNDRV_PCM_STREAM_PLAYBACK)) && substream->stream == SNDRV_PCM_STREAM_CAPTURE) rme9652_silence_playback(rme9652); } else { if (running && substream->stream == SNDRV_PCM_STREAM_PLAYBACK) rme9652_silence_playback(rme9652); } } else { if (substream->stream == SNDRV_PCM_STREAM_CAPTURE) rme9652_silence_playback(rme9652); } _ok: snd_pcm_trigger_done(substream, substream); if (!rme9652->running && running) rme9652_start(rme9652); else if (rme9652->running && !running) rme9652_stop(rme9652); rme9652->running = running; spin_unlock(&rme9652->lock); return 0; } static int snd_rme9652_prepare(struct snd_pcm_substream *substream) { struct snd_rme9652 *rme9652 = snd_pcm_substream_chip(substream); unsigned long flags; int result = 0; spin_lock_irqsave(&rme9652->lock, flags); if (!rme9652->running) rme9652_reset_hw_pointer(rme9652); spin_unlock_irqrestore(&rme9652->lock, flags); return result; } static struct snd_pcm_hardware snd_rme9652_playback_subinfo = { .info = (SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_MMAP_VALID | SNDRV_PCM_INFO_NONINTERLEAVED | SNDRV_PCM_INFO_SYNC_START | SNDRV_PCM_INFO_DOUBLE), .formats = SNDRV_PCM_FMTBIT_S32_LE, .rates = (SNDRV_PCM_RATE_44100 | SNDRV_PCM_RATE_48000 | SNDRV_PCM_RATE_88200 | SNDRV_PCM_RATE_96000), .rate_min = 44100, .rate_max = 96000, .channels_min = 10, .channels_max = 26, .buffer_bytes_max = RME9652_CHANNEL_BUFFER_BYTES * 26, .period_bytes_min = (64 * 4) * 10, .period_bytes_max = (8192 * 4) * 26, .periods_min = 2, .periods_max = 2, .fifo_size = 0, }; static struct snd_pcm_hardware snd_rme9652_capture_subinfo = { .info = (SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_MMAP_VALID | SNDRV_PCM_INFO_NONINTERLEAVED | SNDRV_PCM_INFO_SYNC_START), .formats = SNDRV_PCM_FMTBIT_S32_LE, .rates = (SNDRV_PCM_RATE_44100 | SNDRV_PCM_RATE_48000 | SNDRV_PCM_RATE_88200 | SNDRV_PCM_RATE_96000), .rate_min = 44100, .rate_max = 96000, .channels_min = 10, .channels_max = 26, .buffer_bytes_max = RME9652_CHANNEL_BUFFER_BYTES *26, .period_bytes_min = (64 * 4) * 10, .period_bytes_max = (8192 * 4) * 26, .periods_min = 2, .periods_max = 2, .fifo_size = 0, }; static unsigned int period_sizes[] = { 64, 128, 256, 512, 1024, 2048, 4096, 8192 }; static struct snd_pcm_hw_constraint_list hw_constraints_period_sizes = { .count = ARRAY_SIZE(period_sizes), .list = period_sizes, .mask = 0 }; static int snd_rme9652_hw_rule_channels(struct snd_pcm_hw_params *params, struct snd_pcm_hw_rule *rule) { struct snd_rme9652 *rme9652 = rule->private; struct snd_interval *c = hw_param_interval(params, SNDRV_PCM_HW_PARAM_CHANNELS); unsigned int list[2] = { rme9652->ds_channels, rme9652->ss_channels }; return snd_interval_list(c, 2, list, 0); } static int snd_rme9652_hw_rule_channels_rate(struct snd_pcm_hw_params *params, struct snd_pcm_hw_rule *rule) { struct snd_rme9652 *rme9652 = rule->private; struct snd_interval *c = hw_param_interval(params, SNDRV_PCM_HW_PARAM_CHANNELS); struct snd_interval *r = hw_param_interval(params, SNDRV_PCM_HW_PARAM_RATE); if (r->min > 48000) { struct snd_interval t = { .min = rme9652->ds_channels, .max = rme9652->ds_channels, .integer = 1, }; return snd_interval_refine(c, &t); } else if (r->max < 88200) { struct snd_interval t = { .min = rme9652->ss_channels, .max = rme9652->ss_channels, .integer = 1, }; return snd_interval_refine(c, &t); } return 0; } static int snd_rme9652_hw_rule_rate_channels(struct snd_pcm_hw_params *params, struct snd_pcm_hw_rule *rule) { struct snd_rme9652 *rme9652 = rule->private; struct snd_interval *c = hw_param_interval(params, SNDRV_PCM_HW_PARAM_CHANNELS); struct snd_interval *r = hw_param_interval(params, SNDRV_PCM_HW_PARAM_RATE); if (c->min >= rme9652->ss_channels) { struct snd_interval t = { .min = 44100, .max = 48000, .integer = 1, }; return snd_interval_refine(r, &t); } else if (c->max <= rme9652->ds_channels) { struct snd_interval t = { .min = 88200, .max = 96000, .integer = 1, }; return snd_interval_refine(r, &t); } return 0; } static int snd_rme9652_playback_open(struct snd_pcm_substream *substream) { struct snd_rme9652 *rme9652 = snd_pcm_substream_chip(substream); struct snd_pcm_runtime *runtime = substream->runtime; spin_lock_irq(&rme9652->lock); snd_pcm_set_sync(substream); runtime->hw = snd_rme9652_playback_subinfo; runtime->dma_area = rme9652->playback_buffer; runtime->dma_bytes = RME9652_DMA_AREA_BYTES; if (rme9652->capture_substream == NULL) { rme9652_stop(rme9652); rme9652_set_thru(rme9652, -1, 0); } rme9652->playback_pid = current->pid; rme9652->playback_substream = substream; spin_unlock_irq(&rme9652->lock); snd_pcm_hw_constraint_msbits(runtime, 0, 32, 24); snd_pcm_hw_constraint_list(runtime, 0, SNDRV_PCM_HW_PARAM_PERIOD_SIZE, &hw_constraints_period_sizes); snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_CHANNELS, snd_rme9652_hw_rule_channels, rme9652, SNDRV_PCM_HW_PARAM_CHANNELS, -1); snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_CHANNELS, snd_rme9652_hw_rule_channels_rate, rme9652, SNDRV_PCM_HW_PARAM_RATE, -1); snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_RATE, snd_rme9652_hw_rule_rate_channels, rme9652, SNDRV_PCM_HW_PARAM_CHANNELS, -1); rme9652->creg_spdif_stream = rme9652->creg_spdif; rme9652->spdif_ctl->vd[0].access &= ~SNDRV_CTL_ELEM_ACCESS_INACTIVE; snd_ctl_notify(rme9652->card, SNDRV_CTL_EVENT_MASK_VALUE | SNDRV_CTL_EVENT_MASK_INFO, &rme9652->spdif_ctl->id); return 0; } static int snd_rme9652_playback_release(struct snd_pcm_substream *substream) { struct snd_rme9652 *rme9652 = snd_pcm_substream_chip(substream); spin_lock_irq(&rme9652->lock); rme9652->playback_pid = -1; rme9652->playback_substream = NULL; spin_unlock_irq(&rme9652->lock); rme9652->spdif_ctl->vd[0].access |= SNDRV_CTL_ELEM_ACCESS_INACTIVE; snd_ctl_notify(rme9652->card, SNDRV_CTL_EVENT_MASK_VALUE | SNDRV_CTL_EVENT_MASK_INFO, &rme9652->spdif_ctl->id); return 0; } static int snd_rme9652_capture_open(struct snd_pcm_substream *substream) { struct snd_rme9652 *rme9652 = snd_pcm_substream_chip(substream); struct snd_pcm_runtime *runtime = substream->runtime; spin_lock_irq(&rme9652->lock); snd_pcm_set_sync(substream); runtime->hw = snd_rme9652_capture_subinfo; runtime->dma_area = rme9652->capture_buffer; runtime->dma_bytes = RME9652_DMA_AREA_BYTES; if (rme9652->playback_substream == NULL) { rme9652_stop(rme9652); rme9652_set_thru(rme9652, -1, 0); } rme9652->capture_pid = current->pid; rme9652->capture_substream = substream; spin_unlock_irq(&rme9652->lock); snd_pcm_hw_constraint_msbits(runtime, 0, 32, 24); snd_pcm_hw_constraint_list(runtime, 0, SNDRV_PCM_HW_PARAM_PERIOD_SIZE, &hw_constraints_period_sizes); snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_CHANNELS, snd_rme9652_hw_rule_channels, rme9652, SNDRV_PCM_HW_PARAM_CHANNELS, -1); snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_CHANNELS, snd_rme9652_hw_rule_channels_rate, rme9652, SNDRV_PCM_HW_PARAM_RATE, -1); snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_RATE, snd_rme9652_hw_rule_rate_channels, rme9652, SNDRV_PCM_HW_PARAM_CHANNELS, -1); return 0; } static int snd_rme9652_capture_release(struct snd_pcm_substream *substream) { struct snd_rme9652 *rme9652 = snd_pcm_substream_chip(substream); spin_lock_irq(&rme9652->lock); rme9652->capture_pid = -1; rme9652->capture_substream = NULL; spin_unlock_irq(&rme9652->lock); return 0; } static struct snd_pcm_ops snd_rme9652_playback_ops = { .open = snd_rme9652_playback_open, .close = snd_rme9652_playback_release, .ioctl = snd_rme9652_ioctl, .hw_params = snd_rme9652_hw_params, .prepare = snd_rme9652_prepare, .trigger = snd_rme9652_trigger, .pointer = snd_rme9652_hw_pointer, .copy = snd_rme9652_playback_copy, .silence = snd_rme9652_hw_silence, }; static struct snd_pcm_ops snd_rme9652_capture_ops = { .open = snd_rme9652_capture_open, .close = snd_rme9652_capture_release, .ioctl = snd_rme9652_ioctl, .hw_params = snd_rme9652_hw_params, .prepare = snd_rme9652_prepare, .trigger = snd_rme9652_trigger, .pointer = snd_rme9652_hw_pointer, .copy = snd_rme9652_capture_copy, }; static int __devinit snd_rme9652_create_pcm(struct snd_card *card, struct snd_rme9652 *rme9652) { struct snd_pcm *pcm; int err; if ((err = snd_pcm_new(card, rme9652->card_name, 0, 1, 1, &pcm)) < 0) { return err; } rme9652->pcm = pcm; pcm->private_data = rme9652; strcpy(pcm->name, rme9652->card_name); snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &snd_rme9652_playback_ops); snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE, &snd_rme9652_capture_ops); pcm->info_flags = SNDRV_PCM_INFO_JOINT_DUPLEX; return 0; } static int __devinit snd_rme9652_create(struct snd_card *card, struct snd_rme9652 *rme9652, int precise_ptr) { struct pci_dev *pci = rme9652->pci; int err; int status; unsigned short rev; rme9652->irq = -1; rme9652->card = card; pci_read_config_word(rme9652->pci, PCI_CLASS_REVISION, &rev); switch (rev & 0xff) { case 3: case 4: case 8: case 9: break; default: /* who knows? */ return -ENODEV; } if ((err = pci_enable_device(pci)) < 0) return err; spin_lock_init(&rme9652->lock); if ((err = pci_request_regions(pci, "rme9652")) < 0) return err; rme9652->port = pci_resource_start(pci, 0); rme9652->iobase = ioremap_nocache(rme9652->port, RME9652_IO_EXTENT); if (rme9652->iobase == NULL) { snd_printk(KERN_ERR "unable to remap region 0x%lx-0x%lx\n", rme9652->port, rme9652->port + RME9652_IO_EXTENT - 1); return -EBUSY; } if (request_irq(pci->irq, snd_rme9652_interrupt, IRQF_SHARED, "rme9652", rme9652)) { snd_printk(KERN_ERR "unable to request IRQ %d\n", pci->irq); return -EBUSY; } rme9652->irq = pci->irq; rme9652->precise_ptr = precise_ptr; /* Determine the h/w rev level of the card. This seems like a particularly kludgy way to encode it, but its what RME chose to do, so we follow them ... */ status = rme9652_read(rme9652, RME9652_status_register); if (rme9652_decode_spdif_rate(status&RME9652_F) == 1) { rme9652->hw_rev = 15; } else { rme9652->hw_rev = 11; } /* Differentiate between the standard Hammerfall, and the "Light", which does not have the expansion board. This method comes from information received from Mathhias Clausen at RME. Display the EEPROM and h/w revID where relevant. */ switch (rev) { case 8: /* original eprom */ strcpy(card->driver, "RME9636"); if (rme9652->hw_rev == 15) { rme9652->card_name = "RME Digi9636 (Rev 1.5)"; } else { rme9652->card_name = "RME Digi9636"; } rme9652->ss_channels = RME9636_NCHANNELS; break; case 9: /* W36_G EPROM */ strcpy(card->driver, "RME9636"); rme9652->card_name = "RME Digi9636 (Rev G)"; rme9652->ss_channels = RME9636_NCHANNELS; break; case 4: /* W52_G EPROM */ strcpy(card->driver, "RME9652"); rme9652->card_name = "RME Digi9652 (Rev G)"; rme9652->ss_channels = RME9652_NCHANNELS; break; case 3: /* original eprom */ strcpy(card->driver, "RME9652"); if (rme9652->hw_rev == 15) { rme9652->card_name = "RME Digi9652 (Rev 1.5)"; } else { rme9652->card_name = "RME Digi9652"; } rme9652->ss_channels = RME9652_NCHANNELS; break; } rme9652->ds_channels = (rme9652->ss_channels - 2) / 2 + 2; pci_set_master(rme9652->pci); if ((err = snd_rme9652_initialize_memory(rme9652)) < 0) { return err; } if ((err = snd_rme9652_create_pcm(card, rme9652)) < 0) { return err; } if ((err = snd_rme9652_create_controls(card, rme9652)) < 0) { return err; } snd_rme9652_proc_init(rme9652); rme9652->last_spdif_sample_rate = -1; rme9652->last_adat_sample_rate = -1; rme9652->playback_pid = -1; rme9652->capture_pid = -1; rme9652->capture_substream = NULL; rme9652->playback_substream = NULL; snd_rme9652_set_defaults(rme9652); if (rme9652->hw_rev == 15) { rme9652_initialize_spdif_receiver (rme9652); } return 0; } static void snd_rme9652_card_free(struct snd_card *card) { struct snd_rme9652 *rme9652 = (struct snd_rme9652 *) card->private_data; if (rme9652) snd_rme9652_free(rme9652); } static int __devinit snd_rme9652_probe(struct pci_dev *pci, const struct pci_device_id *pci_id) { static int dev; struct snd_rme9652 *rme9652; struct snd_card *card; int err; if (dev >= SNDRV_CARDS) return -ENODEV; if (!enable[dev]) { dev++; return -ENOENT; } err = snd_card_create(index[dev], id[dev], THIS_MODULE, sizeof(struct snd_rme9652), &card); if (err < 0) return err; rme9652 = (struct snd_rme9652 *) card->private_data; card->private_free = snd_rme9652_card_free; rme9652->dev = dev; rme9652->pci = pci; snd_card_set_dev(card, &pci->dev); if ((err = snd_rme9652_create(card, rme9652, precise_ptr[dev])) < 0) { snd_card_free(card); return err; } strcpy(card->shortname, rme9652->card_name); sprintf(card->longname, "%s at 0x%lx, irq %d", card->shortname, rme9652->port, rme9652->irq); if ((err = snd_card_register(card)) < 0) { snd_card_free(card); return err; } pci_set_drvdata(pci, card); dev++; return 0; } static void __devexit snd_rme9652_remove(struct pci_dev *pci) { snd_card_free(pci_get_drvdata(pci)); pci_set_drvdata(pci, NULL); } static struct pci_driver driver = { .name = "RME Digi9652 (Hammerfall)", .id_table = snd_rme9652_ids, .probe = snd_rme9652_probe, .remove = __devexit_p(snd_rme9652_remove), }; static int __init alsa_card_hammerfall_init(void) { return pci_register_driver(&driver); } static void __exit alsa_card_hammerfall_exit(void) { pci_unregister_driver(&driver); } module_init(alsa_card_hammerfall_init) module_exit(alsa_card_hammerfall_exit)
gpl-2.0
hunter3k/aosp_kernel_lge_d315
net/netfilter/nf_log.c
4607
7370
#include <linux/kernel.h> #include <linux/init.h> #include <linux/module.h> #include <linux/proc_fs.h> #include <linux/skbuff.h> #include <linux/netfilter.h> #include <linux/seq_file.h> #include <net/protocol.h> #include <net/netfilter/nf_log.h> #include "nf_internals.h" /* Internal logging interface, which relies on the real LOG target modules */ #define NF_LOG_PREFIXLEN 128 #define NFLOGGER_NAME_LEN 64 static const struct nf_logger __rcu *nf_loggers[NFPROTO_NUMPROTO] __read_mostly; static struct list_head nf_loggers_l[NFPROTO_NUMPROTO] __read_mostly; static DEFINE_MUTEX(nf_log_mutex); static struct nf_logger *__find_logger(int pf, const char *str_logger) { struct nf_logger *t; list_for_each_entry(t, &nf_loggers_l[pf], list[pf]) { if (!strnicmp(str_logger, t->name, strlen(t->name))) return t; } return NULL; } /* return EEXIST if the same logger is registred, 0 on success. */ int nf_log_register(u_int8_t pf, struct nf_logger *logger) { const struct nf_logger *llog; int i; if (pf >= ARRAY_SIZE(nf_loggers)) return -EINVAL; for (i = 0; i < ARRAY_SIZE(logger->list); i++) INIT_LIST_HEAD(&logger->list[i]); mutex_lock(&nf_log_mutex); if (pf == NFPROTO_UNSPEC) { for (i = NFPROTO_UNSPEC; i < NFPROTO_NUMPROTO; i++) list_add_tail(&(logger->list[i]), &(nf_loggers_l[i])); } else { /* register at end of list to honor first register win */ list_add_tail(&logger->list[pf], &nf_loggers_l[pf]); llog = rcu_dereference_protected(nf_loggers[pf], lockdep_is_held(&nf_log_mutex)); if (llog == NULL) rcu_assign_pointer(nf_loggers[pf], logger); } mutex_unlock(&nf_log_mutex); return 0; } EXPORT_SYMBOL(nf_log_register); void nf_log_unregister(struct nf_logger *logger) { const struct nf_logger *c_logger; int i; mutex_lock(&nf_log_mutex); for (i = 0; i < ARRAY_SIZE(nf_loggers); i++) { c_logger = rcu_dereference_protected(nf_loggers[i], lockdep_is_held(&nf_log_mutex)); if (c_logger == logger) RCU_INIT_POINTER(nf_loggers[i], NULL); list_del(&logger->list[i]); } mutex_unlock(&nf_log_mutex); synchronize_rcu(); } EXPORT_SYMBOL(nf_log_unregister); int nf_log_bind_pf(u_int8_t pf, const struct nf_logger *logger) { if (pf >= ARRAY_SIZE(nf_loggers)) return -EINVAL; mutex_lock(&nf_log_mutex); if (__find_logger(pf, logger->name) == NULL) { mutex_unlock(&nf_log_mutex); return -ENOENT; } rcu_assign_pointer(nf_loggers[pf], logger); mutex_unlock(&nf_log_mutex); return 0; } EXPORT_SYMBOL(nf_log_bind_pf); void nf_log_unbind_pf(u_int8_t pf) { if (pf >= ARRAY_SIZE(nf_loggers)) return; mutex_lock(&nf_log_mutex); RCU_INIT_POINTER(nf_loggers[pf], NULL); mutex_unlock(&nf_log_mutex); } EXPORT_SYMBOL(nf_log_unbind_pf); void nf_log_packet(u_int8_t pf, unsigned int hooknum, const struct sk_buff *skb, const struct net_device *in, const struct net_device *out, const struct nf_loginfo *loginfo, const char *fmt, ...) { va_list args; char prefix[NF_LOG_PREFIXLEN]; const struct nf_logger *logger; rcu_read_lock(); logger = rcu_dereference(nf_loggers[pf]); if (logger) { va_start(args, fmt); vsnprintf(prefix, sizeof(prefix), fmt, args); va_end(args); logger->logfn(pf, hooknum, skb, in, out, loginfo, prefix); } rcu_read_unlock(); } EXPORT_SYMBOL(nf_log_packet); #ifdef CONFIG_PROC_FS static void *seq_start(struct seq_file *seq, loff_t *pos) { mutex_lock(&nf_log_mutex); if (*pos >= ARRAY_SIZE(nf_loggers)) return NULL; return pos; } static void *seq_next(struct seq_file *s, void *v, loff_t *pos) { (*pos)++; if (*pos >= ARRAY_SIZE(nf_loggers)) return NULL; return pos; } static void seq_stop(struct seq_file *s, void *v) { mutex_unlock(&nf_log_mutex); } static int seq_show(struct seq_file *s, void *v) { loff_t *pos = v; const struct nf_logger *logger; struct nf_logger *t; int ret; logger = rcu_dereference_protected(nf_loggers[*pos], lockdep_is_held(&nf_log_mutex)); if (!logger) ret = seq_printf(s, "%2lld NONE (", *pos); else ret = seq_printf(s, "%2lld %s (", *pos, logger->name); if (ret < 0) return ret; list_for_each_entry(t, &nf_loggers_l[*pos], list[*pos]) { ret = seq_printf(s, "%s", t->name); if (ret < 0) return ret; if (&t->list[*pos] != nf_loggers_l[*pos].prev) { ret = seq_printf(s, ","); if (ret < 0) return ret; } } return seq_printf(s, ")\n"); } static const struct seq_operations nflog_seq_ops = { .start = seq_start, .next = seq_next, .stop = seq_stop, .show = seq_show, }; static int nflog_open(struct inode *inode, struct file *file) { return seq_open(file, &nflog_seq_ops); } static const struct file_operations nflog_file_ops = { .owner = THIS_MODULE, .open = nflog_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release, }; #endif /* PROC_FS */ #ifdef CONFIG_SYSCTL static struct ctl_path nf_log_sysctl_path[] = { { .procname = "net", }, { .procname = "netfilter", }, { .procname = "nf_log", }, { } }; static char nf_log_sysctl_fnames[NFPROTO_NUMPROTO-NFPROTO_UNSPEC][3]; static struct ctl_table nf_log_sysctl_table[NFPROTO_NUMPROTO+1]; static struct ctl_table_header *nf_log_dir_header; static int nf_log_proc_dostring(ctl_table *table, int write, void __user *buffer, size_t *lenp, loff_t *ppos) { const struct nf_logger *logger; char buf[NFLOGGER_NAME_LEN]; size_t size = *lenp; int r = 0; int tindex = (unsigned long)table->extra1; if (write) { if (size > sizeof(buf)) size = sizeof(buf); if (copy_from_user(buf, buffer, size)) return -EFAULT; if (!strcmp(buf, "NONE")) { nf_log_unbind_pf(tindex); return 0; } mutex_lock(&nf_log_mutex); logger = __find_logger(tindex, buf); if (logger == NULL) { mutex_unlock(&nf_log_mutex); return -ENOENT; } rcu_assign_pointer(nf_loggers[tindex], logger); mutex_unlock(&nf_log_mutex); } else { mutex_lock(&nf_log_mutex); logger = rcu_dereference_protected(nf_loggers[tindex], lockdep_is_held(&nf_log_mutex)); if (!logger) table->data = "NONE"; else table->data = logger->name; r = proc_dostring(table, write, buffer, lenp, ppos); mutex_unlock(&nf_log_mutex); } return r; } static __init int netfilter_log_sysctl_init(void) { int i; for (i = NFPROTO_UNSPEC; i < NFPROTO_NUMPROTO; i++) { snprintf(nf_log_sysctl_fnames[i-NFPROTO_UNSPEC], 3, "%d", i); nf_log_sysctl_table[i].procname = nf_log_sysctl_fnames[i-NFPROTO_UNSPEC]; nf_log_sysctl_table[i].data = NULL; nf_log_sysctl_table[i].maxlen = NFLOGGER_NAME_LEN * sizeof(char); nf_log_sysctl_table[i].mode = 0644; nf_log_sysctl_table[i].proc_handler = nf_log_proc_dostring; nf_log_sysctl_table[i].extra1 = (void *)(unsigned long) i; } nf_log_dir_header = register_sysctl_paths(nf_log_sysctl_path, nf_log_sysctl_table); if (!nf_log_dir_header) return -ENOMEM; return 0; } #else static __init int netfilter_log_sysctl_init(void) { return 0; } #endif /* CONFIG_SYSCTL */ int __init netfilter_log_init(void) { int i, r; #ifdef CONFIG_PROC_FS if (!proc_create("nf_log", S_IRUGO, proc_net_netfilter, &nflog_file_ops)) return -1; #endif /* Errors will trigger panic, unroll on error is unnecessary. */ r = netfilter_log_sysctl_init(); if (r < 0) return r; for (i = NFPROTO_UNSPEC; i < NFPROTO_NUMPROTO; i++) INIT_LIST_HEAD(&(nf_loggers_l[i])); return 0; }
gpl-2.0
3EleVen/android_kernel_motorola_ghost
net/netfilter/nf_log.c
4607
7370
#include <linux/kernel.h> #include <linux/init.h> #include <linux/module.h> #include <linux/proc_fs.h> #include <linux/skbuff.h> #include <linux/netfilter.h> #include <linux/seq_file.h> #include <net/protocol.h> #include <net/netfilter/nf_log.h> #include "nf_internals.h" /* Internal logging interface, which relies on the real LOG target modules */ #define NF_LOG_PREFIXLEN 128 #define NFLOGGER_NAME_LEN 64 static const struct nf_logger __rcu *nf_loggers[NFPROTO_NUMPROTO] __read_mostly; static struct list_head nf_loggers_l[NFPROTO_NUMPROTO] __read_mostly; static DEFINE_MUTEX(nf_log_mutex); static struct nf_logger *__find_logger(int pf, const char *str_logger) { struct nf_logger *t; list_for_each_entry(t, &nf_loggers_l[pf], list[pf]) { if (!strnicmp(str_logger, t->name, strlen(t->name))) return t; } return NULL; } /* return EEXIST if the same logger is registred, 0 on success. */ int nf_log_register(u_int8_t pf, struct nf_logger *logger) { const struct nf_logger *llog; int i; if (pf >= ARRAY_SIZE(nf_loggers)) return -EINVAL; for (i = 0; i < ARRAY_SIZE(logger->list); i++) INIT_LIST_HEAD(&logger->list[i]); mutex_lock(&nf_log_mutex); if (pf == NFPROTO_UNSPEC) { for (i = NFPROTO_UNSPEC; i < NFPROTO_NUMPROTO; i++) list_add_tail(&(logger->list[i]), &(nf_loggers_l[i])); } else { /* register at end of list to honor first register win */ list_add_tail(&logger->list[pf], &nf_loggers_l[pf]); llog = rcu_dereference_protected(nf_loggers[pf], lockdep_is_held(&nf_log_mutex)); if (llog == NULL) rcu_assign_pointer(nf_loggers[pf], logger); } mutex_unlock(&nf_log_mutex); return 0; } EXPORT_SYMBOL(nf_log_register); void nf_log_unregister(struct nf_logger *logger) { const struct nf_logger *c_logger; int i; mutex_lock(&nf_log_mutex); for (i = 0; i < ARRAY_SIZE(nf_loggers); i++) { c_logger = rcu_dereference_protected(nf_loggers[i], lockdep_is_held(&nf_log_mutex)); if (c_logger == logger) RCU_INIT_POINTER(nf_loggers[i], NULL); list_del(&logger->list[i]); } mutex_unlock(&nf_log_mutex); synchronize_rcu(); } EXPORT_SYMBOL(nf_log_unregister); int nf_log_bind_pf(u_int8_t pf, const struct nf_logger *logger) { if (pf >= ARRAY_SIZE(nf_loggers)) return -EINVAL; mutex_lock(&nf_log_mutex); if (__find_logger(pf, logger->name) == NULL) { mutex_unlock(&nf_log_mutex); return -ENOENT; } rcu_assign_pointer(nf_loggers[pf], logger); mutex_unlock(&nf_log_mutex); return 0; } EXPORT_SYMBOL(nf_log_bind_pf); void nf_log_unbind_pf(u_int8_t pf) { if (pf >= ARRAY_SIZE(nf_loggers)) return; mutex_lock(&nf_log_mutex); RCU_INIT_POINTER(nf_loggers[pf], NULL); mutex_unlock(&nf_log_mutex); } EXPORT_SYMBOL(nf_log_unbind_pf); void nf_log_packet(u_int8_t pf, unsigned int hooknum, const struct sk_buff *skb, const struct net_device *in, const struct net_device *out, const struct nf_loginfo *loginfo, const char *fmt, ...) { va_list args; char prefix[NF_LOG_PREFIXLEN]; const struct nf_logger *logger; rcu_read_lock(); logger = rcu_dereference(nf_loggers[pf]); if (logger) { va_start(args, fmt); vsnprintf(prefix, sizeof(prefix), fmt, args); va_end(args); logger->logfn(pf, hooknum, skb, in, out, loginfo, prefix); } rcu_read_unlock(); } EXPORT_SYMBOL(nf_log_packet); #ifdef CONFIG_PROC_FS static void *seq_start(struct seq_file *seq, loff_t *pos) { mutex_lock(&nf_log_mutex); if (*pos >= ARRAY_SIZE(nf_loggers)) return NULL; return pos; } static void *seq_next(struct seq_file *s, void *v, loff_t *pos) { (*pos)++; if (*pos >= ARRAY_SIZE(nf_loggers)) return NULL; return pos; } static void seq_stop(struct seq_file *s, void *v) { mutex_unlock(&nf_log_mutex); } static int seq_show(struct seq_file *s, void *v) { loff_t *pos = v; const struct nf_logger *logger; struct nf_logger *t; int ret; logger = rcu_dereference_protected(nf_loggers[*pos], lockdep_is_held(&nf_log_mutex)); if (!logger) ret = seq_printf(s, "%2lld NONE (", *pos); else ret = seq_printf(s, "%2lld %s (", *pos, logger->name); if (ret < 0) return ret; list_for_each_entry(t, &nf_loggers_l[*pos], list[*pos]) { ret = seq_printf(s, "%s", t->name); if (ret < 0) return ret; if (&t->list[*pos] != nf_loggers_l[*pos].prev) { ret = seq_printf(s, ","); if (ret < 0) return ret; } } return seq_printf(s, ")\n"); } static const struct seq_operations nflog_seq_ops = { .start = seq_start, .next = seq_next, .stop = seq_stop, .show = seq_show, }; static int nflog_open(struct inode *inode, struct file *file) { return seq_open(file, &nflog_seq_ops); } static const struct file_operations nflog_file_ops = { .owner = THIS_MODULE, .open = nflog_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release, }; #endif /* PROC_FS */ #ifdef CONFIG_SYSCTL static struct ctl_path nf_log_sysctl_path[] = { { .procname = "net", }, { .procname = "netfilter", }, { .procname = "nf_log", }, { } }; static char nf_log_sysctl_fnames[NFPROTO_NUMPROTO-NFPROTO_UNSPEC][3]; static struct ctl_table nf_log_sysctl_table[NFPROTO_NUMPROTO+1]; static struct ctl_table_header *nf_log_dir_header; static int nf_log_proc_dostring(ctl_table *table, int write, void __user *buffer, size_t *lenp, loff_t *ppos) { const struct nf_logger *logger; char buf[NFLOGGER_NAME_LEN]; size_t size = *lenp; int r = 0; int tindex = (unsigned long)table->extra1; if (write) { if (size > sizeof(buf)) size = sizeof(buf); if (copy_from_user(buf, buffer, size)) return -EFAULT; if (!strcmp(buf, "NONE")) { nf_log_unbind_pf(tindex); return 0; } mutex_lock(&nf_log_mutex); logger = __find_logger(tindex, buf); if (logger == NULL) { mutex_unlock(&nf_log_mutex); return -ENOENT; } rcu_assign_pointer(nf_loggers[tindex], logger); mutex_unlock(&nf_log_mutex); } else { mutex_lock(&nf_log_mutex); logger = rcu_dereference_protected(nf_loggers[tindex], lockdep_is_held(&nf_log_mutex)); if (!logger) table->data = "NONE"; else table->data = logger->name; r = proc_dostring(table, write, buffer, lenp, ppos); mutex_unlock(&nf_log_mutex); } return r; } static __init int netfilter_log_sysctl_init(void) { int i; for (i = NFPROTO_UNSPEC; i < NFPROTO_NUMPROTO; i++) { snprintf(nf_log_sysctl_fnames[i-NFPROTO_UNSPEC], 3, "%d", i); nf_log_sysctl_table[i].procname = nf_log_sysctl_fnames[i-NFPROTO_UNSPEC]; nf_log_sysctl_table[i].data = NULL; nf_log_sysctl_table[i].maxlen = NFLOGGER_NAME_LEN * sizeof(char); nf_log_sysctl_table[i].mode = 0644; nf_log_sysctl_table[i].proc_handler = nf_log_proc_dostring; nf_log_sysctl_table[i].extra1 = (void *)(unsigned long) i; } nf_log_dir_header = register_sysctl_paths(nf_log_sysctl_path, nf_log_sysctl_table); if (!nf_log_dir_header) return -ENOMEM; return 0; } #else static __init int netfilter_log_sysctl_init(void) { return 0; } #endif /* CONFIG_SYSCTL */ int __init netfilter_log_init(void) { int i, r; #ifdef CONFIG_PROC_FS if (!proc_create("nf_log", S_IRUGO, proc_net_netfilter, &nflog_file_ops)) return -1; #endif /* Errors will trigger panic, unroll on error is unnecessary. */ r = netfilter_log_sysctl_init(); if (r < 0) return r; for (i = NFPROTO_UNSPEC; i < NFPROTO_NUMPROTO; i++) INIT_LIST_HEAD(&(nf_loggers_l[i])); return 0; }
gpl-2.0
Troj80/android_kernel_htc_vivo
arch/arm/mach-pxa/palmte2.c
4863
9869
/* * Hardware definitions for Palm Tungsten|E2 * * Author: * Carlos Eduardo Medaglia Dyonisio <cadu@nerdfeliz.com> * * Rewrite for mainline: * Marek Vasut <marek.vasut@gmail.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. * * (find more info at www.hackndev.com) * */ #include <linux/platform_device.h> #include <linux/delay.h> #include <linux/irq.h> #include <linux/gpio_keys.h> #include <linux/input.h> #include <linux/pda_power.h> #include <linux/pwm_backlight.h> #include <linux/gpio.h> #include <linux/wm97xx.h> #include <linux/power_supply.h> #include <linux/usb/gpio_vbus.h> #include <asm/mach-types.h> #include <asm/mach/arch.h> #include <asm/mach/map.h> #include <mach/pxa25x.h> #include <mach/audio.h> #include <mach/palmte2.h> #include <mach/mmc.h> #include <mach/pxafb.h> #include <mach/irda.h> #include <mach/udc.h> #include <mach/palmasoc.h> #include "generic.h" #include "devices.h" /****************************************************************************** * Pin configuration ******************************************************************************/ static unsigned long palmte2_pin_config[] __initdata = { /* MMC */ GPIO6_MMC_CLK, GPIO8_MMC_CS0, GPIO10_GPIO, /* SD detect */ GPIO55_GPIO, /* SD power */ GPIO51_GPIO, /* SD r/o switch */ /* AC97 */ GPIO28_AC97_BITCLK, GPIO29_AC97_SDATA_IN_0, GPIO30_AC97_SDATA_OUT, GPIO31_AC97_SYNC, /* PWM */ GPIO16_PWM0_OUT, /* USB */ GPIO15_GPIO, /* usb detect */ GPIO53_GPIO, /* usb power */ /* IrDA */ GPIO48_GPIO, /* ir disable */ GPIO46_FICP_RXD, GPIO47_FICP_TXD, /* LCD */ GPIOxx_LCD_TFT_16BPP, /* GPIO KEYS */ GPIO5_GPIO, /* notes */ GPIO7_GPIO, /* tasks */ GPIO11_GPIO, /* calendar */ GPIO13_GPIO, /* contacts */ GPIO14_GPIO, /* center */ GPIO19_GPIO, /* left */ GPIO20_GPIO, /* right */ GPIO21_GPIO, /* down */ GPIO22_GPIO, /* up */ /* MISC */ GPIO1_RST, /* reset */ GPIO4_GPIO, /* Hotsync button */ GPIO9_GPIO, /* power detect */ GPIO15_GPIO, /* earphone detect */ GPIO37_GPIO, /* LCD power */ GPIO56_GPIO, /* Backlight power */ }; /****************************************************************************** * SD/MMC card controller ******************************************************************************/ static struct pxamci_platform_data palmte2_mci_platform_data = { .ocr_mask = MMC_VDD_32_33 | MMC_VDD_33_34, .gpio_card_detect = GPIO_NR_PALMTE2_SD_DETECT_N, .gpio_card_ro = GPIO_NR_PALMTE2_SD_READONLY, .gpio_power = GPIO_NR_PALMTE2_SD_POWER, }; /****************************************************************************** * GPIO keys ******************************************************************************/ static struct gpio_keys_button palmte2_pxa_buttons[] = { {KEY_F1, GPIO_NR_PALMTE2_KEY_CONTACTS, 1, "Contacts" }, {KEY_F2, GPIO_NR_PALMTE2_KEY_CALENDAR, 1, "Calendar" }, {KEY_F3, GPIO_NR_PALMTE2_KEY_TASKS, 1, "Tasks" }, {KEY_F4, GPIO_NR_PALMTE2_KEY_NOTES, 1, "Notes" }, {KEY_ENTER, GPIO_NR_PALMTE2_KEY_CENTER, 1, "Center" }, {KEY_LEFT, GPIO_NR_PALMTE2_KEY_LEFT, 1, "Left" }, {KEY_RIGHT, GPIO_NR_PALMTE2_KEY_RIGHT, 1, "Right" }, {KEY_DOWN, GPIO_NR_PALMTE2_KEY_DOWN, 1, "Down" }, {KEY_UP, GPIO_NR_PALMTE2_KEY_UP, 1, "Up" }, }; static struct gpio_keys_platform_data palmte2_pxa_keys_data = { .buttons = palmte2_pxa_buttons, .nbuttons = ARRAY_SIZE(palmte2_pxa_buttons), }; static struct platform_device palmte2_pxa_keys = { .name = "gpio-keys", .id = -1, .dev = { .platform_data = &palmte2_pxa_keys_data, }, }; /****************************************************************************** * Backlight ******************************************************************************/ static struct gpio palmte_bl_gpios[] = { { GPIO_NR_PALMTE2_BL_POWER, GPIOF_INIT_LOW, "Backlight power" }, { GPIO_NR_PALMTE2_LCD_POWER, GPIOF_INIT_LOW, "LCD power" }, }; static int palmte2_backlight_init(struct device *dev) { return gpio_request_array(ARRAY_AND_SIZE(palmte_bl_gpios)); } static int palmte2_backlight_notify(struct device *dev, int brightness) { gpio_set_value(GPIO_NR_PALMTE2_BL_POWER, brightness); gpio_set_value(GPIO_NR_PALMTE2_LCD_POWER, brightness); return brightness; } static void palmte2_backlight_exit(struct device *dev) { gpio_free_array(ARRAY_AND_SIZE(palmte_bl_gpios)); } static struct platform_pwm_backlight_data palmte2_backlight_data = { .pwm_id = 0, .max_brightness = PALMTE2_MAX_INTENSITY, .dft_brightness = PALMTE2_MAX_INTENSITY, .pwm_period_ns = PALMTE2_PERIOD_NS, .init = palmte2_backlight_init, .notify = palmte2_backlight_notify, .exit = palmte2_backlight_exit, }; static struct platform_device palmte2_backlight = { .name = "pwm-backlight", .dev = { .parent = &pxa25x_device_pwm0.dev, .platform_data = &palmte2_backlight_data, }, }; /****************************************************************************** * IrDA ******************************************************************************/ static struct pxaficp_platform_data palmte2_ficp_platform_data = { .gpio_pwdown = GPIO_NR_PALMTE2_IR_DISABLE, .transceiver_cap = IR_SIRMODE | IR_OFF, }; /****************************************************************************** * UDC ******************************************************************************/ static struct gpio_vbus_mach_info palmte2_udc_info = { .gpio_vbus = GPIO_NR_PALMTE2_USB_DETECT_N, .gpio_vbus_inverted = 1, .gpio_pullup = GPIO_NR_PALMTE2_USB_PULLUP, }; static struct platform_device palmte2_gpio_vbus = { .name = "gpio-vbus", .id = -1, .dev = { .platform_data = &palmte2_udc_info, }, }; /****************************************************************************** * Power supply ******************************************************************************/ static int power_supply_init(struct device *dev) { int ret; ret = gpio_request(GPIO_NR_PALMTE2_POWER_DETECT, "CABLE_STATE_AC"); if (ret) goto err1; ret = gpio_direction_input(GPIO_NR_PALMTE2_POWER_DETECT); if (ret) goto err2; return 0; err2: gpio_free(GPIO_NR_PALMTE2_POWER_DETECT); err1: return ret; } static int palmte2_is_ac_online(void) { return gpio_get_value(GPIO_NR_PALMTE2_POWER_DETECT); } static void power_supply_exit(struct device *dev) { gpio_free(GPIO_NR_PALMTE2_POWER_DETECT); } static char *palmte2_supplicants[] = { "main-battery", }; static struct pda_power_pdata power_supply_info = { .init = power_supply_init, .is_ac_online = palmte2_is_ac_online, .exit = power_supply_exit, .supplied_to = palmte2_supplicants, .num_supplicants = ARRAY_SIZE(palmte2_supplicants), }; static struct platform_device power_supply = { .name = "pda-power", .id = -1, .dev = { .platform_data = &power_supply_info, }, }; /****************************************************************************** * WM97xx audio, battery ******************************************************************************/ static struct wm97xx_batt_pdata palmte2_batt_pdata = { .batt_aux = WM97XX_AUX_ID3, .temp_aux = WM97XX_AUX_ID2, .charge_gpio = -1, .max_voltage = PALMTE2_BAT_MAX_VOLTAGE, .min_voltage = PALMTE2_BAT_MIN_VOLTAGE, .batt_mult = 1000, .batt_div = 414, .temp_mult = 1, .temp_div = 1, .batt_tech = POWER_SUPPLY_TECHNOLOGY_LIPO, .batt_name = "main-batt", }; static struct wm97xx_pdata palmte2_wm97xx_pdata = { .batt_pdata = &palmte2_batt_pdata, }; static pxa2xx_audio_ops_t palmte2_ac97_pdata = { .codec_pdata = { &palmte2_wm97xx_pdata, }, }; static struct palm27x_asoc_info palmte2_asoc_pdata = { .jack_gpio = GPIO_NR_PALMTE2_EARPHONE_DETECT, }; static struct platform_device palmte2_asoc = { .name = "palm27x-asoc", .id = -1, .dev = { .platform_data = &palmte2_asoc_pdata, }, }; /****************************************************************************** * Framebuffer ******************************************************************************/ static struct pxafb_mode_info palmte2_lcd_modes[] = { { .pixclock = 77757, .xres = 320, .yres = 320, .bpp = 16, .left_margin = 28, .right_margin = 7, .upper_margin = 7, .lower_margin = 5, .hsync_len = 4, .vsync_len = 1, }, }; static struct pxafb_mach_info palmte2_lcd_screen = { .modes = palmte2_lcd_modes, .num_modes = ARRAY_SIZE(palmte2_lcd_modes), .lcd_conn = LCD_COLOR_TFT_16BPP | LCD_PCLK_EDGE_FALL, }; /****************************************************************************** * Machine init ******************************************************************************/ static struct platform_device *devices[] __initdata = { #if defined(CONFIG_KEYBOARD_GPIO) || defined(CONFIG_KEYBOARD_GPIO_MODULE) &palmte2_pxa_keys, #endif &palmte2_backlight, &power_supply, &palmte2_asoc, &palmte2_gpio_vbus, }; /* setup udc GPIOs initial state */ static void __init palmte2_udc_init(void) { if (!gpio_request(GPIO_NR_PALMTE2_USB_PULLUP, "UDC Vbus")) { gpio_direction_output(GPIO_NR_PALMTE2_USB_PULLUP, 1); gpio_free(GPIO_NR_PALMTE2_USB_PULLUP); } } static void __init palmte2_init(void) { pxa2xx_mfp_config(ARRAY_AND_SIZE(palmte2_pin_config)); pxa_set_ffuart_info(NULL); pxa_set_btuart_info(NULL); pxa_set_stuart_info(NULL); pxa_set_fb_info(NULL, &palmte2_lcd_screen); pxa_set_mci_info(&palmte2_mci_platform_data); palmte2_udc_init(); pxa_set_ac97_info(&palmte2_ac97_pdata); pxa_set_ficp_info(&palmte2_ficp_platform_data); platform_add_devices(devices, ARRAY_SIZE(devices)); } MACHINE_START(PALMTE2, "Palm Tungsten|E2") .atag_offset = 0x100, .map_io = pxa25x_map_io, .nr_irqs = PXA_NR_IRQS, .init_irq = pxa25x_init_irq, .handle_irq = pxa25x_handle_irq, .timer = &pxa_timer, .init_machine = palmte2_init, .restart = pxa_restart, MACHINE_END
gpl-2.0
brymaster5000/m7_4.1
arch/arm/mach-pxa/palmtreo.c
4863
11548
/* * Hardware definitions for Palm Treo smartphones * * currently supported: * Palm Treo 680 (GSM) * Palm Centro 685 (GSM) * * Author: Tomas Cech <sleep_walker@suse.cz> * * 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. * * (find more info at www.hackndev.com) * */ #include <linux/platform_device.h> #include <linux/delay.h> #include <linux/irq.h> #include <linux/gpio_keys.h> #include <linux/input.h> #include <linux/memblock.h> #include <linux/pda_power.h> #include <linux/pwm_backlight.h> #include <linux/gpio.h> #include <linux/power_supply.h> #include <linux/w1-gpio.h> #include <asm/mach-types.h> #include <asm/mach/arch.h> #include <asm/mach/map.h> #include <mach/pxa27x.h> #include <mach/pxa27x-udc.h> #include <mach/audio.h> #include <mach/palmtreo.h> #include <mach/mmc.h> #include <mach/pxafb.h> #include <mach/irda.h> #include <plat/pxa27x_keypad.h> #include <mach/udc.h> #include <mach/ohci.h> #include <mach/pxa2xx-regs.h> #include <mach/palmasoc.h> #include <mach/camera.h> #include <mach/palm27x.h> #include <sound/pxa2xx-lib.h> #include "generic.h" #include "devices.h" /****************************************************************************** * Pin configuration ******************************************************************************/ static unsigned long treo_pin_config[] __initdata = { /* MMC */ GPIO32_MMC_CLK, GPIO92_MMC_DAT_0, GPIO109_MMC_DAT_1, GPIO110_MMC_DAT_2, GPIO111_MMC_DAT_3, GPIO112_MMC_CMD, GPIO113_GPIO, /* SD detect */ /* AC97 */ GPIO28_AC97_BITCLK, GPIO29_AC97_SDATA_IN_0, GPIO30_AC97_SDATA_OUT, GPIO31_AC97_SYNC, GPIO89_AC97_SYSCLK, GPIO95_AC97_nRESET, /* IrDA */ GPIO46_FICP_RXD, GPIO47_FICP_TXD, /* PWM */ GPIO16_PWM0_OUT, /* USB */ GPIO1_GPIO | WAKEUP_ON_EDGE_BOTH, /* usb detect */ /* MATRIX KEYPAD */ GPIO101_KP_MKIN_1, GPIO102_KP_MKIN_2, GPIO97_KP_MKIN_3, GPIO98_KP_MKIN_4, GPIO91_KP_MKIN_6, GPIO13_KP_MKIN_7, GPIO103_KP_MKOUT_0 | MFP_LPM_DRIVE_HIGH, GPIO104_KP_MKOUT_1, GPIO105_KP_MKOUT_2, GPIO106_KP_MKOUT_3, GPIO107_KP_MKOUT_4, GPIO108_KP_MKOUT_5, GPIO96_KP_MKOUT_6, GPIO93_KP_DKIN_0 | WAKEUP_ON_LEVEL_HIGH, /* Hotsync button */ /* LCD */ GPIOxx_LCD_TFT_16BPP, /* Quick Capture Interface */ GPIO84_CIF_FV, GPIO85_CIF_LV, GPIO53_CIF_MCLK, GPIO54_CIF_PCLK, GPIO81_CIF_DD_0, GPIO55_CIF_DD_1, GPIO51_CIF_DD_2, GPIO50_CIF_DD_3, GPIO52_CIF_DD_4, GPIO48_CIF_DD_5, GPIO17_CIF_DD_6, GPIO12_CIF_DD_7, /* I2C */ GPIO117_I2C_SCL, GPIO118_I2C_SDA, /* GSM */ GPIO14_GPIO | WAKEUP_ON_EDGE_BOTH, /* GSM host wake up */ GPIO34_FFUART_RXD, GPIO35_FFUART_CTS, GPIO39_FFUART_TXD, GPIO41_FFUART_RTS, /* MISC. */ GPIO0_GPIO | WAKEUP_ON_EDGE_BOTH, /* external power detect */ GPIO15_GPIO | WAKEUP_ON_EDGE_BOTH, /* silent switch */ GPIO116_GPIO, /* headphone detect */ GPIO11_GPIO | WAKEUP_ON_EDGE_BOTH, /* bluetooth host wake up */ }; #ifdef CONFIG_MACH_TREO680 static unsigned long treo680_pin_config[] __initdata = { GPIO33_GPIO, /* SD read only */ /* MATRIX KEYPAD - different wake up source */ GPIO100_KP_MKIN_0 | WAKEUP_ON_LEVEL_HIGH, GPIO99_KP_MKIN_5, }; #endif /* CONFIG_MACH_TREO680 */ #ifdef CONFIG_MACH_CENTRO static unsigned long centro685_pin_config[] __initdata = { /* Bluetooth attached to BT UART*/ MFP_CFG_OUT(GPIO80, AF0, DRIVE_LOW), /* power: LOW = off */ GPIO42_BTUART_RXD, GPIO43_BTUART_TXD, GPIO44_BTUART_CTS, GPIO45_BTUART_RTS, /* MATRIX KEYPAD - different wake up source */ GPIO100_KP_MKIN_0, GPIO99_KP_MKIN_5 | WAKEUP_ON_LEVEL_HIGH, }; #endif /* CONFIG_MACH_CENTRO */ /****************************************************************************** * GPIO keyboard ******************************************************************************/ #if defined(CONFIG_KEYBOARD_PXA27x) || defined(CONFIG_KEYBOARD_PXA27x_MODULE) static unsigned int treo680_matrix_keys[] = { KEY(0, 0, KEY_F8), /* Red/Off/Power */ KEY(0, 1, KEY_LEFT), KEY(0, 2, KEY_LEFTCTRL), /* Alternate */ KEY(0, 3, KEY_L), KEY(0, 4, KEY_A), KEY(0, 5, KEY_Q), KEY(0, 6, KEY_P), KEY(1, 0, KEY_RIGHTCTRL), /* Menu */ KEY(1, 1, KEY_RIGHT), KEY(1, 2, KEY_LEFTSHIFT), /* Left shift */ KEY(1, 3, KEY_Z), KEY(1, 4, KEY_S), KEY(1, 5, KEY_W), KEY(2, 0, KEY_F1), /* Phone */ KEY(2, 1, KEY_UP), KEY(2, 2, KEY_0), KEY(2, 3, KEY_X), KEY(2, 4, KEY_D), KEY(2, 5, KEY_E), KEY(3, 0, KEY_F10), /* Calendar */ KEY(3, 1, KEY_DOWN), KEY(3, 2, KEY_SPACE), KEY(3, 3, KEY_C), KEY(3, 4, KEY_F), KEY(3, 5, KEY_R), KEY(4, 0, KEY_F12), /* Mail */ KEY(4, 1, KEY_KPENTER), KEY(4, 2, KEY_RIGHTALT), /* Alt */ KEY(4, 3, KEY_V), KEY(4, 4, KEY_G), KEY(4, 5, KEY_T), KEY(5, 0, KEY_F9), /* Home */ KEY(5, 1, KEY_PAGEUP), /* Side up */ KEY(5, 2, KEY_DOT), KEY(5, 3, KEY_B), KEY(5, 4, KEY_H), KEY(5, 5, KEY_Y), KEY(6, 0, KEY_TAB), /* Side Activate */ KEY(6, 1, KEY_PAGEDOWN), /* Side down */ KEY(6, 2, KEY_ENTER), KEY(6, 3, KEY_N), KEY(6, 4, KEY_J), KEY(6, 5, KEY_U), KEY(7, 0, KEY_F6), /* Green/Call */ KEY(7, 1, KEY_O), KEY(7, 2, KEY_BACKSPACE), KEY(7, 3, KEY_M), KEY(7, 4, KEY_K), KEY(7, 5, KEY_I), }; static unsigned int centro_matrix_keys[] = { KEY(0, 0, KEY_F9), /* Home */ KEY(0, 1, KEY_LEFT), KEY(0, 2, KEY_LEFTCTRL), /* Alternate */ KEY(0, 3, KEY_L), KEY(0, 4, KEY_A), KEY(0, 5, KEY_Q), KEY(0, 6, KEY_P), KEY(1, 0, KEY_RIGHTCTRL), /* Menu */ KEY(1, 1, KEY_RIGHT), KEY(1, 2, KEY_LEFTSHIFT), /* Left shift */ KEY(1, 3, KEY_Z), KEY(1, 4, KEY_S), KEY(1, 5, KEY_W), KEY(2, 0, KEY_F1), /* Phone */ KEY(2, 1, KEY_UP), KEY(2, 2, KEY_0), KEY(2, 3, KEY_X), KEY(2, 4, KEY_D), KEY(2, 5, KEY_E), KEY(3, 0, KEY_F10), /* Calendar */ KEY(3, 1, KEY_DOWN), KEY(3, 2, KEY_SPACE), KEY(3, 3, KEY_C), KEY(3, 4, KEY_F), KEY(3, 5, KEY_R), KEY(4, 0, KEY_F12), /* Mail */ KEY(4, 1, KEY_KPENTER), KEY(4, 2, KEY_RIGHTALT), /* Alt */ KEY(4, 3, KEY_V), KEY(4, 4, KEY_G), KEY(4, 5, KEY_T), KEY(5, 0, KEY_F8), /* Red/Off/Power */ KEY(5, 1, KEY_PAGEUP), /* Side up */ KEY(5, 2, KEY_DOT), KEY(5, 3, KEY_B), KEY(5, 4, KEY_H), KEY(5, 5, KEY_Y), KEY(6, 0, KEY_TAB), /* Side Activate */ KEY(6, 1, KEY_PAGEDOWN), /* Side down */ KEY(6, 2, KEY_ENTER), KEY(6, 3, KEY_N), KEY(6, 4, KEY_J), KEY(6, 5, KEY_U), KEY(7, 0, KEY_F6), /* Green/Call */ KEY(7, 1, KEY_O), KEY(7, 2, KEY_BACKSPACE), KEY(7, 3, KEY_M), KEY(7, 4, KEY_K), KEY(7, 5, KEY_I), }; static struct pxa27x_keypad_platform_data treo680_keypad_pdata = { .matrix_key_rows = 8, .matrix_key_cols = 7, .matrix_key_map = treo680_matrix_keys, .matrix_key_map_size = ARRAY_SIZE(treo680_matrix_keys), .direct_key_map = { KEY_CONNECT }, .direct_key_num = 1, .debounce_interval = 30, }; static void __init palmtreo_kpc_init(void) { static struct pxa27x_keypad_platform_data *data = &treo680_keypad_pdata; if (machine_is_centro()) { data->matrix_key_map = centro_matrix_keys; data->matrix_key_map_size = ARRAY_SIZE(centro_matrix_keys); } pxa_set_keypad_info(&treo680_keypad_pdata); } #else static inline void palmtreo_kpc_init(void) {} #endif /****************************************************************************** * USB host ******************************************************************************/ #if defined(CONFIG_USB_OHCI_HCD) || defined(CONFIG_USB_OHCI_HCD_MODULE) static struct pxaohci_platform_data treo680_ohci_info = { .port_mode = PMM_PERPORT_MODE, .flags = ENABLE_PORT1 | ENABLE_PORT3, .power_budget = 0, }; static void __init palmtreo_uhc_init(void) { if (machine_is_treo680()) pxa_set_ohci_info(&treo680_ohci_info); } #else static inline void palmtreo_uhc_init(void) {} #endif /****************************************************************************** * Vibra and LEDs ******************************************************************************/ #ifdef CONFIG_MACH_TREO680 static struct gpio_led treo680_gpio_leds[] = { { .name = "treo680:vibra:vibra", .default_trigger = "none", .gpio = GPIO_NR_TREO680_VIBRATE_EN, }, { .name = "treo680:green:led", .default_trigger = "mmc0", .gpio = GPIO_NR_TREO_GREEN_LED, }, { .name = "treo680:white:keybbl", .default_trigger = "none", .gpio = GPIO_NR_TREO680_KEYB_BL, }, }; static struct gpio_led_platform_data treo680_gpio_led_info = { .leds = treo680_gpio_leds, .num_leds = ARRAY_SIZE(treo680_gpio_leds), }; static struct gpio_led centro_gpio_leds[] = { { .name = "centro:vibra:vibra", .default_trigger = "none", .gpio = GPIO_NR_CENTRO_VIBRATE_EN, }, { .name = "centro:green:led", .default_trigger = "mmc0", .gpio = GPIO_NR_TREO_GREEN_LED, }, { .name = "centro:white:keybbl", .default_trigger = "none", .active_low = 1, .gpio = GPIO_NR_CENTRO_KEYB_BL, }, }; static struct gpio_led_platform_data centro_gpio_led_info = { .leds = centro_gpio_leds, .num_leds = ARRAY_SIZE(centro_gpio_leds), }; static struct platform_device palmtreo_leds = { .name = "leds-gpio", .id = -1, .dev = { .platform_data = &treo680_gpio_led_info, } }; static void __init palmtreo_leds_init(void) { if (machine_is_centro()) palmtreo_leds.dev.platform_data = &centro_gpio_led_info; platform_device_register(&palmtreo_leds); } #else static inline void palmtreo_leds_init(void) {} #endif /****************************************************************************** * Machine init ******************************************************************************/ static void __init treo_reserve(void) { memblock_reserve(0xa0000000, 0x1000); memblock_reserve(0xa2000000, 0x1000); } static void __init palmphone_common_init(void) { pxa2xx_mfp_config(ARRAY_AND_SIZE(treo_pin_config)); pxa_set_ffuart_info(NULL); pxa_set_btuart_info(NULL); pxa_set_stuart_info(NULL); palm27x_pm_init(TREO_STR_BASE); palm27x_lcd_init(GPIO_NR_TREO_BL_POWER, &palm_320x320_new_lcd_mode); palm27x_udc_init(GPIO_NR_TREO_USB_DETECT, GPIO_NR_TREO_USB_PULLUP, 1); palm27x_irda_init(GPIO_NR_TREO_IR_EN); palm27x_ac97_init(-1, -1, -1, 95); palm27x_pwm_init(GPIO_NR_TREO_BL_POWER, -1); palm27x_power_init(GPIO_NR_TREO_POWER_DETECT, -1); palm27x_pmic_init(); palmtreo_kpc_init(); palmtreo_uhc_init(); palmtreo_leds_init(); } #ifdef CONFIG_MACH_TREO680 static void __init treo680_init(void) { pxa2xx_mfp_config(ARRAY_AND_SIZE(treo680_pin_config)); palmphone_common_init(); palm27x_mmc_init(GPIO_NR_TREO_SD_DETECT_N, GPIO_NR_TREO680_SD_READONLY, GPIO_NR_TREO680_SD_POWER, 0); } #endif #ifdef CONFIG_MACH_CENTRO static void __init centro_init(void) { pxa2xx_mfp_config(ARRAY_AND_SIZE(centro685_pin_config)); palmphone_common_init(); palm27x_mmc_init(GPIO_NR_TREO_SD_DETECT_N, -1, GPIO_NR_CENTRO_SD_POWER, 1); } #endif #ifdef CONFIG_MACH_TREO680 MACHINE_START(TREO680, "Palm Treo 680") .atag_offset = 0x100, .map_io = pxa27x_map_io, .reserve = treo_reserve, .nr_irqs = PXA_NR_IRQS, .init_irq = pxa27x_init_irq, .handle_irq = pxa27x_handle_irq, .timer = &pxa_timer, .init_machine = treo680_init, .restart = pxa_restart, MACHINE_END #endif #ifdef CONFIG_MACH_CENTRO MACHINE_START(CENTRO, "Palm Centro 685") .atag_offset = 0x100, .map_io = pxa27x_map_io, .reserve = treo_reserve, .nr_irqs = PXA_NR_IRQS, .init_irq = pxa27x_init_irq, .handle_irq = pxa27x_handle_irq, .timer = &pxa_timer, .init_machine = centro_init, .restart = pxa_restart, MACHINE_END #endif
gpl-2.0
BanBxda/GoogleEdition_4.3
drivers/media/video/ov2640.c
4863
31605
/* * ov2640 Camera Driver * * Copyright (C) 2010 Alberto Panizzo <maramaopercheseimorto@gmail.com> * * Based on ov772x, ov9640 drivers and previous non merged implementations. * * Copyright 2005-2009 Freescale Semiconductor, Inc. All Rights Reserved. * Copyright (C) 2006, OmniVision * * 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. */ #include <linux/init.h> #include <linux/module.h> #include <linux/i2c.h> #include <linux/slab.h> #include <linux/delay.h> #include <linux/v4l2-mediabus.h> #include <linux/videodev2.h> #include <media/soc_camera.h> #include <media/v4l2-chip-ident.h> #include <media/v4l2-subdev.h> #include <media/v4l2-ctrls.h> #define VAL_SET(x, mask, rshift, lshift) \ ((((x) >> rshift) & mask) << lshift) /* * DSP registers * register offset for BANK_SEL == BANK_SEL_DSP */ #define R_BYPASS 0x05 /* Bypass DSP */ #define R_BYPASS_DSP_BYPAS 0x01 /* Bypass DSP, sensor out directly */ #define R_BYPASS_USE_DSP 0x00 /* Use the internal DSP */ #define QS 0x44 /* Quantization Scale Factor */ #define CTRLI 0x50 #define CTRLI_LP_DP 0x80 #define CTRLI_ROUND 0x40 #define CTRLI_V_DIV_SET(x) VAL_SET(x, 0x3, 0, 3) #define CTRLI_H_DIV_SET(x) VAL_SET(x, 0x3, 0, 0) #define HSIZE 0x51 /* H_SIZE[7:0] (real/4) */ #define HSIZE_SET(x) VAL_SET(x, 0xFF, 2, 0) #define VSIZE 0x52 /* V_SIZE[7:0] (real/4) */ #define VSIZE_SET(x) VAL_SET(x, 0xFF, 2, 0) #define XOFFL 0x53 /* OFFSET_X[7:0] */ #define XOFFL_SET(x) VAL_SET(x, 0xFF, 0, 0) #define YOFFL 0x54 /* OFFSET_Y[7:0] */ #define YOFFL_SET(x) VAL_SET(x, 0xFF, 0, 0) #define VHYX 0x55 /* Offset and size completion */ #define VHYX_VSIZE_SET(x) VAL_SET(x, 0x1, (8+2), 7) #define VHYX_HSIZE_SET(x) VAL_SET(x, 0x1, (8+2), 3) #define VHYX_YOFF_SET(x) VAL_SET(x, 0x3, 8, 4) #define VHYX_XOFF_SET(x) VAL_SET(x, 0x3, 8, 0) #define DPRP 0x56 #define TEST 0x57 /* Horizontal size completion */ #define TEST_HSIZE_SET(x) VAL_SET(x, 0x1, (9+2), 7) #define ZMOW 0x5A /* Zoom: Out Width OUTW[7:0] (real/4) */ #define ZMOW_OUTW_SET(x) VAL_SET(x, 0xFF, 2, 0) #define ZMOH 0x5B /* Zoom: Out Height OUTH[7:0] (real/4) */ #define ZMOH_OUTH_SET(x) VAL_SET(x, 0xFF, 2, 0) #define ZMHH 0x5C /* Zoom: Speed and H&W completion */ #define ZMHH_ZSPEED_SET(x) VAL_SET(x, 0x0F, 0, 4) #define ZMHH_OUTH_SET(x) VAL_SET(x, 0x1, (8+2), 2) #define ZMHH_OUTW_SET(x) VAL_SET(x, 0x3, (8+2), 0) #define BPADDR 0x7C /* SDE Indirect Register Access: Address */ #define BPDATA 0x7D /* SDE Indirect Register Access: Data */ #define CTRL2 0x86 /* DSP Module enable 2 */ #define CTRL2_DCW_EN 0x20 #define CTRL2_SDE_EN 0x10 #define CTRL2_UV_ADJ_EN 0x08 #define CTRL2_UV_AVG_EN 0x04 #define CTRL2_CMX_EN 0x01 #define CTRL3 0x87 /* DSP Module enable 3 */ #define CTRL3_BPC_EN 0x80 #define CTRL3_WPC_EN 0x40 #define SIZEL 0x8C /* Image Size Completion */ #define SIZEL_HSIZE8_11_SET(x) VAL_SET(x, 0x1, 11, 6) #define SIZEL_HSIZE8_SET(x) VAL_SET(x, 0x7, 0, 3) #define SIZEL_VSIZE8_SET(x) VAL_SET(x, 0x7, 0, 0) #define HSIZE8 0xC0 /* Image Horizontal Size HSIZE[10:3] */ #define HSIZE8_SET(x) VAL_SET(x, 0xFF, 3, 0) #define VSIZE8 0xC1 /* Image Vertical Size VSIZE[10:3] */ #define VSIZE8_SET(x) VAL_SET(x, 0xFF, 3, 0) #define CTRL0 0xC2 /* DSP Module enable 0 */ #define CTRL0_AEC_EN 0x80 #define CTRL0_AEC_SEL 0x40 #define CTRL0_STAT_SEL 0x20 #define CTRL0_VFIRST 0x10 #define CTRL0_YUV422 0x08 #define CTRL0_YUV_EN 0x04 #define CTRL0_RGB_EN 0x02 #define CTRL0_RAW_EN 0x01 #define CTRL1 0xC3 /* DSP Module enable 1 */ #define CTRL1_CIP 0x80 #define CTRL1_DMY 0x40 #define CTRL1_RAW_GMA 0x20 #define CTRL1_DG 0x10 #define CTRL1_AWB 0x08 #define CTRL1_AWB_GAIN 0x04 #define CTRL1_LENC 0x02 #define CTRL1_PRE 0x01 #define R_DVP_SP 0xD3 /* DVP output speed control */ #define R_DVP_SP_AUTO_MODE 0x80 #define R_DVP_SP_DVP_MASK 0x3F /* DVP PCLK = sysclk (48)/[6:0] (YUV0); * = sysclk (48)/(2*[6:0]) (RAW);*/ #define IMAGE_MODE 0xDA /* Image Output Format Select */ #define IMAGE_MODE_Y8_DVP_EN 0x40 #define IMAGE_MODE_JPEG_EN 0x10 #define IMAGE_MODE_YUV422 0x00 #define IMAGE_MODE_RAW10 0x04 /* (DVP) */ #define IMAGE_MODE_RGB565 0x08 #define IMAGE_MODE_HREF_VSYNC 0x02 /* HREF timing select in DVP JPEG output * mode (0 for HREF is same as sensor) */ #define IMAGE_MODE_LBYTE_FIRST 0x01 /* Byte swap enable for DVP * 1: Low byte first UYVY (C2[4] =0) * VYUY (C2[4] =1) * 0: High byte first YUYV (C2[4]=0) * YVYU (C2[4] = 1) */ #define RESET 0xE0 /* Reset */ #define RESET_MICROC 0x40 #define RESET_SCCB 0x20 #define RESET_JPEG 0x10 #define RESET_DVP 0x04 #define RESET_IPU 0x02 #define RESET_CIF 0x01 #define REGED 0xED /* Register ED */ #define REGED_CLK_OUT_DIS 0x10 #define MS_SP 0xF0 /* SCCB Master Speed */ #define SS_ID 0xF7 /* SCCB Slave ID */ #define SS_CTRL 0xF8 /* SCCB Slave Control */ #define SS_CTRL_ADD_AUTO_INC 0x20 #define SS_CTRL_EN 0x08 #define SS_CTRL_DELAY_CLK 0x04 #define SS_CTRL_ACC_EN 0x02 #define SS_CTRL_SEN_PASS_THR 0x01 #define MC_BIST 0xF9 /* Microcontroller misc register */ #define MC_BIST_RESET 0x80 /* Microcontroller Reset */ #define MC_BIST_BOOT_ROM_SEL 0x40 #define MC_BIST_12KB_SEL 0x20 #define MC_BIST_12KB_MASK 0x30 #define MC_BIST_512KB_SEL 0x08 #define MC_BIST_512KB_MASK 0x0C #define MC_BIST_BUSY_BIT_R 0x02 #define MC_BIST_MC_RES_ONE_SH_W 0x02 #define MC_BIST_LAUNCH 0x01 #define BANK_SEL 0xFF /* Register Bank Select */ #define BANK_SEL_DSP 0x00 #define BANK_SEL_SENS 0x01 /* * Sensor registers * register offset for BANK_SEL == BANK_SEL_SENS */ #define GAIN 0x00 /* AGC - Gain control gain setting */ #define COM1 0x03 /* Common control 1 */ #define COM1_1_DUMMY_FR 0x40 #define COM1_3_DUMMY_FR 0x80 #define COM1_7_DUMMY_FR 0xC0 #define COM1_VWIN_LSB_UXGA 0x0F #define COM1_VWIN_LSB_SVGA 0x0A #define COM1_VWIN_LSB_CIF 0x06 #define REG04 0x04 /* Register 04 */ #define REG04_DEF 0x20 /* Always set */ #define REG04_HFLIP_IMG 0x80 /* Horizontal mirror image ON/OFF */ #define REG04_VFLIP_IMG 0x40 /* Vertical flip image ON/OFF */ #define REG04_VREF_EN 0x10 #define REG04_HREF_EN 0x08 #define REG04_AEC_SET(x) VAL_SET(x, 0x3, 0, 0) #define REG08 0x08 /* Frame Exposure One-pin Control Pre-charge Row Num */ #define COM2 0x09 /* Common control 2 */ #define COM2_SOFT_SLEEP_MODE 0x10 /* Soft sleep mode */ /* Output drive capability */ #define COM2_OCAP_Nx_SET(N) (((N) - 1) & 0x03) /* N = [1x .. 4x] */ #define PID 0x0A /* Product ID Number MSB */ #define VER 0x0B /* Product ID Number LSB */ #define COM3 0x0C /* Common control 3 */ #define COM3_BAND_50H 0x04 /* 0 For Banding at 60H */ #define COM3_BAND_AUTO 0x02 /* Auto Banding */ #define COM3_SING_FR_SNAPSH 0x01 /* 0 For enable live video output after the * snapshot sequence*/ #define AEC 0x10 /* AEC[9:2] Exposure Value */ #define CLKRC 0x11 /* Internal clock */ #define CLKRC_EN 0x80 #define CLKRC_DIV_SET(x) (((x) - 1) & 0x1F) /* CLK = XVCLK/(x) */ #define COM7 0x12 /* Common control 7 */ #define COM7_SRST 0x80 /* Initiates system reset. All registers are * set to factory default values after which * the chip resumes normal operation */ #define COM7_RES_UXGA 0x00 /* Resolution selectors for UXGA */ #define COM7_RES_SVGA 0x40 /* SVGA */ #define COM7_RES_CIF 0x20 /* CIF */ #define COM7_ZOOM_EN 0x04 /* Enable Zoom mode */ #define COM7_COLOR_BAR_TEST 0x02 /* Enable Color Bar Test Pattern */ #define COM8 0x13 /* Common control 8 */ #define COM8_DEF 0xC0 /* Banding filter ON/OFF */ #define COM8_BNDF_EN 0x20 /* Banding filter ON/OFF */ #define COM8_AGC_EN 0x04 /* AGC Auto/Manual control selection */ #define COM8_AEC_EN 0x01 /* Auto/Manual Exposure control */ #define COM9 0x14 /* Common control 9 * Automatic gain ceiling - maximum AGC value [7:5]*/ #define COM9_AGC_GAIN_2x 0x00 /* 000 : 2x */ #define COM9_AGC_GAIN_4x 0x20 /* 001 : 4x */ #define COM9_AGC_GAIN_8x 0x40 /* 010 : 8x */ #define COM9_AGC_GAIN_16x 0x60 /* 011 : 16x */ #define COM9_AGC_GAIN_32x 0x80 /* 100 : 32x */ #define COM9_AGC_GAIN_64x 0xA0 /* 101 : 64x */ #define COM9_AGC_GAIN_128x 0xC0 /* 110 : 128x */ #define COM10 0x15 /* Common control 10 */ #define COM10_PCLK_HREF 0x20 /* PCLK output qualified by HREF */ #define COM10_PCLK_RISE 0x10 /* Data is updated at the rising edge of * PCLK (user can latch data at the next * falling edge of PCLK). * 0 otherwise. */ #define COM10_HREF_INV 0x08 /* Invert HREF polarity: * HREF negative for valid data*/ #define COM10_VSINC_INV 0x02 /* Invert VSYNC polarity */ #define HSTART 0x17 /* Horizontal Window start MSB 8 bit */ #define HEND 0x18 /* Horizontal Window end MSB 8 bit */ #define VSTART 0x19 /* Vertical Window start MSB 8 bit */ #define VEND 0x1A /* Vertical Window end MSB 8 bit */ #define MIDH 0x1C /* Manufacturer ID byte - high */ #define MIDL 0x1D /* Manufacturer ID byte - low */ #define AEW 0x24 /* AGC/AEC - Stable operating region (upper limit) */ #define AEB 0x25 /* AGC/AEC - Stable operating region (lower limit) */ #define VV 0x26 /* AGC/AEC Fast mode operating region */ #define VV_HIGH_TH_SET(x) VAL_SET(x, 0xF, 0, 4) #define VV_LOW_TH_SET(x) VAL_SET(x, 0xF, 0, 0) #define REG2A 0x2A /* Dummy pixel insert MSB */ #define FRARL 0x2B /* Dummy pixel insert LSB */ #define ADDVFL 0x2D /* LSB of insert dummy lines in Vertical direction */ #define ADDVFH 0x2E /* MSB of insert dummy lines in Vertical direction */ #define YAVG 0x2F /* Y/G Channel Average value */ #define REG32 0x32 /* Common Control 32 */ #define REG32_PCLK_DIV_2 0x80 /* PCLK freq divided by 2 */ #define REG32_PCLK_DIV_4 0xC0 /* PCLK freq divided by 4 */ #define ARCOM2 0x34 /* Zoom: Horizontal start point */ #define REG45 0x45 /* Register 45 */ #define FLL 0x46 /* Frame Length Adjustment LSBs */ #define FLH 0x47 /* Frame Length Adjustment MSBs */ #define COM19 0x48 /* Zoom: Vertical start point */ #define ZOOMS 0x49 /* Zoom: Vertical start point */ #define COM22 0x4B /* Flash light control */ #define COM25 0x4E /* For Banding operations */ #define BD50 0x4F /* 50Hz Banding AEC 8 LSBs */ #define BD60 0x50 /* 60Hz Banding AEC 8 LSBs */ #define REG5D 0x5D /* AVGsel[7:0], 16-zone average weight option */ #define REG5E 0x5E /* AVGsel[15:8], 16-zone average weight option */ #define REG5F 0x5F /* AVGsel[23:16], 16-zone average weight option */ #define REG60 0x60 /* AVGsel[31:24], 16-zone average weight option */ #define HISTO_LOW 0x61 /* Histogram Algorithm Low Level */ #define HISTO_HIGH 0x62 /* Histogram Algorithm High Level */ /* * ID */ #define MANUFACTURER_ID 0x7FA2 #define PID_OV2640 0x2642 #define VERSION(pid, ver) ((pid << 8) | (ver & 0xFF)) /* * Struct */ struct regval_list { u8 reg_num; u8 value; }; /* Supported resolutions */ enum ov2640_width { W_QCIF = 176, W_QVGA = 320, W_CIF = 352, W_VGA = 640, W_SVGA = 800, W_XGA = 1024, W_SXGA = 1280, W_UXGA = 1600, }; enum ov2640_height { H_QCIF = 144, H_QVGA = 240, H_CIF = 288, H_VGA = 480, H_SVGA = 600, H_XGA = 768, H_SXGA = 1024, H_UXGA = 1200, }; struct ov2640_win_size { char *name; enum ov2640_width width; enum ov2640_height height; const struct regval_list *regs; }; struct ov2640_priv { struct v4l2_subdev subdev; struct v4l2_ctrl_handler hdl; enum v4l2_mbus_pixelcode cfmt_code; const struct ov2640_win_size *win; int model; }; /* * Registers settings */ #define ENDMARKER { 0xff, 0xff } static const struct regval_list ov2640_init_regs[] = { { BANK_SEL, BANK_SEL_DSP }, { 0x2c, 0xff }, { 0x2e, 0xdf }, { BANK_SEL, BANK_SEL_SENS }, { 0x3c, 0x32 }, { CLKRC, CLKRC_DIV_SET(1) }, { COM2, COM2_OCAP_Nx_SET(3) }, { REG04, REG04_DEF | REG04_HREF_EN }, { COM8, COM8_DEF | COM8_BNDF_EN | COM8_AGC_EN | COM8_AEC_EN }, { COM9, COM9_AGC_GAIN_8x | 0x08}, { 0x2c, 0x0c }, { 0x33, 0x78 }, { 0x3a, 0x33 }, { 0x3b, 0xfb }, { 0x3e, 0x00 }, { 0x43, 0x11 }, { 0x16, 0x10 }, { 0x39, 0x02 }, { 0x35, 0x88 }, { 0x22, 0x0a }, { 0x37, 0x40 }, { 0x23, 0x00 }, { ARCOM2, 0xa0 }, { 0x06, 0x02 }, { 0x06, 0x88 }, { 0x07, 0xc0 }, { 0x0d, 0xb7 }, { 0x0e, 0x01 }, { 0x4c, 0x00 }, { 0x4a, 0x81 }, { 0x21, 0x99 }, { AEW, 0x40 }, { AEB, 0x38 }, { VV, VV_HIGH_TH_SET(0x08) | VV_LOW_TH_SET(0x02) }, { 0x5c, 0x00 }, { 0x63, 0x00 }, { FLL, 0x22 }, { COM3, 0x38 | COM3_BAND_AUTO }, { REG5D, 0x55 }, { REG5E, 0x7d }, { REG5F, 0x7d }, { REG60, 0x55 }, { HISTO_LOW, 0x70 }, { HISTO_HIGH, 0x80 }, { 0x7c, 0x05 }, { 0x20, 0x80 }, { 0x28, 0x30 }, { 0x6c, 0x00 }, { 0x6d, 0x80 }, { 0x6e, 0x00 }, { 0x70, 0x02 }, { 0x71, 0x94 }, { 0x73, 0xc1 }, { 0x3d, 0x34 }, { COM7, COM7_RES_UXGA | COM7_ZOOM_EN }, { 0x5a, 0x57 }, { BD50, 0xbb }, { BD60, 0x9c }, { BANK_SEL, BANK_SEL_DSP }, { 0xe5, 0x7f }, { MC_BIST, MC_BIST_RESET | MC_BIST_BOOT_ROM_SEL }, { 0x41, 0x24 }, { RESET, RESET_JPEG | RESET_DVP }, { 0x76, 0xff }, { 0x33, 0xa0 }, { 0x42, 0x20 }, { 0x43, 0x18 }, { 0x4c, 0x00 }, { CTRL3, CTRL3_BPC_EN | CTRL3_WPC_EN | 0x10 }, { 0x88, 0x3f }, { 0xd7, 0x03 }, { 0xd9, 0x10 }, { R_DVP_SP , R_DVP_SP_AUTO_MODE | 0x2 }, { 0xc8, 0x08 }, { 0xc9, 0x80 }, { BPADDR, 0x00 }, { BPDATA, 0x00 }, { BPADDR, 0x03 }, { BPDATA, 0x48 }, { BPDATA, 0x48 }, { BPADDR, 0x08 }, { BPDATA, 0x20 }, { BPDATA, 0x10 }, { BPDATA, 0x0e }, { 0x90, 0x00 }, { 0x91, 0x0e }, { 0x91, 0x1a }, { 0x91, 0x31 }, { 0x91, 0x5a }, { 0x91, 0x69 }, { 0x91, 0x75 }, { 0x91, 0x7e }, { 0x91, 0x88 }, { 0x91, 0x8f }, { 0x91, 0x96 }, { 0x91, 0xa3 }, { 0x91, 0xaf }, { 0x91, 0xc4 }, { 0x91, 0xd7 }, { 0x91, 0xe8 }, { 0x91, 0x20 }, { 0x92, 0x00 }, { 0x93, 0x06 }, { 0x93, 0xe3 }, { 0x93, 0x03 }, { 0x93, 0x03 }, { 0x93, 0x00 }, { 0x93, 0x02 }, { 0x93, 0x00 }, { 0x93, 0x00 }, { 0x93, 0x00 }, { 0x93, 0x00 }, { 0x93, 0x00 }, { 0x93, 0x00 }, { 0x93, 0x00 }, { 0x96, 0x00 }, { 0x97, 0x08 }, { 0x97, 0x19 }, { 0x97, 0x02 }, { 0x97, 0x0c }, { 0x97, 0x24 }, { 0x97, 0x30 }, { 0x97, 0x28 }, { 0x97, 0x26 }, { 0x97, 0x02 }, { 0x97, 0x98 }, { 0x97, 0x80 }, { 0x97, 0x00 }, { 0x97, 0x00 }, { 0xa4, 0x00 }, { 0xa8, 0x00 }, { 0xc5, 0x11 }, { 0xc6, 0x51 }, { 0xbf, 0x80 }, { 0xc7, 0x10 }, { 0xb6, 0x66 }, { 0xb8, 0xA5 }, { 0xb7, 0x64 }, { 0xb9, 0x7C }, { 0xb3, 0xaf }, { 0xb4, 0x97 }, { 0xb5, 0xFF }, { 0xb0, 0xC5 }, { 0xb1, 0x94 }, { 0xb2, 0x0f }, { 0xc4, 0x5c }, { 0xa6, 0x00 }, { 0xa7, 0x20 }, { 0xa7, 0xd8 }, { 0xa7, 0x1b }, { 0xa7, 0x31 }, { 0xa7, 0x00 }, { 0xa7, 0x18 }, { 0xa7, 0x20 }, { 0xa7, 0xd8 }, { 0xa7, 0x19 }, { 0xa7, 0x31 }, { 0xa7, 0x00 }, { 0xa7, 0x18 }, { 0xa7, 0x20 }, { 0xa7, 0xd8 }, { 0xa7, 0x19 }, { 0xa7, 0x31 }, { 0xa7, 0x00 }, { 0xa7, 0x18 }, { 0x7f, 0x00 }, { 0xe5, 0x1f }, { 0xe1, 0x77 }, { 0xdd, 0x7f }, { CTRL0, CTRL0_YUV422 | CTRL0_YUV_EN | CTRL0_RGB_EN }, ENDMARKER, }; /* * Register settings for window size * The preamble, setup the internal DSP to input an UXGA (1600x1200) image. * Then the different zooming configurations will setup the output image size. */ static const struct regval_list ov2640_size_change_preamble_regs[] = { { BANK_SEL, BANK_SEL_DSP }, { RESET, RESET_DVP }, { HSIZE8, HSIZE8_SET(W_UXGA) }, { VSIZE8, VSIZE8_SET(H_UXGA) }, { CTRL2, CTRL2_DCW_EN | CTRL2_SDE_EN | CTRL2_UV_AVG_EN | CTRL2_CMX_EN | CTRL2_UV_ADJ_EN }, { HSIZE, HSIZE_SET(W_UXGA) }, { VSIZE, VSIZE_SET(H_UXGA) }, { XOFFL, XOFFL_SET(0) }, { YOFFL, YOFFL_SET(0) }, { VHYX, VHYX_HSIZE_SET(W_UXGA) | VHYX_VSIZE_SET(H_UXGA) | VHYX_XOFF_SET(0) | VHYX_YOFF_SET(0)}, { TEST, TEST_HSIZE_SET(W_UXGA) }, ENDMARKER, }; #define PER_SIZE_REG_SEQ(x, y, v_div, h_div, pclk_div) \ { CTRLI, CTRLI_LP_DP | CTRLI_V_DIV_SET(v_div) | \ CTRLI_H_DIV_SET(h_div)}, \ { ZMOW, ZMOW_OUTW_SET(x) }, \ { ZMOH, ZMOH_OUTH_SET(y) }, \ { ZMHH, ZMHH_OUTW_SET(x) | ZMHH_OUTH_SET(y) }, \ { R_DVP_SP, pclk_div }, \ { RESET, 0x00} static const struct regval_list ov2640_qcif_regs[] = { PER_SIZE_REG_SEQ(W_QCIF, H_QCIF, 3, 3, 4), ENDMARKER, }; static const struct regval_list ov2640_qvga_regs[] = { PER_SIZE_REG_SEQ(W_QVGA, H_QVGA, 2, 2, 4), ENDMARKER, }; static const struct regval_list ov2640_cif_regs[] = { PER_SIZE_REG_SEQ(W_CIF, H_CIF, 2, 2, 8), ENDMARKER, }; static const struct regval_list ov2640_vga_regs[] = { PER_SIZE_REG_SEQ(W_VGA, H_VGA, 0, 0, 2), ENDMARKER, }; static const struct regval_list ov2640_svga_regs[] = { PER_SIZE_REG_SEQ(W_SVGA, H_SVGA, 1, 1, 2), ENDMARKER, }; static const struct regval_list ov2640_xga_regs[] = { PER_SIZE_REG_SEQ(W_XGA, H_XGA, 0, 0, 2), { CTRLI, 0x00}, ENDMARKER, }; static const struct regval_list ov2640_sxga_regs[] = { PER_SIZE_REG_SEQ(W_SXGA, H_SXGA, 0, 0, 2), { CTRLI, 0x00}, { R_DVP_SP, 2 | R_DVP_SP_AUTO_MODE }, ENDMARKER, }; static const struct regval_list ov2640_uxga_regs[] = { PER_SIZE_REG_SEQ(W_UXGA, H_UXGA, 0, 0, 0), { CTRLI, 0x00}, { R_DVP_SP, 0 | R_DVP_SP_AUTO_MODE }, ENDMARKER, }; #define OV2640_SIZE(n, w, h, r) \ {.name = n, .width = w , .height = h, .regs = r } static const struct ov2640_win_size ov2640_supported_win_sizes[] = { OV2640_SIZE("QCIF", W_QCIF, H_QCIF, ov2640_qcif_regs), OV2640_SIZE("QVGA", W_QVGA, H_QVGA, ov2640_qvga_regs), OV2640_SIZE("CIF", W_CIF, H_CIF, ov2640_cif_regs), OV2640_SIZE("VGA", W_VGA, H_VGA, ov2640_vga_regs), OV2640_SIZE("SVGA", W_SVGA, H_SVGA, ov2640_svga_regs), OV2640_SIZE("XGA", W_XGA, H_XGA, ov2640_xga_regs), OV2640_SIZE("SXGA", W_SXGA, H_SXGA, ov2640_sxga_regs), OV2640_SIZE("UXGA", W_UXGA, H_UXGA, ov2640_uxga_regs), }; /* * Register settings for pixel formats */ static const struct regval_list ov2640_format_change_preamble_regs[] = { { BANK_SEL, BANK_SEL_DSP }, { R_BYPASS, R_BYPASS_USE_DSP }, ENDMARKER, }; static const struct regval_list ov2640_yuv422_regs[] = { { IMAGE_MODE, IMAGE_MODE_LBYTE_FIRST | IMAGE_MODE_YUV422 }, { 0xD7, 0x01 }, { 0x33, 0xa0 }, { 0xe1, 0x67 }, { RESET, 0x00 }, { R_BYPASS, R_BYPASS_USE_DSP }, ENDMARKER, }; static const struct regval_list ov2640_rgb565_regs[] = { { IMAGE_MODE, IMAGE_MODE_LBYTE_FIRST | IMAGE_MODE_RGB565 }, { 0xd7, 0x03 }, { RESET, 0x00 }, { R_BYPASS, R_BYPASS_USE_DSP }, ENDMARKER, }; static enum v4l2_mbus_pixelcode ov2640_codes[] = { V4L2_MBUS_FMT_UYVY8_2X8, V4L2_MBUS_FMT_RGB565_2X8_LE, }; /* * General functions */ static struct ov2640_priv *to_ov2640(const struct i2c_client *client) { return container_of(i2c_get_clientdata(client), struct ov2640_priv, subdev); } static int ov2640_write_array(struct i2c_client *client, const struct regval_list *vals) { int ret; while ((vals->reg_num != 0xff) || (vals->value != 0xff)) { ret = i2c_smbus_write_byte_data(client, vals->reg_num, vals->value); dev_vdbg(&client->dev, "array: 0x%02x, 0x%02x", vals->reg_num, vals->value); if (ret < 0) return ret; vals++; } return 0; } static int ov2640_mask_set(struct i2c_client *client, u8 reg, u8 mask, u8 set) { s32 val = i2c_smbus_read_byte_data(client, reg); if (val < 0) return val; val &= ~mask; val |= set & mask; dev_vdbg(&client->dev, "masks: 0x%02x, 0x%02x", reg, val); return i2c_smbus_write_byte_data(client, reg, val); } static int ov2640_reset(struct i2c_client *client) { int ret; const struct regval_list reset_seq[] = { {BANK_SEL, BANK_SEL_SENS}, {COM7, COM7_SRST}, ENDMARKER, }; ret = ov2640_write_array(client, reset_seq); if (ret) goto err; msleep(5); err: dev_dbg(&client->dev, "%s: (ret %d)", __func__, ret); return ret; } /* * soc_camera_ops functions */ static int ov2640_s_stream(struct v4l2_subdev *sd, int enable) { return 0; } static int ov2640_s_ctrl(struct v4l2_ctrl *ctrl) { struct v4l2_subdev *sd = &container_of(ctrl->handler, struct ov2640_priv, hdl)->subdev; struct i2c_client *client = v4l2_get_subdevdata(sd); u8 val; switch (ctrl->id) { case V4L2_CID_VFLIP: val = ctrl->val ? REG04_VFLIP_IMG : 0x00; return ov2640_mask_set(client, REG04, REG04_VFLIP_IMG, val); case V4L2_CID_HFLIP: val = ctrl->val ? REG04_HFLIP_IMG : 0x00; return ov2640_mask_set(client, REG04, REG04_HFLIP_IMG, val); } return -EINVAL; } static int ov2640_g_chip_ident(struct v4l2_subdev *sd, struct v4l2_dbg_chip_ident *id) { struct i2c_client *client = v4l2_get_subdevdata(sd); struct ov2640_priv *priv = to_ov2640(client); id->ident = priv->model; id->revision = 0; return 0; } #ifdef CONFIG_VIDEO_ADV_DEBUG static int ov2640_g_register(struct v4l2_subdev *sd, struct v4l2_dbg_register *reg) { struct i2c_client *client = v4l2_get_subdevdata(sd); int ret; reg->size = 1; if (reg->reg > 0xff) return -EINVAL; ret = i2c_smbus_read_byte_data(client, reg->reg); if (ret < 0) return ret; reg->val = ret; return 0; } static int ov2640_s_register(struct v4l2_subdev *sd, struct v4l2_dbg_register *reg) { struct i2c_client *client = v4l2_get_subdevdata(sd); if (reg->reg > 0xff || reg->val > 0xff) return -EINVAL; return i2c_smbus_write_byte_data(client, reg->reg, reg->val); } #endif /* Select the nearest higher resolution for capture */ static const struct ov2640_win_size *ov2640_select_win(u32 *width, u32 *height) { int i, default_size = ARRAY_SIZE(ov2640_supported_win_sizes) - 1; for (i = 0; i < ARRAY_SIZE(ov2640_supported_win_sizes); i++) { if (ov2640_supported_win_sizes[i].width >= *width && ov2640_supported_win_sizes[i].height >= *height) { *width = ov2640_supported_win_sizes[i].width; *height = ov2640_supported_win_sizes[i].height; return &ov2640_supported_win_sizes[i]; } } *width = ov2640_supported_win_sizes[default_size].width; *height = ov2640_supported_win_sizes[default_size].height; return &ov2640_supported_win_sizes[default_size]; } static int ov2640_set_params(struct i2c_client *client, u32 *width, u32 *height, enum v4l2_mbus_pixelcode code) { struct ov2640_priv *priv = to_ov2640(client); const struct regval_list *selected_cfmt_regs; int ret; /* select win */ priv->win = ov2640_select_win(width, height); /* select format */ priv->cfmt_code = 0; switch (code) { case V4L2_MBUS_FMT_RGB565_2X8_LE: dev_dbg(&client->dev, "%s: Selected cfmt RGB565", __func__); selected_cfmt_regs = ov2640_rgb565_regs; break; default: case V4L2_MBUS_FMT_UYVY8_2X8: dev_dbg(&client->dev, "%s: Selected cfmt YUV422", __func__); selected_cfmt_regs = ov2640_yuv422_regs; } /* reset hardware */ ov2640_reset(client); /* initialize the sensor with default data */ dev_dbg(&client->dev, "%s: Init default", __func__); ret = ov2640_write_array(client, ov2640_init_regs); if (ret < 0) goto err; /* select preamble */ dev_dbg(&client->dev, "%s: Set size to %s", __func__, priv->win->name); ret = ov2640_write_array(client, ov2640_size_change_preamble_regs); if (ret < 0) goto err; /* set size win */ ret = ov2640_write_array(client, priv->win->regs); if (ret < 0) goto err; /* cfmt preamble */ dev_dbg(&client->dev, "%s: Set cfmt", __func__); ret = ov2640_write_array(client, ov2640_format_change_preamble_regs); if (ret < 0) goto err; /* set cfmt */ ret = ov2640_write_array(client, selected_cfmt_regs); if (ret < 0) goto err; priv->cfmt_code = code; *width = priv->win->width; *height = priv->win->height; return 0; err: dev_err(&client->dev, "%s: Error %d", __func__, ret); ov2640_reset(client); priv->win = NULL; return ret; } static int ov2640_g_fmt(struct v4l2_subdev *sd, struct v4l2_mbus_framefmt *mf) { struct i2c_client *client = v4l2_get_subdevdata(sd); struct ov2640_priv *priv = to_ov2640(client); if (!priv->win) { u32 width = W_SVGA, height = H_SVGA; int ret = ov2640_set_params(client, &width, &height, V4L2_MBUS_FMT_UYVY8_2X8); if (ret < 0) return ret; } mf->width = priv->win->width; mf->height = priv->win->height; mf->code = priv->cfmt_code; switch (mf->code) { case V4L2_MBUS_FMT_RGB565_2X8_LE: mf->colorspace = V4L2_COLORSPACE_SRGB; break; default: case V4L2_MBUS_FMT_UYVY8_2X8: mf->colorspace = V4L2_COLORSPACE_JPEG; } mf->field = V4L2_FIELD_NONE; return 0; } static int ov2640_s_fmt(struct v4l2_subdev *sd, struct v4l2_mbus_framefmt *mf) { struct i2c_client *client = v4l2_get_subdevdata(sd); int ret; switch (mf->code) { case V4L2_MBUS_FMT_RGB565_2X8_LE: mf->colorspace = V4L2_COLORSPACE_SRGB; break; default: mf->code = V4L2_MBUS_FMT_UYVY8_2X8; case V4L2_MBUS_FMT_UYVY8_2X8: mf->colorspace = V4L2_COLORSPACE_JPEG; } ret = ov2640_set_params(client, &mf->width, &mf->height, mf->code); return ret; } static int ov2640_try_fmt(struct v4l2_subdev *sd, struct v4l2_mbus_framefmt *mf) { const struct ov2640_win_size *win; /* * select suitable win */ win = ov2640_select_win(&mf->width, &mf->height); mf->field = V4L2_FIELD_NONE; switch (mf->code) { case V4L2_MBUS_FMT_RGB565_2X8_LE: mf->colorspace = V4L2_COLORSPACE_SRGB; break; default: mf->code = V4L2_MBUS_FMT_UYVY8_2X8; case V4L2_MBUS_FMT_UYVY8_2X8: mf->colorspace = V4L2_COLORSPACE_JPEG; } return 0; } static int ov2640_enum_fmt(struct v4l2_subdev *sd, unsigned int index, enum v4l2_mbus_pixelcode *code) { if (index >= ARRAY_SIZE(ov2640_codes)) return -EINVAL; *code = ov2640_codes[index]; return 0; } static int ov2640_g_crop(struct v4l2_subdev *sd, struct v4l2_crop *a) { a->c.left = 0; a->c.top = 0; a->c.width = W_UXGA; a->c.height = H_UXGA; a->type = V4L2_BUF_TYPE_VIDEO_CAPTURE; return 0; } static int ov2640_cropcap(struct v4l2_subdev *sd, struct v4l2_cropcap *a) { a->bounds.left = 0; a->bounds.top = 0; a->bounds.width = W_UXGA; a->bounds.height = H_UXGA; a->defrect = a->bounds; a->type = V4L2_BUF_TYPE_VIDEO_CAPTURE; a->pixelaspect.numerator = 1; a->pixelaspect.denominator = 1; return 0; } static int ov2640_video_probe(struct i2c_client *client) { struct ov2640_priv *priv = to_ov2640(client); u8 pid, ver, midh, midl; const char *devname; int ret; /* * check and show product ID and manufacturer ID */ i2c_smbus_write_byte_data(client, BANK_SEL, BANK_SEL_SENS); pid = i2c_smbus_read_byte_data(client, PID); ver = i2c_smbus_read_byte_data(client, VER); midh = i2c_smbus_read_byte_data(client, MIDH); midl = i2c_smbus_read_byte_data(client, MIDL); switch (VERSION(pid, ver)) { case PID_OV2640: devname = "ov2640"; priv->model = V4L2_IDENT_OV2640; break; default: dev_err(&client->dev, "Product ID error %x:%x\n", pid, ver); ret = -ENODEV; goto err; } dev_info(&client->dev, "%s Product ID %0x:%0x Manufacturer ID %x:%x\n", devname, pid, ver, midh, midl); return v4l2_ctrl_handler_setup(&priv->hdl); err: return ret; } static const struct v4l2_ctrl_ops ov2640_ctrl_ops = { .s_ctrl = ov2640_s_ctrl, }; static struct v4l2_subdev_core_ops ov2640_subdev_core_ops = { .g_chip_ident = ov2640_g_chip_ident, #ifdef CONFIG_VIDEO_ADV_DEBUG .g_register = ov2640_g_register, .s_register = ov2640_s_register, #endif }; static int ov2640_g_mbus_config(struct v4l2_subdev *sd, struct v4l2_mbus_config *cfg) { struct i2c_client *client = v4l2_get_subdevdata(sd); struct soc_camera_link *icl = soc_camera_i2c_to_link(client); cfg->flags = V4L2_MBUS_PCLK_SAMPLE_RISING | V4L2_MBUS_MASTER | V4L2_MBUS_VSYNC_ACTIVE_HIGH | V4L2_MBUS_HSYNC_ACTIVE_HIGH | V4L2_MBUS_DATA_ACTIVE_HIGH; cfg->type = V4L2_MBUS_PARALLEL; cfg->flags = soc_camera_apply_board_flags(icl, cfg); return 0; } static struct v4l2_subdev_video_ops ov2640_subdev_video_ops = { .s_stream = ov2640_s_stream, .g_mbus_fmt = ov2640_g_fmt, .s_mbus_fmt = ov2640_s_fmt, .try_mbus_fmt = ov2640_try_fmt, .cropcap = ov2640_cropcap, .g_crop = ov2640_g_crop, .enum_mbus_fmt = ov2640_enum_fmt, .g_mbus_config = ov2640_g_mbus_config, }; static struct v4l2_subdev_ops ov2640_subdev_ops = { .core = &ov2640_subdev_core_ops, .video = &ov2640_subdev_video_ops, }; /* * i2c_driver functions */ static int ov2640_probe(struct i2c_client *client, const struct i2c_device_id *did) { struct ov2640_priv *priv; struct soc_camera_link *icl = soc_camera_i2c_to_link(client); struct i2c_adapter *adapter = to_i2c_adapter(client->dev.parent); int ret; if (!icl) { dev_err(&adapter->dev, "OV2640: Missing platform_data for driver\n"); return -EINVAL; } if (!i2c_check_functionality(adapter, I2C_FUNC_SMBUS_BYTE_DATA)) { dev_err(&adapter->dev, "OV2640: I2C-Adapter doesn't support SMBUS\n"); return -EIO; } priv = kzalloc(sizeof(struct ov2640_priv), GFP_KERNEL); if (!priv) { dev_err(&adapter->dev, "Failed to allocate memory for private data!\n"); return -ENOMEM; } v4l2_i2c_subdev_init(&priv->subdev, client, &ov2640_subdev_ops); v4l2_ctrl_handler_init(&priv->hdl, 2); v4l2_ctrl_new_std(&priv->hdl, &ov2640_ctrl_ops, V4L2_CID_VFLIP, 0, 1, 1, 0); v4l2_ctrl_new_std(&priv->hdl, &ov2640_ctrl_ops, V4L2_CID_HFLIP, 0, 1, 1, 0); priv->subdev.ctrl_handler = &priv->hdl; if (priv->hdl.error) { int err = priv->hdl.error; kfree(priv); return err; } ret = ov2640_video_probe(client); if (ret) { v4l2_ctrl_handler_free(&priv->hdl); kfree(priv); } else { dev_info(&adapter->dev, "OV2640 Probed\n"); } return ret; } static int ov2640_remove(struct i2c_client *client) { struct ov2640_priv *priv = to_ov2640(client); v4l2_device_unregister_subdev(&priv->subdev); v4l2_ctrl_handler_free(&priv->hdl); kfree(priv); return 0; } static const struct i2c_device_id ov2640_id[] = { { "ov2640", 0 }, { } }; MODULE_DEVICE_TABLE(i2c, ov2640_id); static struct i2c_driver ov2640_i2c_driver = { .driver = { .name = "ov2640", }, .probe = ov2640_probe, .remove = ov2640_remove, .id_table = ov2640_id, }; module_i2c_driver(ov2640_i2c_driver); MODULE_DESCRIPTION("SoC Camera driver for Omni Vision 2640 sensor"); MODULE_AUTHOR("Alberto Panizzo"); MODULE_LICENSE("GPL v2");
gpl-2.0
willizambranoback/evolution_CM13
drivers/usb/storage/sierra_ms.c
4863
5491
#include <scsi/scsi.h> #include <scsi/scsi_host.h> #include <scsi/scsi_cmnd.h> #include <scsi/scsi_device.h> #include <linux/usb.h> #include <linux/module.h> #include <linux/slab.h> #include "usb.h" #include "transport.h" #include "protocol.h" #include "scsiglue.h" #include "sierra_ms.h" #include "debug.h" #define SWIMS_USB_REQUEST_SetSwocMode 0x0B #define SWIMS_USB_REQUEST_GetSwocInfo 0x0A #define SWIMS_USB_INDEX_SetMode 0x0000 #define SWIMS_SET_MODE_Modem 0x0001 #define TRU_NORMAL 0x01 #define TRU_FORCE_MS 0x02 #define TRU_FORCE_MODEM 0x03 static unsigned int swi_tru_install = 1; module_param(swi_tru_install, uint, S_IRUGO | S_IWUSR); MODULE_PARM_DESC(swi_tru_install, "TRU-Install mode (1=Full Logic (def)," " 2=Force CD-Rom, 3=Force Modem)"); struct swoc_info { __u8 rev; __u8 reserved[8]; __u16 LinuxSKU; __u16 LinuxVer; __u8 reserved2[47]; } __attribute__((__packed__)); static bool containsFullLinuxPackage(struct swoc_info *swocInfo) { if ((swocInfo->LinuxSKU >= 0x2100 && swocInfo->LinuxSKU <= 0x2FFF) || (swocInfo->LinuxSKU >= 0x7100 && swocInfo->LinuxSKU <= 0x7FFF)) return true; else return false; } static int sierra_set_ms_mode(struct usb_device *udev, __u16 eSWocMode) { int result; US_DEBUGP("SWIMS: %s", "DEVICE MODE SWITCH\n"); result = usb_control_msg(udev, usb_sndctrlpipe(udev, 0), SWIMS_USB_REQUEST_SetSwocMode, /* __u8 request */ USB_TYPE_VENDOR | USB_DIR_OUT, /* __u8 request type */ eSWocMode, /* __u16 value */ 0x0000, /* __u16 index */ NULL, /* void *data */ 0, /* __u16 size */ USB_CTRL_SET_TIMEOUT); /* int timeout */ return result; } static int sierra_get_swoc_info(struct usb_device *udev, struct swoc_info *swocInfo) { int result; US_DEBUGP("SWIMS: Attempting to get TRU-Install info.\n"); result = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0), SWIMS_USB_REQUEST_GetSwocInfo, /* __u8 request */ USB_TYPE_VENDOR | USB_DIR_IN, /* __u8 request type */ 0, /* __u16 value */ 0, /* __u16 index */ (void *) swocInfo, /* void *data */ sizeof(struct swoc_info), /* __u16 size */ USB_CTRL_SET_TIMEOUT); /* int timeout */ swocInfo->LinuxSKU = le16_to_cpu(swocInfo->LinuxSKU); swocInfo->LinuxVer = le16_to_cpu(swocInfo->LinuxVer); return result; } static void debug_swoc(struct swoc_info *swocInfo) { US_DEBUGP("SWIMS: SWoC Rev: %02d \n", swocInfo->rev); US_DEBUGP("SWIMS: Linux SKU: %04X \n", swocInfo->LinuxSKU); US_DEBUGP("SWIMS: Linux Version: %04X \n", swocInfo->LinuxVer); } static ssize_t show_truinst(struct device *dev, struct device_attribute *attr, char *buf) { struct swoc_info *swocInfo; struct usb_interface *intf = to_usb_interface(dev); struct usb_device *udev = interface_to_usbdev(intf); int result; if (swi_tru_install == TRU_FORCE_MS) { result = snprintf(buf, PAGE_SIZE, "Forced Mass Storage\n"); } else { swocInfo = kmalloc(sizeof(struct swoc_info), GFP_KERNEL); if (!swocInfo) { US_DEBUGP("SWIMS: Allocation failure\n"); snprintf(buf, PAGE_SIZE, "Error\n"); return -ENOMEM; } result = sierra_get_swoc_info(udev, swocInfo); if (result < 0) { US_DEBUGP("SWIMS: failed SWoC query\n"); kfree(swocInfo); snprintf(buf, PAGE_SIZE, "Error\n"); return -EIO; } debug_swoc(swocInfo); result = snprintf(buf, PAGE_SIZE, "REV=%02d SKU=%04X VER=%04X\n", swocInfo->rev, swocInfo->LinuxSKU, swocInfo->LinuxVer); kfree(swocInfo); } return result; } static DEVICE_ATTR(truinst, S_IRUGO, show_truinst, NULL); int sierra_ms_init(struct us_data *us) { int result, retries; struct swoc_info *swocInfo; struct usb_device *udev; struct Scsi_Host *sh; struct scsi_device *sd; retries = 3; result = 0; udev = us->pusb_dev; sh = us_to_host(us); sd = scsi_get_host_dev(sh); US_DEBUGP("SWIMS: sierra_ms_init called\n"); /* Force Modem mode */ if (swi_tru_install == TRU_FORCE_MODEM) { US_DEBUGP("SWIMS: %s", "Forcing Modem Mode\n"); result = sierra_set_ms_mode(udev, SWIMS_SET_MODE_Modem); if (result < 0) US_DEBUGP("SWIMS: Failed to switch to modem mode.\n"); return -EIO; } /* Force Mass Storage mode (keep CD-Rom) */ else if (swi_tru_install == TRU_FORCE_MS) { US_DEBUGP("SWIMS: %s", "Forcing Mass Storage Mode\n"); goto complete; } /* Normal TRU-Install Logic */ else { US_DEBUGP("SWIMS: %s", "Normal SWoC Logic\n"); swocInfo = kmalloc(sizeof(struct swoc_info), GFP_KERNEL); if (!swocInfo) { US_DEBUGP("SWIMS: %s", "Allocation failure\n"); return -ENOMEM; } retries = 3; do { retries--; result = sierra_get_swoc_info(udev, swocInfo); if (result < 0) { US_DEBUGP("SWIMS: %s", "Failed SWoC query\n"); schedule_timeout_uninterruptible(2*HZ); } } while (retries && result < 0); if (result < 0) { US_DEBUGP("SWIMS: %s", "Completely failed SWoC query\n"); kfree(swocInfo); return -EIO; } debug_swoc(swocInfo); /* If there is not Linux software on the TRU-Install device * then switch to modem mode */ if (!containsFullLinuxPackage(swocInfo)) { US_DEBUGP("SWIMS: %s", "Switching to Modem Mode\n"); result = sierra_set_ms_mode(udev, SWIMS_SET_MODE_Modem); if (result < 0) US_DEBUGP("SWIMS: Failed to switch modem\n"); kfree(swocInfo); return -EIO; } kfree(swocInfo); } complete: result = device_create_file(&us->pusb_intf->dev, &dev_attr_truinst); return 0; }
gpl-2.0
SlimRoms/kernel_htc_m7
sound/core/seq/seq_virmidi.c
7679
13920
/* * Virtual Raw MIDI client on Sequencer * * Copyright (c) 2000 by Takashi Iwai <tiwai@suse.de>, * Jaroslav Kysela <perex@perex.cz> * * 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 * */ /* * Virtual Raw MIDI client * * The virtual rawmidi client is a sequencer client which associate * a rawmidi device file. The created rawmidi device file can be * accessed as a normal raw midi, but its MIDI source and destination * are arbitrary. For example, a user-client software synth connected * to this port can be used as a normal midi device as well. * * The virtual rawmidi device accepts also multiple opens. Each file * has its own input buffer, so that no conflict would occur. The drain * of input/output buffer acts only to the local buffer. * */ #include <linux/init.h> #include <linux/wait.h> #include <linux/module.h> #include <linux/slab.h> #include <sound/core.h> #include <sound/rawmidi.h> #include <sound/info.h> #include <sound/control.h> #include <sound/minors.h> #include <sound/seq_kernel.h> #include <sound/seq_midi_event.h> #include <sound/seq_virmidi.h> MODULE_AUTHOR("Takashi Iwai <tiwai@suse.de>"); MODULE_DESCRIPTION("Virtual Raw MIDI client on Sequencer"); MODULE_LICENSE("GPL"); /* * initialize an event record */ static void snd_virmidi_init_event(struct snd_virmidi *vmidi, struct snd_seq_event *ev) { memset(ev, 0, sizeof(*ev)); ev->source.port = vmidi->port; switch (vmidi->seq_mode) { case SNDRV_VIRMIDI_SEQ_DISPATCH: ev->dest.client = SNDRV_SEQ_ADDRESS_SUBSCRIBERS; break; case SNDRV_VIRMIDI_SEQ_ATTACH: /* FIXME: source and destination are same - not good.. */ ev->dest.client = vmidi->client; ev->dest.port = vmidi->port; break; } ev->type = SNDRV_SEQ_EVENT_NONE; } /* * decode input event and put to read buffer of each opened file */ static int snd_virmidi_dev_receive_event(struct snd_virmidi_dev *rdev, struct snd_seq_event *ev) { struct snd_virmidi *vmidi; unsigned char msg[4]; int len; read_lock(&rdev->filelist_lock); list_for_each_entry(vmidi, &rdev->filelist, list) { if (!vmidi->trigger) continue; if (ev->type == SNDRV_SEQ_EVENT_SYSEX) { if ((ev->flags & SNDRV_SEQ_EVENT_LENGTH_MASK) != SNDRV_SEQ_EVENT_LENGTH_VARIABLE) continue; snd_seq_dump_var_event(ev, (snd_seq_dump_func_t)snd_rawmidi_receive, vmidi->substream); } else { len = snd_midi_event_decode(vmidi->parser, msg, sizeof(msg), ev); if (len > 0) snd_rawmidi_receive(vmidi->substream, msg, len); } } read_unlock(&rdev->filelist_lock); return 0; } /* * receive an event from the remote virmidi port * * for rawmidi inputs, you can call this function from the event * handler of a remote port which is attached to the virmidi via * SNDRV_VIRMIDI_SEQ_ATTACH. */ #if 0 int snd_virmidi_receive(struct snd_rawmidi *rmidi, struct snd_seq_event *ev) { struct snd_virmidi_dev *rdev; rdev = rmidi->private_data; return snd_virmidi_dev_receive_event(rdev, ev); } #endif /* 0 */ /* * event handler of virmidi port */ static int snd_virmidi_event_input(struct snd_seq_event *ev, int direct, void *private_data, int atomic, int hop) { struct snd_virmidi_dev *rdev; rdev = private_data; if (!(rdev->flags & SNDRV_VIRMIDI_USE)) return 0; /* ignored */ return snd_virmidi_dev_receive_event(rdev, ev); } /* * trigger rawmidi stream for input */ static void snd_virmidi_input_trigger(struct snd_rawmidi_substream *substream, int up) { struct snd_virmidi *vmidi = substream->runtime->private_data; if (up) { vmidi->trigger = 1; } else { vmidi->trigger = 0; } } /* * trigger rawmidi stream for output */ static void snd_virmidi_output_trigger(struct snd_rawmidi_substream *substream, int up) { struct snd_virmidi *vmidi = substream->runtime->private_data; int count, res; unsigned char buf[32], *pbuf; if (up) { vmidi->trigger = 1; if (vmidi->seq_mode == SNDRV_VIRMIDI_SEQ_DISPATCH && !(vmidi->rdev->flags & SNDRV_VIRMIDI_SUBSCRIBE)) { snd_rawmidi_transmit_ack(substream, substream->runtime->buffer_size - substream->runtime->avail); return; /* ignored */ } if (vmidi->event.type != SNDRV_SEQ_EVENT_NONE) { if (snd_seq_kernel_client_dispatch(vmidi->client, &vmidi->event, in_atomic(), 0) < 0) return; vmidi->event.type = SNDRV_SEQ_EVENT_NONE; } while (1) { count = snd_rawmidi_transmit_peek(substream, buf, sizeof(buf)); if (count <= 0) break; pbuf = buf; while (count > 0) { res = snd_midi_event_encode(vmidi->parser, pbuf, count, &vmidi->event); if (res < 0) { snd_midi_event_reset_encode(vmidi->parser); continue; } snd_rawmidi_transmit_ack(substream, res); pbuf += res; count -= res; if (vmidi->event.type != SNDRV_SEQ_EVENT_NONE) { if (snd_seq_kernel_client_dispatch(vmidi->client, &vmidi->event, in_atomic(), 0) < 0) return; vmidi->event.type = SNDRV_SEQ_EVENT_NONE; } } } } else { vmidi->trigger = 0; } } /* * open rawmidi handle for input */ static int snd_virmidi_input_open(struct snd_rawmidi_substream *substream) { struct snd_virmidi_dev *rdev = substream->rmidi->private_data; struct snd_rawmidi_runtime *runtime = substream->runtime; struct snd_virmidi *vmidi; unsigned long flags; vmidi = kzalloc(sizeof(*vmidi), GFP_KERNEL); if (vmidi == NULL) return -ENOMEM; vmidi->substream = substream; if (snd_midi_event_new(0, &vmidi->parser) < 0) { kfree(vmidi); return -ENOMEM; } vmidi->seq_mode = rdev->seq_mode; vmidi->client = rdev->client; vmidi->port = rdev->port; runtime->private_data = vmidi; write_lock_irqsave(&rdev->filelist_lock, flags); list_add_tail(&vmidi->list, &rdev->filelist); write_unlock_irqrestore(&rdev->filelist_lock, flags); vmidi->rdev = rdev; return 0; } /* * open rawmidi handle for output */ static int snd_virmidi_output_open(struct snd_rawmidi_substream *substream) { struct snd_virmidi_dev *rdev = substream->rmidi->private_data; struct snd_rawmidi_runtime *runtime = substream->runtime; struct snd_virmidi *vmidi; vmidi = kzalloc(sizeof(*vmidi), GFP_KERNEL); if (vmidi == NULL) return -ENOMEM; vmidi->substream = substream; if (snd_midi_event_new(MAX_MIDI_EVENT_BUF, &vmidi->parser) < 0) { kfree(vmidi); return -ENOMEM; } vmidi->seq_mode = rdev->seq_mode; vmidi->client = rdev->client; vmidi->port = rdev->port; snd_virmidi_init_event(vmidi, &vmidi->event); vmidi->rdev = rdev; runtime->private_data = vmidi; return 0; } /* * close rawmidi handle for input */ static int snd_virmidi_input_close(struct snd_rawmidi_substream *substream) { struct snd_virmidi *vmidi = substream->runtime->private_data; snd_midi_event_free(vmidi->parser); list_del(&vmidi->list); substream->runtime->private_data = NULL; kfree(vmidi); return 0; } /* * close rawmidi handle for output */ static int snd_virmidi_output_close(struct snd_rawmidi_substream *substream) { struct snd_virmidi *vmidi = substream->runtime->private_data; snd_midi_event_free(vmidi->parser); substream->runtime->private_data = NULL; kfree(vmidi); return 0; } /* * subscribe callback - allow output to rawmidi device */ static int snd_virmidi_subscribe(void *private_data, struct snd_seq_port_subscribe *info) { struct snd_virmidi_dev *rdev; rdev = private_data; if (!try_module_get(rdev->card->module)) return -EFAULT; rdev->flags |= SNDRV_VIRMIDI_SUBSCRIBE; return 0; } /* * unsubscribe callback - disallow output to rawmidi device */ static int snd_virmidi_unsubscribe(void *private_data, struct snd_seq_port_subscribe *info) { struct snd_virmidi_dev *rdev; rdev = private_data; rdev->flags &= ~SNDRV_VIRMIDI_SUBSCRIBE; module_put(rdev->card->module); return 0; } /* * use callback - allow input to rawmidi device */ static int snd_virmidi_use(void *private_data, struct snd_seq_port_subscribe *info) { struct snd_virmidi_dev *rdev; rdev = private_data; if (!try_module_get(rdev->card->module)) return -EFAULT; rdev->flags |= SNDRV_VIRMIDI_USE; return 0; } /* * unuse callback - disallow input to rawmidi device */ static int snd_virmidi_unuse(void *private_data, struct snd_seq_port_subscribe *info) { struct snd_virmidi_dev *rdev; rdev = private_data; rdev->flags &= ~SNDRV_VIRMIDI_USE; module_put(rdev->card->module); return 0; } /* * Register functions */ static struct snd_rawmidi_ops snd_virmidi_input_ops = { .open = snd_virmidi_input_open, .close = snd_virmidi_input_close, .trigger = snd_virmidi_input_trigger, }; static struct snd_rawmidi_ops snd_virmidi_output_ops = { .open = snd_virmidi_output_open, .close = snd_virmidi_output_close, .trigger = snd_virmidi_output_trigger, }; /* * create a sequencer client and a port */ static int snd_virmidi_dev_attach_seq(struct snd_virmidi_dev *rdev) { int client; struct snd_seq_port_callback pcallbacks; struct snd_seq_port_info *pinfo; int err; if (rdev->client >= 0) return 0; pinfo = kzalloc(sizeof(*pinfo), GFP_KERNEL); if (!pinfo) { err = -ENOMEM; goto __error; } client = snd_seq_create_kernel_client(rdev->card, rdev->device, "%s %d-%d", rdev->rmidi->name, rdev->card->number, rdev->device); if (client < 0) { err = client; goto __error; } rdev->client = client; /* create a port */ pinfo->addr.client = client; sprintf(pinfo->name, "VirMIDI %d-%d", rdev->card->number, rdev->device); /* set all capabilities */ pinfo->capability |= SNDRV_SEQ_PORT_CAP_WRITE | SNDRV_SEQ_PORT_CAP_SYNC_WRITE | SNDRV_SEQ_PORT_CAP_SUBS_WRITE; pinfo->capability |= SNDRV_SEQ_PORT_CAP_READ | SNDRV_SEQ_PORT_CAP_SYNC_READ | SNDRV_SEQ_PORT_CAP_SUBS_READ; pinfo->capability |= SNDRV_SEQ_PORT_CAP_DUPLEX; pinfo->type = SNDRV_SEQ_PORT_TYPE_MIDI_GENERIC | SNDRV_SEQ_PORT_TYPE_SOFTWARE | SNDRV_SEQ_PORT_TYPE_PORT; pinfo->midi_channels = 16; memset(&pcallbacks, 0, sizeof(pcallbacks)); pcallbacks.owner = THIS_MODULE; pcallbacks.private_data = rdev; pcallbacks.subscribe = snd_virmidi_subscribe; pcallbacks.unsubscribe = snd_virmidi_unsubscribe; pcallbacks.use = snd_virmidi_use; pcallbacks.unuse = snd_virmidi_unuse; pcallbacks.event_input = snd_virmidi_event_input; pinfo->kernel = &pcallbacks; err = snd_seq_kernel_client_ctl(client, SNDRV_SEQ_IOCTL_CREATE_PORT, pinfo); if (err < 0) { snd_seq_delete_kernel_client(client); rdev->client = -1; goto __error; } rdev->port = pinfo->addr.port; err = 0; /* success */ __error: kfree(pinfo); return err; } /* * release the sequencer client */ static void snd_virmidi_dev_detach_seq(struct snd_virmidi_dev *rdev) { if (rdev->client >= 0) { snd_seq_delete_kernel_client(rdev->client); rdev->client = -1; } } /* * register the device */ static int snd_virmidi_dev_register(struct snd_rawmidi *rmidi) { struct snd_virmidi_dev *rdev = rmidi->private_data; int err; switch (rdev->seq_mode) { case SNDRV_VIRMIDI_SEQ_DISPATCH: err = snd_virmidi_dev_attach_seq(rdev); if (err < 0) return err; break; case SNDRV_VIRMIDI_SEQ_ATTACH: if (rdev->client == 0) return -EINVAL; /* should check presence of port more strictly.. */ break; default: snd_printk(KERN_ERR "seq_mode is not set: %d\n", rdev->seq_mode); return -EINVAL; } return 0; } /* * unregister the device */ static int snd_virmidi_dev_unregister(struct snd_rawmidi *rmidi) { struct snd_virmidi_dev *rdev = rmidi->private_data; if (rdev->seq_mode == SNDRV_VIRMIDI_SEQ_DISPATCH) snd_virmidi_dev_detach_seq(rdev); return 0; } /* * */ static struct snd_rawmidi_global_ops snd_virmidi_global_ops = { .dev_register = snd_virmidi_dev_register, .dev_unregister = snd_virmidi_dev_unregister, }; /* * free device */ static void snd_virmidi_free(struct snd_rawmidi *rmidi) { struct snd_virmidi_dev *rdev = rmidi->private_data; kfree(rdev); } /* * create a new device * */ /* exported */ int snd_virmidi_new(struct snd_card *card, int device, struct snd_rawmidi **rrmidi) { struct snd_rawmidi *rmidi; struct snd_virmidi_dev *rdev; int err; *rrmidi = NULL; if ((err = snd_rawmidi_new(card, "VirMidi", device, 16, /* may be configurable */ 16, /* may be configurable */ &rmidi)) < 0) return err; strcpy(rmidi->name, rmidi->id); rdev = kzalloc(sizeof(*rdev), GFP_KERNEL); if (rdev == NULL) { snd_device_free(card, rmidi); return -ENOMEM; } rdev->card = card; rdev->rmidi = rmidi; rdev->device = device; rdev->client = -1; rwlock_init(&rdev->filelist_lock); INIT_LIST_HEAD(&rdev->filelist); rdev->seq_mode = SNDRV_VIRMIDI_SEQ_DISPATCH; rmidi->private_data = rdev; rmidi->private_free = snd_virmidi_free; rmidi->ops = &snd_virmidi_global_ops; snd_rawmidi_set_ops(rmidi, SNDRV_RAWMIDI_STREAM_INPUT, &snd_virmidi_input_ops); snd_rawmidi_set_ops(rmidi, SNDRV_RAWMIDI_STREAM_OUTPUT, &snd_virmidi_output_ops); rmidi->info_flags = SNDRV_RAWMIDI_INFO_INPUT | SNDRV_RAWMIDI_INFO_OUTPUT | SNDRV_RAWMIDI_INFO_DUPLEX; *rrmidi = rmidi; return 0; } /* * ENTRY functions */ static int __init alsa_virmidi_init(void) { return 0; } static void __exit alsa_virmidi_exit(void) { } module_init(alsa_virmidi_init) module_exit(alsa_virmidi_exit) EXPORT_SYMBOL(snd_virmidi_new);
gpl-2.0
KDr2/linux
arch/sh/boards/mach-r2d/setup.c
12287
7390
/* * Renesas Technology Sales RTS7751R2D Support. * * Copyright (C) 2002 - 2006 Atom Create Engineering Co., Ltd. * Copyright (C) 2004 - 2007 Paul Mundt * * This file is subject to the terms and conditions of the GNU General Public * License. See the file "COPYING" in the main directory of this archive * for more details. */ #include <linux/init.h> #include <linux/platform_device.h> #include <linux/mtd/mtd.h> #include <linux/mtd/partitions.h> #include <linux/mtd/physmap.h> #include <linux/ata_platform.h> #include <linux/sm501.h> #include <linux/sm501-regs.h> #include <linux/pm.h> #include <linux/fb.h> #include <linux/spi/spi.h> #include <linux/spi/spi_bitbang.h> #include <asm/machvec.h> #include <mach/r2d.h> #include <asm/io.h> #include <asm/io_trapped.h> #include <asm/spi.h> static struct resource cf_ide_resources[] = { [0] = { .start = PA_AREA5_IO + 0x1000, .end = PA_AREA5_IO + 0x1000 + 0x10 - 0x2, .flags = IORESOURCE_MEM, }, [1] = { .start = PA_AREA5_IO + 0x80c, .end = PA_AREA5_IO + 0x80c, .flags = IORESOURCE_MEM, }, #ifndef CONFIG_RTS7751R2D_1 /* For R2D-1 polling is preferred */ [2] = { .start = IRQ_CF_IDE, .flags = IORESOURCE_IRQ, }, #endif }; static struct pata_platform_info pata_info = { .ioport_shift = 1, }; static struct platform_device cf_ide_device = { .name = "pata_platform", .id = -1, .num_resources = ARRAY_SIZE(cf_ide_resources), .resource = cf_ide_resources, .dev = { .platform_data = &pata_info, }, }; static struct spi_board_info spi_bus[] = { { .modalias = "rtc-r9701", .max_speed_hz = 1000000, .mode = SPI_MODE_3, }, }; static void r2d_chip_select(struct sh_spi_info *spi, int cs, int state) { BUG_ON(cs != 0); /* Single Epson RTC-9701JE attached on CS0 */ __raw_writew(state == BITBANG_CS_ACTIVE, PA_RTCCE); } static struct sh_spi_info spi_info = { .num_chipselect = 1, .chip_select = r2d_chip_select, }; static struct resource spi_sh_sci_resources[] = { { .start = 0xffe00000, .end = 0xffe0001f, .flags = IORESOURCE_MEM, }, }; static struct platform_device spi_sh_sci_device = { .name = "spi_sh_sci", .id = -1, .num_resources = ARRAY_SIZE(spi_sh_sci_resources), .resource = spi_sh_sci_resources, .dev = { .platform_data = &spi_info, }, }; static struct resource heartbeat_resources[] = { [0] = { .start = PA_OUTPORT, .end = PA_OUTPORT, .flags = IORESOURCE_MEM, }, }; static struct platform_device heartbeat_device = { .name = "heartbeat", .id = -1, .num_resources = ARRAY_SIZE(heartbeat_resources), .resource = heartbeat_resources, }; static struct resource sm501_resources[] = { [0] = { .start = 0x10000000, .end = 0x13e00000 - 1, .flags = IORESOURCE_MEM, }, [1] = { .start = 0x13e00000, .end = 0x13ffffff, .flags = IORESOURCE_MEM, }, [2] = { .start = IRQ_VOYAGER, .flags = IORESOURCE_IRQ, }, }; static struct fb_videomode sm501_default_mode = { .pixclock = 35714, .xres = 640, .yres = 480, .left_margin = 105, .right_margin = 50, .upper_margin = 35, .lower_margin = 0, .hsync_len = 96, .vsync_len = 2, .sync = FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT, }; static struct sm501_platdata_fbsub sm501_pdata_fbsub_pnl = { .def_bpp = 16, .def_mode = &sm501_default_mode, .flags = SM501FB_FLAG_USE_INIT_MODE | SM501FB_FLAG_USE_HWCURSOR | SM501FB_FLAG_USE_HWACCEL | SM501FB_FLAG_DISABLE_AT_EXIT, }; static struct sm501_platdata_fbsub sm501_pdata_fbsub_crt = { .flags = (SM501FB_FLAG_USE_INIT_MODE | SM501FB_FLAG_USE_HWCURSOR | SM501FB_FLAG_USE_HWACCEL | SM501FB_FLAG_DISABLE_AT_EXIT), }; static struct sm501_platdata_fb sm501_fb_pdata = { .fb_route = SM501_FB_OWN, .fb_crt = &sm501_pdata_fbsub_crt, .fb_pnl = &sm501_pdata_fbsub_pnl, .flags = SM501_FBPD_SWAP_FB_ENDIAN, }; static struct sm501_initdata sm501_initdata = { .devices = SM501_USE_USB_HOST | SM501_USE_UART0, }; static struct sm501_platdata sm501_platform_data = { .init = &sm501_initdata, .fb = &sm501_fb_pdata, }; static struct platform_device sm501_device = { .name = "sm501", .id = -1, .dev = { .platform_data = &sm501_platform_data, }, .num_resources = ARRAY_SIZE(sm501_resources), .resource = sm501_resources, }; static struct mtd_partition r2d_partitions[] = { { .name = "U-Boot", .offset = 0x00000000, .size = 0x00040000, .mask_flags = MTD_WRITEABLE, }, { .name = "Environment", .offset = MTDPART_OFS_NXTBLK, .size = 0x00040000, .mask_flags = MTD_WRITEABLE, }, { .name = "Kernel", .offset = MTDPART_OFS_NXTBLK, .size = 0x001c0000, }, { .name = "Flash_FS", .offset = MTDPART_OFS_NXTBLK, .size = MTDPART_SIZ_FULL, } }; static struct physmap_flash_data flash_data = { .width = 2, .nr_parts = ARRAY_SIZE(r2d_partitions), .parts = r2d_partitions, }; static struct resource flash_resource = { .start = 0x00000000, .end = 0x02000000, .flags = IORESOURCE_MEM, }; static struct platform_device flash_device = { .name = "physmap-flash", .id = -1, .resource = &flash_resource, .num_resources = 1, .dev = { .platform_data = &flash_data, }, }; static struct platform_device *rts7751r2d_devices[] __initdata = { &sm501_device, &heartbeat_device, &spi_sh_sci_device, }; /* * The CF is connected with a 16-bit bus where 8-bit operations are * unsupported. The linux ata driver is however using 8-bit operations, so * insert a trapped io filter to convert 8-bit operations into 16-bit. */ static struct trapped_io cf_trapped_io = { .resource = cf_ide_resources, .num_resources = 2, .minimum_bus_width = 16, }; static int __init rts7751r2d_devices_setup(void) { if (register_trapped_io(&cf_trapped_io) == 0) platform_device_register(&cf_ide_device); if (mach_is_r2d_plus()) platform_device_register(&flash_device); spi_register_board_info(spi_bus, ARRAY_SIZE(spi_bus)); return platform_add_devices(rts7751r2d_devices, ARRAY_SIZE(rts7751r2d_devices)); } device_initcall(rts7751r2d_devices_setup); static void rts7751r2d_power_off(void) { __raw_writew(0x0001, PA_POWOFF); } /* * Initialize the board */ static void __init rts7751r2d_setup(char **cmdline_p) { void __iomem *sm501_reg; u16 ver = __raw_readw(PA_VERREG); printk(KERN_INFO "Renesas Technology Sales RTS7751R2D support.\n"); printk(KERN_INFO "FPGA version:%d (revision:%d)\n", (ver >> 4) & 0xf, ver & 0xf); __raw_writew(0x0000, PA_OUTPORT); pm_power_off = rts7751r2d_power_off; /* sm501 dram configuration: * ColSizeX = 11 - External Memory Column Size: 256 words. * APX = 1 - External Memory Active to Pre-Charge Delay: 7 clocks. * RstX = 1 - External Memory Reset: Normal. * Rfsh = 1 - Local Memory Refresh to Command Delay: 12 clocks. * BwC = 1 - Local Memory Block Write Cycle Time: 2 clocks. * BwP = 1 - Local Memory Block Write to Pre-Charge Delay: 1 clock. * AP = 1 - Internal Memory Active to Pre-Charge Delay: 7 clocks. * Rst = 1 - Internal Memory Reset: Normal. * RA = 1 - Internal Memory Remain in Active State: Do not remain. */ sm501_reg = (void __iomem *)0xb3e00000 + SM501_DRAM_CONTROL; writel(readl(sm501_reg) | 0x00f107c0, sm501_reg); } /* * The Machine Vector */ static struct sh_machine_vector mv_rts7751r2d __initmv = { .mv_name = "RTS7751R2D", .mv_setup = rts7751r2d_setup, .mv_init_irq = init_rts7751r2d_IRQ, .mv_irq_demux = rts7751r2d_irq_demux, };
gpl-2.0
JohnKDay/linux
arch/sh/boards/mach-rsk/devices-rsk7203.c
12287
3199
/* * Renesas Technology Europe RSK+ 7203 Support. * * Copyright (C) 2008 - 2010 Paul Mundt * * This file is subject to the terms and conditions of the GNU General Public * License. See the file "COPYING" in the main directory of this archive * for more details. */ #include <linux/init.h> #include <linux/types.h> #include <linux/platform_device.h> #include <linux/interrupt.h> #include <linux/smsc911x.h> #include <linux/input.h> #include <linux/gpio.h> #include <linux/gpio_keys.h> #include <linux/leds.h> #include <asm/machvec.h> #include <asm/io.h> #include <cpu/sh7203.h> static struct smsc911x_platform_config smsc911x_config = { .phy_interface = PHY_INTERFACE_MODE_MII, .irq_polarity = SMSC911X_IRQ_POLARITY_ACTIVE_LOW, .irq_type = SMSC911X_IRQ_TYPE_OPEN_DRAIN, .flags = SMSC911X_USE_32BIT | SMSC911X_SWAP_FIFO, }; static struct resource smsc911x_resources[] = { [0] = { .start = 0x24000000, .end = 0x240000ff, .flags = IORESOURCE_MEM, }, [1] = { .start = 64, .end = 64, .flags = IORESOURCE_IRQ, }, }; static struct platform_device smsc911x_device = { .name = "smsc911x", .id = -1, .num_resources = ARRAY_SIZE(smsc911x_resources), .resource = smsc911x_resources, .dev = { .platform_data = &smsc911x_config, }, }; static struct gpio_led rsk7203_gpio_leds[] = { { .name = "green", .gpio = GPIO_PE10, .active_low = 1, }, { .name = "orange", .default_trigger = "nand-disk", .gpio = GPIO_PE12, .active_low = 1, }, { .name = "red:timer", .default_trigger = "timer", .gpio = GPIO_PC14, .active_low = 1, }, { .name = "red:heartbeat", .default_trigger = "heartbeat", .gpio = GPIO_PE11, .active_low = 1, }, }; static struct gpio_led_platform_data rsk7203_gpio_leds_info = { .leds = rsk7203_gpio_leds, .num_leds = ARRAY_SIZE(rsk7203_gpio_leds), }; static struct platform_device led_device = { .name = "leds-gpio", .id = -1, .dev = { .platform_data = &rsk7203_gpio_leds_info, }, }; static struct gpio_keys_button rsk7203_gpio_keys_table[] = { { .code = BTN_0, .gpio = GPIO_PB0, .active_low = 1, .desc = "SW1", }, { .code = BTN_1, .gpio = GPIO_PB1, .active_low = 1, .desc = "SW2", }, { .code = BTN_2, .gpio = GPIO_PB2, .active_low = 1, .desc = "SW3", }, }; static struct gpio_keys_platform_data rsk7203_gpio_keys_info = { .buttons = rsk7203_gpio_keys_table, .nbuttons = ARRAY_SIZE(rsk7203_gpio_keys_table), .poll_interval = 50, /* default to 50ms */ }; static struct platform_device keys_device = { .name = "gpio-keys-polled", .dev = { .platform_data = &rsk7203_gpio_keys_info, }, }; static struct platform_device *rsk7203_devices[] __initdata = { &smsc911x_device, &led_device, &keys_device, }; static int __init rsk7203_devices_setup(void) { /* Select pins for SCIF0 */ gpio_request(GPIO_FN_TXD0, NULL); gpio_request(GPIO_FN_RXD0, NULL); /* Setup LAN9118: CS1 in 16-bit Big Endian Mode, IRQ0 at Port B */ __raw_writel(0x36db0400, 0xfffc0008); /* CS1BCR */ gpio_request(GPIO_FN_IRQ0_PB, NULL); return platform_add_devices(rsk7203_devices, ARRAY_SIZE(rsk7203_devices)); } device_initcall(rsk7203_devices_setup);
gpl-2.0
samba-team/samba
source3/winbindd/winbindd_traceid.c
1
5180
/* Authors: Pavel Březina <pbrezina@redhat.com> Copyright (C) 2021 Red Hat This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "lib/util/debug.h" #include "winbindd_traceid.h" #include "tevent.h" static void debug_traceid_trace_fde(struct tevent_fd *fde, enum tevent_event_trace_point point, void *private_data) { switch (point) { case TEVENT_EVENT_TRACE_ATTACH: /* Assign the current traceid id when the event is created. */ tevent_fd_set_tag(fde, debug_traceid_get()); break; case TEVENT_EVENT_TRACE_BEFORE_HANDLER: /* Set the traceid id when a handler is being called. */ debug_traceid_set(tevent_fd_get_tag(fde)); break; default: /* Do nothing. */ break; } } static void debug_traceid_trace_signal(struct tevent_signal *se, enum tevent_event_trace_point point, void *private_data) { switch (point) { case TEVENT_EVENT_TRACE_ATTACH: /* Assign the current traceid id when the event is created. */ tevent_signal_set_tag(se, debug_traceid_get()); break; case TEVENT_EVENT_TRACE_BEFORE_HANDLER: /* Set the traceid id when a handler is being called. */ debug_traceid_set(tevent_signal_get_tag(se)); break; default: /* Do nothing. */ break; } } static void debug_traceid_trace_timer(struct tevent_timer *timer, enum tevent_event_trace_point point, void *private_data) { switch (point) { case TEVENT_EVENT_TRACE_ATTACH: /* Assign the current traceid id when the event is created. */ tevent_timer_set_tag(timer, debug_traceid_get()); break; case TEVENT_EVENT_TRACE_BEFORE_HANDLER: /* Set the traceid id when a handler is being called. */ debug_traceid_set(tevent_timer_get_tag(timer)); break; default: /* Do nothing. */ break; } } static void debug_traceid_trace_immediate(struct tevent_immediate *im, enum tevent_event_trace_point point, void *private_data) { switch (point) { case TEVENT_EVENT_TRACE_ATTACH: /* Assign the current traceid id when the event is created. */ tevent_immediate_set_tag(im, debug_traceid_get()); break; case TEVENT_EVENT_TRACE_BEFORE_HANDLER: /* Set the traceid id when a handler is being called. */ debug_traceid_set(tevent_immediate_get_tag(im)); break; default: /* Do nothing. */ break; } } static void debug_traceid_trace_queue(struct tevent_queue_entry *qe, enum tevent_event_trace_point point, void *private_data) { switch (point) { case TEVENT_EVENT_TRACE_ATTACH: /* Assign the current traceid id when the event is created. */ tevent_queue_entry_set_tag(qe, debug_traceid_get()); break; case TEVENT_EVENT_TRACE_BEFORE_HANDLER: /* Set the traceid id when a handler is being called. */ debug_traceid_set(tevent_queue_entry_get_tag(qe)); break; default: /* Do nothing. */ break; } } static void debug_traceid_trace_loop(enum tevent_trace_point point, void *private_data) { switch (point) { case TEVENT_TRACE_AFTER_LOOP_ONCE: /* Reset traceid id when we got back to the loop. An event handler * that set traceid id was fired. This tracepoint represents a place * after the event handler was finished, we need to restore traceid * id to 1 (out of request). 0 means not initialized. */ debug_traceid_set(1); break; default: /* Do nothing. */ break; } } void winbind_debug_traceid_setup(struct tevent_context *ev) { tevent_set_trace_callback(ev, debug_traceid_trace_loop, NULL); tevent_set_trace_fd_callback(ev, debug_traceid_trace_fde, NULL); tevent_set_trace_signal_callback(ev, debug_traceid_trace_signal, NULL); tevent_set_trace_timer_callback(ev, debug_traceid_trace_timer, NULL); tevent_set_trace_immediate_callback(ev, debug_traceid_trace_immediate, NULL); tevent_set_trace_queue_callback(ev, debug_traceid_trace_queue, NULL); debug_traceid_set(1); }
gpl-3.0
SanderMertens/opensplice
src/api/dcps/ccpp/code/ccpp_QosUtils.cpp
1
69293
/* * OpenSplice DDS * * This software and documentation are Copyright 2006 to 2013 PrismTech * Limited and its licensees. All rights reserved. See file: * * $OSPL_HOME/LICENSE * * for full copyright notice and license terms. * */ #include "ccpp_dds_builtinTopics.h" #include "ccpp_dds_namedQosTypes.h" #include "ccpp_QosUtils.h" #include "qp_qosProvider.h" #include "orb_abstraction.h" namespace DDS { static const DDS::UserDataQosPolicy DEFAULT_USERDATA_QOSPOLICY = { DDS::octSeq() }; static const DDS::TopicDataQosPolicy DEFAULT_TOPICDATA_QOSPOLICY = { DDS::octSeq() }; static const DDS::GroupDataQosPolicy DEFAULT_GROUPDATA_QOSPOLICY = { DDS::octSeq() }; static const DDS::TransportPriorityQosPolicy DEFAULT_TRANSPORTPRIORITY_QOSPOLICY = { 0L }; static const DDS::LifespanQosPolicy DEFAULT_LIFESPAN_QOSPOLICY = { {DURATION_INFINITE_SEC, DURATION_INFINITE_NSEC} }; static const DDS::DurabilityQosPolicy DEFAULT_DURABILITY_QOSPOLICY = { VOLATILE_DURABILITY_QOS }; static const DDS::DurabilityServiceQosPolicy DEFAULT_DURABILITYSERVICE_QOSPOLICY = { {DURATION_ZERO_SEC, DURATION_ZERO_NSEC}, KEEP_LAST_HISTORY_QOS, 1L, LENGTH_UNLIMITED, LENGTH_UNLIMITED, LENGTH_UNLIMITED }; static const DDS::PresentationQosPolicy DEFAULT_PRESENTATION_QOSPOLICY = { INSTANCE_PRESENTATION_QOS, false, false }; static const DDS::DeadlineQosPolicy DEFAULT_DEADLINE_QOSPOLICY = { {DURATION_INFINITE_SEC, DURATION_INFINITE_NSEC} }; static const DDS::LatencyBudgetQosPolicy DEFAULT_LATENCYBUDGET_QOSPOLICY = { {DURATION_ZERO_SEC, DURATION_ZERO_NSEC} }; static const DDS::OwnershipQosPolicy DEFAULT_OWNERSHIP_QOSPOLICY = { SHARED_OWNERSHIP_QOS }; static const DDS::OwnershipStrengthQosPolicy DEFAULT_OWNERSHIPSTRENGTH_QOSPOLICY = { 0L }; static const DDS::LivelinessQosPolicy DEFAULT_LIVELINESS_QOSPOLICY = { AUTOMATIC_LIVELINESS_QOS, {DURATION_INFINITE_SEC, DURATION_INFINITE_NSEC} }; static const DDS::TimeBasedFilterQosPolicy DEFAULT_TIMEBASEDFILTER_QOSPOLICY = { {DURATION_ZERO_SEC, DURATION_ZERO_NSEC} }; static const DDS::PartitionQosPolicy DEFAULT_PARTITION_QOSPOLICY = { DDS::StringSeq() }; static const DDS::ReliabilityQosPolicy DEFAULT_RELIABILITY_QOSPOLICY = { BEST_EFFORT_RELIABILITY_QOS, {0, 100000000} }; static const DDS::DestinationOrderQosPolicy DEFAULT_DESTINATIONORDER_QOSPOLICY = { BY_RECEPTION_TIMESTAMP_DESTINATIONORDER_QOS }; static const DDS::HistoryQosPolicy DEFAULT_HISTORY_QOSPOLICY = { KEEP_LAST_HISTORY_QOS, 1L }; static const DDS::ResourceLimitsQosPolicy DEFAULT_RESOURCELIMITS_QOSPOLICY = { LENGTH_UNLIMITED, LENGTH_UNLIMITED, LENGTH_UNLIMITED }; static const DDS::EntityFactoryQosPolicy DEFAULT_ENTITYFACTORY_QOSPOLICY = { true }; static const DDS::WriterDataLifecycleQosPolicy DEFAULT_WRITERDATALIFECYCLE_QOSPOLICY= { true, {DURATION_INFINITE_SEC, DURATION_INFINITE_NSEC}, {DURATION_INFINITE_SEC, DURATION_INFINITE_NSEC} }; static const DDS::ReaderDataLifecycleQosPolicy DEFAULT_READERDATALIFECYCLE_QOSPOLICY= { {DURATION_INFINITE_SEC, DURATION_INFINITE_NSEC}, {DURATION_INFINITE_SEC, DURATION_INFINITE_NSEC}, true, { MINIMUM_INVALID_SAMPLES } }; static const DDS::SchedulingQosPolicy DEFAULT_SCHEDULING_QOSPOLICY= { { SCHEDULE_DEFAULT }, { PRIORITY_RELATIVE }, 0 }; static const DDS::SubscriptionKeyQosPolicy DEFAULT_SUBSCRIPTIONKEY_QOSPOLICY= { false, DDS::StringSeq() }; static const DDS::ReaderLifespanQosPolicy DEFAULT_READERLIFESPAN_QOSPOLICY= { false, {DURATION_INFINITE_SEC, DURATION_INFINITE_NSEC} }; static const DDS::ShareQosPolicy DEFAULT_SHARE_QOSPOLICY= { "", false }; static const DDS::ViewKeyQosPolicy DEFAULT_VIEWKEY_QOSPOLICY= { false, DDS::StringSeq() }; static DDS::DomainParticipantFactoryQos * const initializeParticipantFactoryQos() { DDS::DomainParticipantFactoryQos *qos = new DDS::DomainParticipantFactoryQos(); qos->entity_factory = DEFAULT_ENTITYFACTORY_QOSPOLICY; return qos; } static DDS::DomainParticipantQos * const initializeParticipantQos() { DDS::DomainParticipantQos *qos = new DDS::DomainParticipantQos(); qos->user_data = DEFAULT_USERDATA_QOSPOLICY; qos->entity_factory = DEFAULT_ENTITYFACTORY_QOSPOLICY; qos->watchdog_scheduling = DEFAULT_SCHEDULING_QOSPOLICY; qos->listener_scheduling = DEFAULT_SCHEDULING_QOSPOLICY; return qos; } static DDS::TopicQos * const initializeTopicQos() { DDS::TopicQos *qos = new DDS::TopicQos(); qos->topic_data = DEFAULT_TOPICDATA_QOSPOLICY; qos->durability = DEFAULT_DURABILITY_QOSPOLICY; qos->durability_service = DEFAULT_DURABILITYSERVICE_QOSPOLICY; qos->deadline = DEFAULT_DEADLINE_QOSPOLICY; qos->latency_budget = DEFAULT_LATENCYBUDGET_QOSPOLICY; qos->liveliness = DEFAULT_LIVELINESS_QOSPOLICY; qos->reliability = DEFAULT_RELIABILITY_QOSPOLICY; qos->destination_order = DEFAULT_DESTINATIONORDER_QOSPOLICY; qos->history = DEFAULT_HISTORY_QOSPOLICY; qos->resource_limits = DEFAULT_RESOURCELIMITS_QOSPOLICY; qos->transport_priority = DEFAULT_TRANSPORTPRIORITY_QOSPOLICY; qos->lifespan = DEFAULT_LIFESPAN_QOSPOLICY; qos->ownership = DEFAULT_OWNERSHIP_QOSPOLICY; return qos; } static DDS::PublisherQos * const initializePublisherQos() { DDS::PublisherQos *qos = new DDS::PublisherQos(); qos->presentation = DEFAULT_PRESENTATION_QOSPOLICY; qos->partition = DEFAULT_PARTITION_QOSPOLICY; qos->group_data = DEFAULT_GROUPDATA_QOSPOLICY; qos->entity_factory = DEFAULT_ENTITYFACTORY_QOSPOLICY; return qos; } static DDS::SubscriberQos * const initializeSubscriberQos() { DDS::SubscriberQos *qos = new DDS::SubscriberQos(); qos->presentation = DEFAULT_PRESENTATION_QOSPOLICY; qos->partition = DEFAULT_PARTITION_QOSPOLICY; qos->group_data = DEFAULT_GROUPDATA_QOSPOLICY; qos->entity_factory = DEFAULT_ENTITYFACTORY_QOSPOLICY; qos->share = DEFAULT_SHARE_QOSPOLICY; return qos; } static DDS::DataReaderQos * const initializeDataReaderQos() { DDS::DataReaderQos *qos = new DDS::DataReaderQos(); qos->durability = DEFAULT_DURABILITY_QOSPOLICY; qos->deadline = DEFAULT_DEADLINE_QOSPOLICY; qos->latency_budget = DEFAULT_LATENCYBUDGET_QOSPOLICY; qos->liveliness = DEFAULT_LIVELINESS_QOSPOLICY; qos->reliability = DEFAULT_RELIABILITY_QOSPOLICY; qos->destination_order = DEFAULT_DESTINATIONORDER_QOSPOLICY; qos->history = DEFAULT_HISTORY_QOSPOLICY; qos->resource_limits = DEFAULT_RESOURCELIMITS_QOSPOLICY; qos->user_data = DEFAULT_USERDATA_QOSPOLICY; qos->ownership = DEFAULT_OWNERSHIP_QOSPOLICY; qos->time_based_filter = DEFAULT_TIMEBASEDFILTER_QOSPOLICY; qos->reader_data_lifecycle = DEFAULT_READERDATALIFECYCLE_QOSPOLICY; qos->subscription_keys = DEFAULT_SUBSCRIPTIONKEY_QOSPOLICY; qos->reader_lifespan = DEFAULT_READERLIFESPAN_QOSPOLICY; qos->share = DEFAULT_SHARE_QOSPOLICY; return qos; } static DDS::DataReaderViewQos * const initializeDataReaderViewQos() { DDS::DataReaderViewQos *qos = new DDS::DataReaderViewQos(); qos->view_keys = DEFAULT_VIEWKEY_QOSPOLICY; return qos; } static DDS::DataWriterQos * const initializeDataWriterQos() { DDS::DataWriterQos *qos = new DDS::DataWriterQos(); qos->durability = DEFAULT_DURABILITY_QOSPOLICY; qos->deadline = DEFAULT_DEADLINE_QOSPOLICY; qos->latency_budget = DEFAULT_LATENCYBUDGET_QOSPOLICY; qos->liveliness = DEFAULT_LIVELINESS_QOSPOLICY; qos->reliability = DEFAULT_RELIABILITY_QOSPOLICY; qos->reliability.kind = RELIABLE_RELIABILITY_QOS; qos->destination_order = DEFAULT_DESTINATIONORDER_QOSPOLICY; qos->history = DEFAULT_HISTORY_QOSPOLICY; qos->resource_limits = DEFAULT_RESOURCELIMITS_QOSPOLICY; qos->transport_priority = DEFAULT_TRANSPORTPRIORITY_QOSPOLICY; qos->lifespan = DEFAULT_LIFESPAN_QOSPOLICY; qos->user_data = DEFAULT_USERDATA_QOSPOLICY; qos->ownership = DEFAULT_OWNERSHIP_QOSPOLICY; qos->ownership_strength = DEFAULT_OWNERSHIPSTRENGTH_QOSPOLICY; qos->writer_data_lifecycle = DEFAULT_WRITERDATALIFECYCLE_QOSPOLICY; return qos; } //static const DDS::DefaultQos UniqueInstance; DDS::DomainParticipantFactoryQos_var DDS::DefaultQos::ParticipantFactoryQosDefault = DDS::initializeParticipantFactoryQos(); DDS::DomainParticipantQos_var DDS::DefaultQos::ParticipantQosDefault = DDS::initializeParticipantQos(); DDS::TopicQos_var DDS::DefaultQos::TopicQosDefault = DDS::initializeTopicQos(); DDS::PublisherQos_var DDS::DefaultQos::PublisherQosDefault = DDS::initializePublisherQos(); DDS::SubscriberQos_var DDS::DefaultQos::SubscriberQosDefault = DDS::initializeSubscriberQos(); DDS::DataReaderQos_var DDS::DefaultQos::DataReaderQosDefault = DDS::initializeDataReaderQos(); DDS::DataReaderQos_var DDS::DefaultQos::DataReaderQosUseTopicQos = DDS::initializeDataReaderQos(); DDS::DataReaderViewQos_var DDS::DefaultQos::DataReaderViewQosDefault = DDS::initializeDataReaderViewQos(); DDS::DataWriterQos_var DDS::DefaultQos::DataWriterQosDefault = DDS::initializeDataWriterQos(); DDS::DataWriterQos_var DDS::DefaultQos::DataWriterQosUseTopicQos = DDS::initializeDataWriterQos(); }; extern c_bool __DDS_NamedDomainParticipantQos__copyIn_noCache( c_base base, struct DDS::NamedDomainParticipantQos *from, struct _DDS_NamedDomainParticipantQos *to); extern void __DDS_NamedDomainParticipantQos__copyOut( void *_from, void *_to); extern c_bool __DDS_NamedPublisherQos__copyIn_noCache( c_base base, struct DDS::NamedPublisherQos *from, struct _DDS_NamedPublisherQos *to); extern void __DDS_NamedPublisherQos__copyOut( void *_from, void *_to); extern c_bool __DDS_NamedSubscriberQos__copyIn_noCache( c_base base, struct DDS::NamedSubscriberQos *from, struct _DDS_NamedSubscriberQos *to); extern void __DDS_NamedSubscriberQos__copyOut( void *_from, void *_to); extern c_bool __DDS_NamedTopicQos__copyIn_noCache( c_base base, struct DDS::NamedTopicQos *from, struct _DDS_NamedTopicQos *to); extern void __DDS_NamedTopicQos__copyOut( void *_from, void *_to); extern c_bool __DDS_NamedDataWriterQos__copyIn_noCache( c_base base, struct DDS::NamedDataWriterQos *from, struct _DDS_NamedDataWriterQos *to); extern void __DDS_NamedDataWriterQos__copyOut( void *_from, void *_to); extern c_bool __DDS_NamedDataReaderQos__copyIn_noCache( c_base base, struct DDS::NamedDataReaderQos *from, struct _DDS_NamedDataReaderQos *to); extern void __DDS_NamedDataReaderQos__copyOut( void *_from, void *_to); namespace DDS { static const NamedDomainParticipantQos defaultNamedParticipantQos = { "", { DEFAULT_USERDATA_QOSPOLICY, DEFAULT_ENTITYFACTORY_QOSPOLICY, DEFAULT_SCHEDULING_QOSPOLICY, DEFAULT_SCHEDULING_QOSPOLICY } }; static const NamedTopicQos defaultNamedTopicQos = { "", { DEFAULT_TOPICDATA_QOSPOLICY, DEFAULT_DURABILITY_QOSPOLICY, DEFAULT_DURABILITYSERVICE_QOSPOLICY, DEFAULT_DEADLINE_QOSPOLICY, DEFAULT_LATENCYBUDGET_QOSPOLICY, DEFAULT_LIVELINESS_QOSPOLICY, DEFAULT_RELIABILITY_QOSPOLICY, DEFAULT_DESTINATIONORDER_QOSPOLICY, DEFAULT_HISTORY_QOSPOLICY, DEFAULT_RESOURCELIMITS_QOSPOLICY, DEFAULT_TRANSPORTPRIORITY_QOSPOLICY, DEFAULT_LIFESPAN_QOSPOLICY, DEFAULT_OWNERSHIP_QOSPOLICY } }; static const NamedSubscriberQos defaultNamedSubscriberQos = { "", { DEFAULT_PRESENTATION_QOSPOLICY, DEFAULT_PARTITION_QOSPOLICY, DEFAULT_GROUPDATA_QOSPOLICY, DEFAULT_ENTITYFACTORY_QOSPOLICY, DEFAULT_SHARE_QOSPOLICY } }; static const NamedDataReaderQos defaultNamedDataReaderQos = { "", { DEFAULT_DURABILITY_QOSPOLICY, DEFAULT_DEADLINE_QOSPOLICY, DEFAULT_LATENCYBUDGET_QOSPOLICY, DEFAULT_LIVELINESS_QOSPOLICY, DEFAULT_RELIABILITY_QOSPOLICY, DEFAULT_DESTINATIONORDER_QOSPOLICY, DEFAULT_HISTORY_QOSPOLICY, DEFAULT_RESOURCELIMITS_QOSPOLICY, DEFAULT_USERDATA_QOSPOLICY, DEFAULT_OWNERSHIP_QOSPOLICY, DEFAULT_TIMEBASEDFILTER_QOSPOLICY, DEFAULT_READERDATALIFECYCLE_QOSPOLICY, DEFAULT_SUBSCRIPTIONKEY_QOSPOLICY, DEFAULT_READERLIFESPAN_QOSPOLICY, DEFAULT_SHARE_QOSPOLICY } }; static const NamedPublisherQos defaultNamedPublisherQos = { "", { DEFAULT_PRESENTATION_QOSPOLICY, DEFAULT_PARTITION_QOSPOLICY, DEFAULT_GROUPDATA_QOSPOLICY, DEFAULT_ENTITYFACTORY_QOSPOLICY } }; static const NamedDataWriterQos defaultNamedDataWriterQos = { "", { DEFAULT_DURABILITY_QOSPOLICY, DEFAULT_DEADLINE_QOSPOLICY, DEFAULT_LATENCYBUDGET_QOSPOLICY, DEFAULT_LIVELINESS_QOSPOLICY, {RELIABLE_RELIABILITY_QOS, {0, 100000000}}, DEFAULT_DESTINATIONORDER_QOSPOLICY, DEFAULT_HISTORY_QOSPOLICY, DEFAULT_RESOURCELIMITS_QOSPOLICY, DEFAULT_TRANSPORTPRIORITY_QOSPOLICY, DEFAULT_LIFESPAN_QOSPOLICY, DEFAULT_USERDATA_QOSPOLICY, DEFAULT_OWNERSHIP_QOSPOLICY, DEFAULT_OWNERSHIPSTRENGTH_QOSPOLICY, DEFAULT_WRITERDATALIFECYCLE_QOSPOLICY } }; /* The below qosProviderAttr uses the defaults supplied by the qosProvider * implementation. If a C++ QoS would have to be used, the idlpp-generated * copyIn-function with static type-caching disabled should be used. By * default these are named __DDS_NamedDomainParticipantQos__copyIn_noCache, * etc. */ static const C_STRUCT(qp_qosProviderInputAttr) qosProviderAttr = { { /* ParticipantQos */ (qp_copyOut)&__DDS_NamedDomainParticipantQos__copyOut }, { /* TopicQos */ (qp_copyOut)&__DDS_NamedTopicQos__copyOut }, { /* SubscriberQos */ (qp_copyOut)&__DDS_NamedSubscriberQos__copyOut }, { /* DataReaderQos */ (qp_copyOut)&__DDS_NamedDataReaderQos__copyOut }, { /* PublisherQos */ (qp_copyOut)&__DDS_NamedPublisherQos__copyOut }, { /* DataWriterQos */ (qp_copyOut)&__DDS_NamedDataWriterQos__copyOut } }; const C_STRUCT(qp_qosProviderInputAttr) * ccpp_getQosProviderInputAttr() { return &qosProviderAttr; } } //policies conversions void DDS::ccpp_UserDataQosPolicy_copyIn( const DDS::UserDataQosPolicy &from, gapi_userDataQosPolicy &to ) { DDS::ccpp_sequenceCopyIn<DDS::octSeq, DDS::Octet, gapi_octetSeq, gapi_octet>(from.value, to.value); } void DDS::ccpp_UserDataQosPolicy_copyOut( const gapi_userDataQosPolicy &from, DDS::UserDataQosPolicy &to ) { DDS::ccpp_sequenceCopyOut< gapi_octetSeq, gapi_octet, DDS::octSeq, DDS::Octet >( from.value, to.value ); } void DDS::ccpp_EntityFactoryQosPolicy_copyIn( const DDS::EntityFactoryQosPolicy &from, gapi_entityFactoryQosPolicy &to) { to.autoenable_created_entities = from.autoenable_created_entities; } void DDS::ccpp_EntityFactoryQosPolicy_copyOut( const gapi_entityFactoryQosPolicy &from, DDS::EntityFactoryQosPolicy &to) { to.autoenable_created_entities = from.autoenable_created_entities != 0; } void DDS::ccpp_TopicDataQosPolicy_copyIn( const DDS::TopicDataQosPolicy &from, gapi_topicDataQosPolicy &to) { DDS::ccpp_sequenceCopyIn< DDS::octSeq, DDS::Octet, gapi_octetSeq, gapi_octet >( from.value, to.value ); } void DDS::ccpp_DurabilityQosPolicy_copyIn( const DDS::DurabilityQosPolicy &from, gapi_durabilityQosPolicy &to) { switch(from.kind) { case DDS::VOLATILE_DURABILITY_QOS: to.kind = GAPI_VOLATILE_DURABILITY_QOS; break; case DDS::TRANSIENT_LOCAL_DURABILITY_QOS: to.kind = GAPI_TRANSIENT_LOCAL_DURABILITY_QOS; break; case DDS::TRANSIENT_DURABILITY_QOS: to.kind = GAPI_TRANSIENT_DURABILITY_QOS; break; case DDS::PERSISTENT_DURABILITY_QOS: to.kind = GAPI_PERSISTENT_DURABILITY_QOS; break; default: // impossible to reach break; } } void DDS::ccpp_DurabilityServiceQosPolicy_copyIn( const DDS::DurabilityServiceQosPolicy &from, gapi_durabilityServiceQosPolicy &to) { DDS::ccpp_Duration_copyIn(from.service_cleanup_delay, to.service_cleanup_delay); switch(from.history_kind) { case DDS::KEEP_LAST_HISTORY_QOS: to.history_kind = GAPI_KEEP_LAST_HISTORY_QOS; break; case DDS::KEEP_ALL_HISTORY_QOS: to.history_kind = GAPI_KEEP_ALL_HISTORY_QOS; break; default: // impossible to reach break; } to.history_depth = from.history_depth; to.max_samples = from.max_samples; to.max_instances = from.max_instances; to.max_samples_per_instance = from.max_samples_per_instance; } void DDS::ccpp_DeadlineQosPolicy_copyIn( const DDS::DeadlineQosPolicy &from, gapi_deadlineQosPolicy &to) { DDS::ccpp_Duration_copyIn( from.period, to.period); } void DDS::ccpp_LatencyBudgetQosPolicy_copyIn( const DDS::LatencyBudgetQosPolicy &from, gapi_latencyBudgetQosPolicy &to) { DDS::ccpp_Duration_copyIn( from.duration, to.duration); } void DDS::ccpp_LivelinessQosPolicy_copyIn( const DDS::LivelinessQosPolicy &from, gapi_livelinessQosPolicy &to) { switch (from.kind) { case DDS::AUTOMATIC_LIVELINESS_QOS: to.kind = GAPI_AUTOMATIC_LIVELINESS_QOS; break; case DDS::MANUAL_BY_PARTICIPANT_LIVELINESS_QOS: to.kind = GAPI_MANUAL_BY_PARTICIPANT_LIVELINESS_QOS; break; case DDS::MANUAL_BY_TOPIC_LIVELINESS_QOS: to.kind = GAPI_MANUAL_BY_TOPIC_LIVELINESS_QOS; break; default: //impossible to reach break; } DDS::ccpp_Duration_copyIn(from.lease_duration, to.lease_duration); } void DDS::ccpp_ReliabilityQosPolicy_copyIn( const DDS::ReliabilityQosPolicy &from, gapi_reliabilityQosPolicy &to) { switch (from.kind) { case DDS::BEST_EFFORT_RELIABILITY_QOS: to.kind = GAPI_BEST_EFFORT_RELIABILITY_QOS; break; case DDS::RELIABLE_RELIABILITY_QOS: to.kind = GAPI_RELIABLE_RELIABILITY_QOS; break; default: //impossible to reach break; } DDS::ccpp_Duration_copyIn(from.max_blocking_time, to.max_blocking_time); to.synchronous = from.synchronous ? TRUE : FALSE; } void DDS::ccpp_DestinationOrderQosPolicy_copyIn( const DDS::DestinationOrderQosPolicy &from, gapi_destinationOrderQosPolicy &to) { switch (from.kind) { case DDS::BY_RECEPTION_TIMESTAMP_DESTINATIONORDER_QOS: to.kind = GAPI_BY_RECEPTION_TIMESTAMP_DESTINATIONORDER_QOS; break; case DDS::BY_SOURCE_TIMESTAMP_DESTINATIONORDER_QOS: to.kind = GAPI_BY_SOURCE_TIMESTAMP_DESTINATIONORDER_QOS; break; default: //impossible to reach break; } } void DDS::ccpp_HistoryQosPolicy_copyIn( const DDS::HistoryQosPolicy &from, gapi_historyQosPolicy &to) { switch (from.kind) { case DDS::KEEP_LAST_HISTORY_QOS: to.kind = GAPI_KEEP_LAST_HISTORY_QOS; break; case DDS::KEEP_ALL_HISTORY_QOS: to.kind = GAPI_KEEP_ALL_HISTORY_QOS; break; default: //impossible to reach break; } to.depth = from.depth; } void DDS::ccpp_ResourceLimitsQosPolicy_copyIn( const DDS::ResourceLimitsQosPolicy &from, gapi_resourceLimitsQosPolicy &to) { to.max_samples = from.max_samples; to.max_instances = from.max_instances; to.max_samples_per_instance = from.max_samples_per_instance; } void DDS::ccpp_TransportPriorityQosPolicy_copyIn( const DDS::TransportPriorityQosPolicy &from, gapi_transportPriorityQosPolicy &to) { to.value = from.value; } void DDS::ccpp_LifespanQosPolicy_copyIn( const DDS::LifespanQosPolicy &from, gapi_lifespanQosPolicy &to) { DDS::ccpp_Duration_copyIn( from.duration, to.duration); } void DDS::ccpp_OwnershipQosPolicy_copyIn( const DDS::OwnershipQosPolicy &from, gapi_ownershipQosPolicy &to) { switch (from.kind) { case DDS::SHARED_OWNERSHIP_QOS: to.kind = GAPI_SHARED_OWNERSHIP_QOS; break; case DDS::EXCLUSIVE_OWNERSHIP_QOS: to.kind = GAPI_EXCLUSIVE_OWNERSHIP_QOS; break; default: //impossible to reach break; } } void DDS::ccpp_OwnershipStrengthQosPolicy_copyIn(const DDS::OwnershipStrengthQosPolicy &from, gapi_ownershipStrengthQosPolicy &to) { to.value = from.value; } void DDS::ccpp_WriterDataLifecycleQosPolicy_copyIn( const DDS::WriterDataLifecycleQosPolicy &from, gapi_writerDataLifecycleQosPolicy &to) { to.autodispose_unregistered_instances = from.autodispose_unregistered_instances; DDS::ccpp_Duration_copyIn( from.autopurge_suspended_samples_delay, to.autopurge_suspended_samples_delay); DDS::ccpp_Duration_copyIn( from.autounregister_instance_delay, to.autounregister_instance_delay); } void DDS::ccpp_PresentationQosPolicy_copyIn( const DDS::PresentationQosPolicy & from, gapi_presentationQosPolicy & to) { to.access_scope = (gapi_presentationQosPolicyAccessScopeKind)from.access_scope; to.coherent_access = from.coherent_access; to.ordered_access = from.ordered_access; } void DDS::ccpp_PartitionQosPolicy_copyIn( const DDS::PartitionQosPolicy &from, gapi_partitionQosPolicy &to) { DDS::ccpp_sequenceCopyIn(from.name, to.name); } void DDS::ccpp_GroupDataQosPolicy_copyIn(const DDS::GroupDataQosPolicy &from, gapi_groupDataQosPolicy &to) { DDS::ccpp_sequenceCopyIn< DDS::octSeq, DDS::Octet, gapi_octetSeq, gapi_octet > ( from.value, to.value ); } void DDS::ccpp_TopicDataQosPolicy_copyOut( const gapi_topicDataQosPolicy &from, DDS::TopicDataQosPolicy &to) { DDS::ccpp_sequenceCopyOut< gapi_octetSeq, gapi_octet, DDS::octSeq, DDS::Octet>( from.value, to.value ); } void DDS::ccpp_DurabilityQosPolicy_copyOut( const gapi_durabilityQosPolicy &from, DDS::DurabilityQosPolicy &to) { switch(from.kind) { case GAPI_VOLATILE_DURABILITY_QOS: to.kind = DDS::VOLATILE_DURABILITY_QOS; break; case GAPI_TRANSIENT_LOCAL_DURABILITY_QOS: to.kind = DDS::TRANSIENT_LOCAL_DURABILITY_QOS; break; case GAPI_TRANSIENT_DURABILITY_QOS: to.kind = DDS::TRANSIENT_DURABILITY_QOS; break; case GAPI_PERSISTENT_DURABILITY_QOS: to.kind = DDS::PERSISTENT_DURABILITY_QOS; break; default: // impossible to reach break; } } void DDS::ccpp_DurabilityServiceQosPolicy_copyOut( const gapi_durabilityServiceQosPolicy &from, DDS::DurabilityServiceQosPolicy &to) { DDS::ccpp_Duration_copyOut(from.service_cleanup_delay, to.service_cleanup_delay); switch(from.history_kind) { case GAPI_KEEP_LAST_HISTORY_QOS: to.history_kind = DDS::KEEP_LAST_HISTORY_QOS; break; case GAPI_KEEP_ALL_HISTORY_QOS: to.history_kind = DDS::KEEP_ALL_HISTORY_QOS; break; default: // impossible to reach break; } to.history_depth = from.history_depth; to.max_samples = from.max_samples; to.max_instances = from.max_instances; to.max_samples_per_instance = from.max_samples_per_instance; } void DDS::ccpp_SampleRejectedStatusKind_copyOut( const gapi_sampleRejectedStatusKind & from, DDS::SampleRejectedStatusKind & to) { switch (from) { case GAPI_NOT_REJECTED: to = DDS::NOT_REJECTED; break; case GAPI_REJECTED_BY_INSTANCES_LIMIT: to = DDS::REJECTED_BY_INSTANCES_LIMIT; break; case GAPI_REJECTED_BY_SAMPLES_LIMIT: to = DDS::REJECTED_BY_SAMPLES_LIMIT; break; case GAPI_REJECTED_BY_SAMPLES_PER_INSTANCE_LIMIT: to = DDS::REJECTED_BY_SAMPLES_PER_INSTANCE_LIMIT; break; default: // impossible to reach break; } } void DDS::ccpp_DeadlineQosPolicy_copyOut( const gapi_deadlineQosPolicy &from, DDS::DeadlineQosPolicy &to) { DDS::ccpp_Duration_copyOut( from.period, to.period); } void DDS::ccpp_LatencyBudgetQosPolicy_copyOut( const gapi_latencyBudgetQosPolicy &from, DDS::LatencyBudgetQosPolicy &to) { DDS::ccpp_Duration_copyOut( from.duration, to.duration); } void DDS::ccpp_LivelinessQosPolicy_copyOut( const gapi_livelinessQosPolicy &from, DDS::LivelinessQosPolicy &to) { switch (from.kind) { case GAPI_AUTOMATIC_LIVELINESS_QOS: to.kind = DDS::AUTOMATIC_LIVELINESS_QOS; break; case GAPI_MANUAL_BY_PARTICIPANT_LIVELINESS_QOS: to.kind = DDS::MANUAL_BY_PARTICIPANT_LIVELINESS_QOS; break; case GAPI_MANUAL_BY_TOPIC_LIVELINESS_QOS: to.kind = DDS::MANUAL_BY_TOPIC_LIVELINESS_QOS; break; default: //impossible to reach break; } DDS::ccpp_Duration_copyOut(from.lease_duration, to.lease_duration); } void DDS::ccpp_ReliabilityQosPolicy_copyOut( const gapi_reliabilityQosPolicy &from, DDS::ReliabilityQosPolicy &to) { switch (from.kind) { case GAPI_BEST_EFFORT_RELIABILITY_QOS: to.kind = DDS::BEST_EFFORT_RELIABILITY_QOS; break; case GAPI_RELIABLE_RELIABILITY_QOS: to.kind = DDS::RELIABLE_RELIABILITY_QOS; break; default: //impossible to reach break; } DDS::ccpp_Duration_copyOut(from.max_blocking_time, to.max_blocking_time); to.synchronous = from.synchronous ? TRUE : FALSE; } void DDS::ccpp_DestinationOrderQosPolicy_copyOut( const gapi_destinationOrderQosPolicy &from, DDS::DestinationOrderQosPolicy &to) { switch (from.kind) { case GAPI_BY_RECEPTION_TIMESTAMP_DESTINATIONORDER_QOS: to.kind = DDS::BY_RECEPTION_TIMESTAMP_DESTINATIONORDER_QOS; break; case GAPI_BY_SOURCE_TIMESTAMP_DESTINATIONORDER_QOS: to.kind = DDS::BY_SOURCE_TIMESTAMP_DESTINATIONORDER_QOS; break; default: //impossible to reach break; } } void DDS::ccpp_HistoryQosPolicy_copyOut( const gapi_historyQosPolicy &from, DDS::HistoryQosPolicy &to) { switch (from.kind) { case GAPI_KEEP_LAST_HISTORY_QOS: to.kind = DDS::KEEP_LAST_HISTORY_QOS; break; case GAPI_KEEP_ALL_HISTORY_QOS: to.kind = DDS::KEEP_ALL_HISTORY_QOS; break; default: //impossible to reach break; } to.depth = from.depth; } void DDS::ccpp_ResourceLimitsQosPolicy_copyOut( const gapi_resourceLimitsQosPolicy &from, DDS::ResourceLimitsQosPolicy &to) { to.max_samples = from.max_samples; to.max_instances = from.max_instances; to.max_samples_per_instance = from.max_samples_per_instance; } void DDS::ccpp_TransportPriorityQosPolicy_copyOut( const gapi_transportPriorityQosPolicy &from, DDS::TransportPriorityQosPolicy &to) { to.value = from.value; } void DDS::ccpp_LifespanQosPolicy_copyOut( const gapi_lifespanQosPolicy &from, DDS::LifespanQosPolicy &to) { DDS::ccpp_Duration_copyOut( from.duration, to.duration); } void DDS::ccpp_OwnershipQosPolicy_copyOut( const gapi_ownershipQosPolicy &from, DDS::OwnershipQosPolicy &to) { switch (from.kind) { case GAPI_SHARED_OWNERSHIP_QOS: to.kind = DDS::SHARED_OWNERSHIP_QOS; break; case GAPI_EXCLUSIVE_OWNERSHIP_QOS: to.kind = DDS::EXCLUSIVE_OWNERSHIP_QOS; break; default: //impossible to reach break; } } void DDS::ccpp_OwnershipStrengthQosPolicy_copyOut(const gapi_ownershipStrengthQosPolicy &from, DDS::OwnershipStrengthQosPolicy &to) { to.value = from.value; } void DDS::ccpp_WriterDataLifecycleQosPolicy_copyOut( const gapi_writerDataLifecycleQosPolicy &from, DDS::WriterDataLifecycleQosPolicy &to) { to.autodispose_unregistered_instances = from.autodispose_unregistered_instances != 0; ccpp_Duration_copyOut(from.autopurge_suspended_samples_delay, to.autopurge_suspended_samples_delay); ccpp_Duration_copyOut(from.autounregister_instance_delay, to.autounregister_instance_delay); } void DDS::ccpp_ReaderDataLifecycleQosPolicy_copyOut( const gapi_readerDataLifecycleQosPolicy &from, DDS::ReaderDataLifecycleQosPolicy &to) { ccpp_Duration_copyOut(from.autopurge_nowriter_samples_delay, to.autopurge_nowriter_samples_delay); ccpp_Duration_copyOut(from.autopurge_disposed_samples_delay, to.autopurge_disposed_samples_delay); to.enable_invalid_samples = from.enable_invalid_samples != 0; ccpp_InvalidSampleVisibilityQosPolicy_copyOut(from.invalid_sample_visibility, to.invalid_sample_visibility); } void DDS::ccpp_ReaderDataLifecycleQosPolicy_copyIn( const DDS::ReaderDataLifecycleQosPolicy &from, gapi_readerDataLifecycleQosPolicy &to) { ccpp_Duration_copyIn(from.autopurge_nowriter_samples_delay, to.autopurge_nowriter_samples_delay); ccpp_Duration_copyIn(from.autopurge_disposed_samples_delay, to.autopurge_disposed_samples_delay); to.enable_invalid_samples = from.enable_invalid_samples; ccpp_InvalidSampleVisibilityQosPolicy_copyIn(from.invalid_sample_visibility, to.invalid_sample_visibility); } void DDS::ccpp_PresentationQosPolicy_copyOut( const gapi_presentationQosPolicy & from, DDS::PresentationQosPolicy & to) { to.access_scope = (DDS::PresentationQosPolicyAccessScopeKind)from.access_scope; to.coherent_access = from.coherent_access != 0; to.ordered_access = from.ordered_access != 0; } void DDS::ccpp_PartitionQosPolicy_copyOut( const gapi_partitionQosPolicy &from, DDS::PartitionQosPolicy &to) { DDS::ccpp_sequenceCopyOut(from.name, to.name); } void DDS::ccpp_GroupDataQosPolicy_copyOut( const gapi_groupDataQosPolicy &from, DDS::GroupDataQosPolicy &to) { DDS::ccpp_sequenceCopyOut< gapi_octetSeq, gapi_octet, DDS::octSeq, DDS::Octet >( from.value, to.value ); } void DDS::ccpp_SubscriptionKeyQosPolicy_copyIn ( const DDS::SubscriptionKeyQosPolicy &from, gapi_subscriptionKeyQosPolicy &to ) { to.use_key_list = (from.use_key_list != FALSE); DDS::ccpp_sequenceCopyIn(from.key_list, to.key_list); } void DDS::ccpp_SubscriptionKeyQosPolicy_copyOut( const gapi_subscriptionKeyQosPolicy &from, DDS::SubscriptionKeyQosPolicy &to ) { DDS::ccpp_sequenceCopyOut(from.key_list, to.key_list); to.use_key_list = from.use_key_list != 0; } void DDS::ccpp_ReaderLifespanQosPolicy_copyIn ( const DDS::ReaderLifespanQosPolicy &from, gapi_readerLifespanQosPolicy &to ) { to.use_lifespan = (from.use_lifespan != FALSE); DDS::ccpp_Duration_copyIn( from.duration, to.duration); } void DDS::ccpp_ReaderLifespanQosPolicy_copyOut ( const gapi_readerLifespanQosPolicy &from, DDS::ReaderLifespanQosPolicy &to ) { to.use_lifespan = from.use_lifespan != 0; DDS::ccpp_Duration_copyOut(from.duration, to.duration); } void DDS::ccpp_ShareQosPolicy_copyIn ( const DDS::ShareQosPolicy &from, gapi_shareQosPolicy &to ) { const char *value = from.name; to.enable = from.enable; to.name = gapi_string_dup(value); } void DDS::ccpp_ShareQosPolicy_copyOut ( const gapi_shareQosPolicy &from, DDS::ShareQosPolicy &to ) { to.enable = from.enable != 0; to.name = DDS::string_dup(reinterpret_cast<const char *>(from.name)); } void DDS::ccpp_SchedulingClassQosPolicy_copyIn ( const DDS::SchedulingClassQosPolicy &from, gapi_schedulingClassQosPolicy &to ) { switch(from.kind) { case DDS::SCHEDULE_TIMESHARING: to.kind = GAPI_SCHEDULE_TIMESHARING; break; case DDS::SCHEDULE_REALTIME: to.kind = GAPI_SCHEDULE_REALTIME; break; case DDS::SCHEDULE_DEFAULT: to.kind = GAPI_SCHEDULE_DEFAULT; break; default: // impossible to reach break; } } void DDS::ccpp_SchedulingClassQosPolicy_copyOut ( const gapi_schedulingClassQosPolicy &from, DDS::SchedulingClassQosPolicy &to ) { switch(from.kind) { case GAPI_SCHEDULE_TIMESHARING: to.kind = DDS::SCHEDULE_TIMESHARING; break; case GAPI_SCHEDULE_REALTIME: to.kind = DDS::SCHEDULE_REALTIME; break; case GAPI_SCHEDULE_DEFAULT: to.kind = DDS::SCHEDULE_DEFAULT; break; default: // impossible to reach break; } } void DDS::ccpp_SchedulingPriorityQosPolicy_copyIn ( const DDS::SchedulingPriorityQosPolicy &from, gapi_schedulingPriorityQosPolicy &to ) { switch(from.kind) { case DDS::PRIORITY_ABSOLUTE: to.kind = GAPI_PRIORITY_ABSOLUTE; break; case DDS::PRIORITY_RELATIVE: to.kind = GAPI_PRIORITY_RELATIVE; break; default: // impossible to reach break; } } void DDS::ccpp_SchedulingPriorityQosPolicy_copyOut ( const gapi_schedulingPriorityQosPolicy &from, DDS::SchedulingPriorityQosPolicy &to ) { switch(from.kind) { case GAPI_PRIORITY_ABSOLUTE: to.kind = DDS::PRIORITY_ABSOLUTE; break; case GAPI_PRIORITY_RELATIVE: to.kind = DDS::PRIORITY_RELATIVE; break; default: // impossible to reach break; } } void DDS::ccpp_SchedulingQosPolicy_copyIn ( const DDS::SchedulingQosPolicy &from, gapi_schedulingQosPolicy &to ) { DDS::ccpp_SchedulingClassQosPolicy_copyIn ( from.scheduling_class, to.scheduling_class ); DDS::ccpp_SchedulingPriorityQosPolicy_copyIn ( from.scheduling_priority_kind, to.scheduling_priority_kind ); to.scheduling_priority = from.scheduling_priority; } void DDS::ccpp_SchedulingQosPolicy_copyOut ( const gapi_schedulingQosPolicy &from, DDS::SchedulingQosPolicy &to ) { DDS::ccpp_SchedulingClassQosPolicy_copyOut ( from.scheduling_class, to.scheduling_class ); DDS::ccpp_SchedulingPriorityQosPolicy_copyOut ( from.scheduling_priority_kind, to.scheduling_priority_kind ); to.scheduling_priority = from.scheduling_priority; } //Qos conversions void DDS::ccpp_DomainParticipantFactoryQos_copyIn( const DDS::DomainParticipantFactoryQos &from, gapi_domainParticipantFactoryQos &to ) { DDS::ccpp_EntityFactoryQosPolicy_copyIn ( from.entity_factory, to.entity_factory ); } void DDS::ccpp_DomainParticipantFactoryQos_copyOut( const gapi_domainParticipantFactoryQos &from, DDS::DomainParticipantFactoryQos &to ) { DDS::ccpp_EntityFactoryQosPolicy_copyOut ( from.entity_factory, to.entity_factory ); } void DDS::ccpp_DomainParticipantQos_copyIn( const DDS::DomainParticipantQos &from, gapi_domainParticipantQos &to ) { DDS::ccpp_UserDataQosPolicy_copyIn( from.user_data, to.user_data ); DDS::ccpp_EntityFactoryQosPolicy_copyIn ( from.entity_factory, to.entity_factory ); DDS::ccpp_SchedulingQosPolicy_copyIn ( from.watchdog_scheduling, to.watchdog_scheduling ); DDS::ccpp_SchedulingQosPolicy_copyIn ( from.listener_scheduling, to.listener_scheduling ); } void DDS::ccpp_DomainParticipantQos_copyOut( const gapi_domainParticipantQos &from, DDS::DomainParticipantQos &to ) { DDS::ccpp_UserDataQosPolicy_copyOut( from.user_data, to.user_data ); DDS::ccpp_EntityFactoryQosPolicy_copyOut ( from.entity_factory, to.entity_factory ); DDS::ccpp_SchedulingQosPolicy_copyOut ( from.watchdog_scheduling, to.watchdog_scheduling ); DDS::ccpp_SchedulingQosPolicy_copyOut ( from.listener_scheduling, to.listener_scheduling ); } void DDS::ccpp_TopicQos_copyIn( const DDS::TopicQos &from, gapi_topicQos &to) { DDS::ccpp_TopicDataQosPolicy_copyIn( from.topic_data, to.topic_data); DDS::ccpp_DurabilityQosPolicy_copyIn( from.durability, to.durability); DDS::ccpp_DurabilityServiceQosPolicy_copyIn( from.durability_service, to.durability_service); DDS::ccpp_DeadlineQosPolicy_copyIn( from.deadline, to.deadline); DDS::ccpp_LatencyBudgetQosPolicy_copyIn( from.latency_budget, to.latency_budget); DDS::ccpp_LivelinessQosPolicy_copyIn( from.liveliness, to.liveliness); DDS::ccpp_ReliabilityQosPolicy_copyIn( from.reliability, to.reliability); DDS::ccpp_DestinationOrderQosPolicy_copyIn( from.destination_order, to.destination_order); DDS::ccpp_HistoryQosPolicy_copyIn( from.history, to.history); DDS::ccpp_ResourceLimitsQosPolicy_copyIn( from.resource_limits, to.resource_limits); DDS::ccpp_TransportPriorityQosPolicy_copyIn( from.transport_priority, to.transport_priority); DDS::ccpp_LifespanQosPolicy_copyIn( from.lifespan, to.lifespan); DDS::ccpp_OwnershipQosPolicy_copyIn( from.ownership, to.ownership); } void DDS::ccpp_TopicQos_copyOut( const gapi_topicQos &from, DDS::TopicQos &to) { DDS::ccpp_TopicDataQosPolicy_copyOut( from.topic_data, to.topic_data); DDS::ccpp_DurabilityQosPolicy_copyOut( from.durability, to.durability); DDS::ccpp_DurabilityServiceQosPolicy_copyOut( from.durability_service, to.durability_service); DDS::ccpp_DeadlineQosPolicy_copyOut( from.deadline, to.deadline); DDS::ccpp_LatencyBudgetQosPolicy_copyOut( from.latency_budget, to.latency_budget); DDS::ccpp_LivelinessQosPolicy_copyOut( from.liveliness, to.liveliness); DDS::ccpp_ReliabilityQosPolicy_copyOut( from.reliability, to.reliability); DDS::ccpp_DestinationOrderQosPolicy_copyOut( from.destination_order, to.destination_order); DDS::ccpp_HistoryQosPolicy_copyOut( from.history, to.history); DDS::ccpp_ResourceLimitsQosPolicy_copyOut( from.resource_limits, to.resource_limits); DDS::ccpp_TransportPriorityQosPolicy_copyOut( from.transport_priority, to.transport_priority); DDS::ccpp_LifespanQosPolicy_copyOut( from.lifespan, to.lifespan); DDS::ccpp_OwnershipQosPolicy_copyOut( from.ownership, to.ownership); } void DDS::ccpp_DataWriterQos_copyIn( const DDS::DataWriterQos &from, gapi_dataWriterQos &to) { DDS::ccpp_DurabilityQosPolicy_copyIn( from.durability, to.durability); DDS::ccpp_DeadlineQosPolicy_copyIn( from.deadline, to.deadline); DDS::ccpp_LatencyBudgetQosPolicy_copyIn( from.latency_budget, to.latency_budget); DDS::ccpp_LivelinessQosPolicy_copyIn( from.liveliness, to.liveliness); DDS::ccpp_ReliabilityQosPolicy_copyIn( from.reliability, to.reliability); DDS::ccpp_DestinationOrderQosPolicy_copyIn( from.destination_order, to.destination_order); DDS::ccpp_HistoryQosPolicy_copyIn( from.history, to.history); DDS::ccpp_ResourceLimitsQosPolicy_copyIn( from.resource_limits, to.resource_limits); DDS::ccpp_TransportPriorityQosPolicy_copyIn( from.transport_priority, to.transport_priority); DDS::ccpp_LifespanQosPolicy_copyIn( from.lifespan, to.lifespan); DDS::ccpp_UserDataQosPolicy_copyIn( from.user_data, to.user_data ); DDS::ccpp_OwnershipQosPolicy_copyIn(from.ownership, to.ownership); DDS::ccpp_OwnershipStrengthQosPolicy_copyIn(from.ownership_strength, to.ownership_strength); DDS::ccpp_WriterDataLifecycleQosPolicy_copyIn(from.writer_data_lifecycle, to.writer_data_lifecycle); } void DDS::ccpp_DataWriterQos_copyOut( const gapi_dataWriterQos &from, DDS::DataWriterQos &to) { DDS::ccpp_DurabilityQosPolicy_copyOut( from.durability, to.durability); DDS::ccpp_DeadlineQosPolicy_copyOut( from.deadline, to.deadline); DDS::ccpp_LatencyBudgetQosPolicy_copyOut( from.latency_budget, to.latency_budget); DDS::ccpp_LivelinessQosPolicy_copyOut( from.liveliness, to.liveliness); DDS::ccpp_ReliabilityQosPolicy_copyOut( from.reliability, to.reliability); DDS::ccpp_DestinationOrderQosPolicy_copyOut( from.destination_order, to.destination_order); DDS::ccpp_HistoryQosPolicy_copyOut( from.history, to.history); DDS::ccpp_ResourceLimitsQosPolicy_copyOut( from.resource_limits, to.resource_limits); DDS::ccpp_TransportPriorityQosPolicy_copyOut( from.transport_priority, to.transport_priority); DDS::ccpp_LifespanQosPolicy_copyOut( from.lifespan, to.lifespan); DDS::ccpp_UserDataQosPolicy_copyOut( from.user_data, to.user_data ); DDS::ccpp_OwnershipQosPolicy_copyOut(from.ownership, to.ownership); DDS::ccpp_OwnershipStrengthQosPolicy_copyOut(from.ownership_strength, to.ownership_strength); DDS::ccpp_WriterDataLifecycleQosPolicy_copyOut(from.writer_data_lifecycle, to.writer_data_lifecycle); } void DDS::ccpp_DataReaderQos_copyOut( const gapi_dataReaderQos &from, DDS::DataReaderQos &to) { DDS::ccpp_DurabilityQosPolicy_copyOut( from.durability, to.durability); DDS::ccpp_DeadlineQosPolicy_copyOut( from.deadline, to.deadline); DDS::ccpp_LatencyBudgetQosPolicy_copyOut( from.latency_budget, to.latency_budget); DDS::ccpp_LivelinessQosPolicy_copyOut( from.liveliness, to.liveliness); DDS::ccpp_ReliabilityQosPolicy_copyOut( from.reliability, to.reliability); DDS::ccpp_DestinationOrderQosPolicy_copyOut( from.destination_order, to.destination_order); DDS::ccpp_HistoryQosPolicy_copyOut( from.history, to.history); DDS::ccpp_ResourceLimitsQosPolicy_copyOut( from.resource_limits, to.resource_limits); DDS::ccpp_UserDataQosPolicy_copyOut( from.user_data, to.user_data ); DDS::ccpp_OwnershipQosPolicy_copyOut(from.ownership, to.ownership); DDS::ccpp_TimeBasedFilterQosPolicy_copyOut(from.time_based_filter, to.time_based_filter); DDS::ccpp_ReaderDataLifecycleQosPolicy_copyOut(from.reader_data_lifecycle, to.reader_data_lifecycle); DDS::ccpp_SubscriptionKeyQosPolicy_copyOut(from.subscription_keys, to.subscription_keys); DDS::ccpp_ReaderLifespanQosPolicy_copyOut(from.reader_lifespan, to.reader_lifespan); DDS::ccpp_ShareQosPolicy_copyOut(from.share, to.share); } void DDS::ccpp_DataReaderQos_copyIn( const DDS::DataReaderQos &from, gapi_dataReaderQos &to) { DDS::ccpp_DurabilityQosPolicy_copyIn( from.durability, to.durability); DDS::ccpp_DeadlineQosPolicy_copyIn( from.deadline, to.deadline); DDS::ccpp_LatencyBudgetQosPolicy_copyIn( from.latency_budget, to.latency_budget); DDS::ccpp_LivelinessQosPolicy_copyIn( from.liveliness, to.liveliness); DDS::ccpp_ReliabilityQosPolicy_copyIn( from.reliability, to.reliability); DDS::ccpp_DestinationOrderQosPolicy_copyIn( from.destination_order, to.destination_order); DDS::ccpp_HistoryQosPolicy_copyIn( from.history, to.history); DDS::ccpp_ResourceLimitsQosPolicy_copyIn( from.resource_limits, to.resource_limits); DDS::ccpp_UserDataQosPolicy_copyIn( from.user_data, to.user_data ); DDS::ccpp_OwnershipQosPolicy_copyIn(from.ownership, to.ownership); DDS::ccpp_TimeBasedFilterQosPolicy_copyIn(from.time_based_filter, to.time_based_filter); DDS::ccpp_ReaderDataLifecycleQosPolicy_copyIn(from.reader_data_lifecycle, to.reader_data_lifecycle); DDS::ccpp_SubscriptionKeyQosPolicy_copyIn(from.subscription_keys, to.subscription_keys); DDS::ccpp_ReaderLifespanQosPolicy_copyIn(from.reader_lifespan, to.reader_lifespan); DDS::ccpp_ShareQosPolicy_copyIn(from.share, to.share); } void DDS::ccpp_PublisherQos_copyOut( const gapi_publisherQos &from, DDS::PublisherQos &to) { DDS::ccpp_PresentationQosPolicy_copyOut( from.presentation, to.presentation); DDS::ccpp_PartitionQosPolicy_copyOut( from.partition, to.partition); DDS::ccpp_GroupDataQosPolicy_copyOut( from.group_data, to.group_data); DDS::ccpp_EntityFactoryQosPolicy_copyOut( from.entity_factory, to.entity_factory); } void DDS::ccpp_PublisherQos_copyIn( const DDS::PublisherQos &from, gapi_publisherQos &to) { DDS::ccpp_PresentationQosPolicy_copyIn( from.presentation, to.presentation); DDS::ccpp_PartitionQosPolicy_copyIn( from.partition, to.partition); DDS::ccpp_GroupDataQosPolicy_copyIn( from.group_data, to.group_data); DDS::ccpp_EntityFactoryQosPolicy_copyIn( from.entity_factory, to.entity_factory); } void DDS::ccpp_SubscriberQos_copyIn( const DDS::SubscriberQos &from, gapi_subscriberQos &to) { DDS::ccpp_PresentationQosPolicy_copyIn( from.presentation, to.presentation); DDS::ccpp_PartitionQosPolicy_copyIn( from.partition, to.partition); DDS::ccpp_GroupDataQosPolicy_copyIn( from.group_data, to.group_data); DDS::ccpp_EntityFactoryQosPolicy_copyIn( from.entity_factory, to.entity_factory); DDS::ccpp_ShareQosPolicy_copyIn(from.share, to.share); } void DDS::ccpp_SubscriberQos_copyOut( const gapi_subscriberQos &from, DDS::SubscriberQos &to) { DDS::ccpp_PresentationQosPolicy_copyOut( from.presentation, to.presentation); DDS::ccpp_PartitionQosPolicy_copyOut( from.partition, to.partition); DDS::ccpp_GroupDataQosPolicy_copyOut( from.group_data, to.group_data); DDS::ccpp_EntityFactoryQosPolicy_copyOut( from.entity_factory, to.entity_factory); DDS::ccpp_ShareQosPolicy_copyOut(from.share, to.share); } void DDS::ccpp_OfferedIncompatibleQosStatus_copyOut( const gapi_offeredIncompatibleQosStatus & from, DDS::OfferedIncompatibleQosStatus &to) { to.total_count = from.total_count; to.total_count_change = from.total_count_change; to.last_policy_id = from.last_policy_id; DDS::ccpp_sequenceCopyOut<gapi_qosPolicyCountSeq, gapi_qosPolicyCount, DDS::QosPolicyCountSeq, DDS::QosPolicyCount>(from.policies, to.policies); } void DDS::ccpp_RequestedIncompatibleQosStatus_copyOut( const gapi_requestedIncompatibleQosStatus & from, DDS::RequestedIncompatibleQosStatus &to) { to.total_count = from.total_count; to.total_count_change = from.total_count_change; to.last_policy_id = from.last_policy_id; DDS::ccpp_sequenceCopyOut<gapi_qosPolicyCountSeq, gapi_qosPolicyCount, DDS::QosPolicyCountSeq, DDS::QosPolicyCount>(from.policies, to.policies); } void DDS::ccpp_TimeBasedFilterQosPolicy_copyOut( const gapi_timeBasedFilterQosPolicy & from, DDS::TimeBasedFilterQosPolicy & to) { DDS::ccpp_Duration_copyOut(from.minimum_separation, to.minimum_separation); } void DDS::ccpp_TimeBasedFilterQosPolicy_copyIn( const DDS::TimeBasedFilterQosPolicy & from, gapi_timeBasedFilterQosPolicy & to) { DDS::ccpp_Duration_copyIn(from.minimum_separation, to.minimum_separation); } void DDS::ccpp_RequestedDeadlineMissedStatus_copyOut( const gapi_requestedDeadlineMissedStatus & from, DDS::RequestedDeadlineMissedStatus &to) { to.total_count = from.total_count; to.total_count_change = from.total_count_change; to.last_instance_handle = from.last_instance_handle; } void DDS::ccpp_SampleRejectedStatus_copyOut( const gapi_sampleRejectedStatus & from, DDS::SampleRejectedStatus &to) { to.total_count = from.total_count; to.total_count_change = from.total_count_change; ccpp_SampleRejectedStatusKind_copyOut(from.last_reason, to.last_reason); to.last_instance_handle = from.last_instance_handle; } void DDS::ccpp_LivelinessChangedStatus_copyOut( const gapi_livelinessChangedStatus & from, DDS::LivelinessChangedStatus &to) { to.alive_count = from.alive_count; to.alive_count_change = from.alive_count_change; to.not_alive_count = from.not_alive_count; to.not_alive_count_change = from.not_alive_count_change; to.last_publication_handle = from.last_publication_handle; } void DDS::ccpp_SubscriptionMatchedStatus_copyOut( const gapi_subscriptionMatchedStatus & from, DDS::SubscriptionMatchedStatus &to) { to.total_count = from.total_count; to.total_count_change = from.total_count_change; to.current_count = from.current_count; to.current_count_change = from.current_count_change; to.last_publication_handle = (DDS::InstanceHandle_t)from.last_publication_handle; } void DDS::ccpp_SampleLostStatus_copyOut( const gapi_sampleLostStatus & from, DDS::SampleLostStatus &to) { to.total_count = from.total_count; to.total_count_change = from.total_count_change; } void DDS::ccpp_InconsistentTopicStatus_copyOut( const gapi_inconsistentTopicStatus & from, DDS::InconsistentTopicStatus &to) { to.total_count = from.total_count; to.total_count_change = from.total_count_change; } void DDS::ccpp_AllDataDisposedTopicStatus_copyOut( const gapi_allDataDisposedTopicStatus & from, DDS::AllDataDisposedTopicStatus &to) { to.total_count = from.total_count; to.total_count_change = from.total_count_change; } void DDS::ccpp_OfferedDeadlineMissedStatus_copyOut( const gapi_offeredDeadlineMissedStatus & from, DDS::OfferedDeadlineMissedStatus &to) { to.total_count = from.total_count; to.total_count_change = from.total_count_change; to.last_instance_handle = from.last_instance_handle; } void DDS::ccpp_LivelinessLostStatus_copyOut( const gapi_livelinessLostStatus & from, DDS::LivelinessLostStatus &to) { to.total_count = from.total_count; to.total_count_change = from.total_count_change; } void DDS::ccpp_PublicationMatchedStatus_copyOut( const gapi_publicationMatchedStatus & from, DDS::PublicationMatchedStatus &to) { to.total_count = from.total_count; to.total_count_change = from.total_count_change; to.current_count = from.current_count; to.current_count_change = from.current_count_change; to.last_subscription_handle = (DDS::InstanceHandle_t)from.last_subscription_handle; } void DDS::ccpp_DataReaderViewQos_copyIn( const DDS::DataReaderViewQos &from, gapi_dataReaderViewQos &to) { DDS::ccpp_ViewKeyQosPolicy_copyIn( from.view_keys, to.view_keys); } void DDS::ccpp_DataReaderViewQos_copyOut( const gapi_dataReaderViewQos &from, DDS::DataReaderViewQos &to) { DDS::ccpp_ViewKeyQosPolicy_copyOut( from.view_keys, to.view_keys); } void DDS::ccpp_ViewKeyQosPolicy_copyIn( const DDS::ViewKeyQosPolicy &from, gapi_viewKeyQosPolicy &to) { to.use_key_list = from.use_key_list; DDS::ccpp_sequenceCopyIn(from.key_list, to.key_list); } void DDS::ccpp_ViewKeyQosPolicy_copyOut( const gapi_viewKeyQosPolicy &from, DDS::ViewKeyQosPolicy &to) { to.use_key_list = from.use_key_list != 0; DDS::ccpp_sequenceCopyOut(from.key_list, to.key_list); } void DDS::ccpp_InvalidSampleVisibilityQosPolicy_copyIn( const DDS::InvalidSampleVisibilityQosPolicy &from, gapi_invalidSampleVisibilityQosPolicy &to) { switch(from.kind) { case DDS::NO_INVALID_SAMPLES: to.kind = GAPI_NO_INVALID_SAMPLES; break; case DDS::MINIMUM_INVALID_SAMPLES: to.kind = GAPI_MINIMUM_INVALID_SAMPLES; break; case DDS::ALL_INVALID_SAMPLES: to.kind = GAPI_ALL_INVALID_SAMPLES; break; default: // impossible to reach break; } } void DDS::ccpp_InvalidSampleVisibilityQosPolicy_copyOut( const gapi_invalidSampleVisibilityQosPolicy &from, DDS::InvalidSampleVisibilityQosPolicy &to) { switch(from.kind) { case GAPI_NO_INVALID_SAMPLES: to.kind = DDS::NO_INVALID_SAMPLES; break; case GAPI_MINIMUM_INVALID_SAMPLES: to.kind = DDS::MINIMUM_INVALID_SAMPLES; break; case GAPI_ALL_INVALID_SAMPLES: to.kind = DDS::ALL_INVALID_SAMPLES; break; default: // impossible to reach break; } } bool DDS::operator==( const DDS::Duration_t &a, const DDS::Duration_t &b) { return a.sec == b.sec && a.nanosec == b.nanosec ? true : false; } bool DDS::operator!=( const DDS::Duration_t &a, const DDS::Duration_t &b) { return !operator==(a, b); } bool DDS::operator==( const DDS::octSeq &a, const DDS::octSeq &b) { DDS::ULong i, j, n; n = a.length (); j = b.length (); if (n == j) { for (i = 0; i < n && a[i] == b[i]; i++) { /* do nothing */ } if (i == n) { return true; } } return false; } bool DDS::operator!=( const DDS::octSeq &a, const DDS::octSeq &b) { return !operator==(a, b); } bool DDS::operator==( const DDS::StringSeq &a, const DDS::StringSeq &b) { DDS::ULong i, j, n; n = a.length (); j = b.length (); if (j == n) { for (i = 0; i < n && strcmp (a[i], b[i]) == 0; i++) { /* do nothing */ } if (i == n) { return true; } } return false; } bool DDS::operator!=( const DDS::StringSeq &a, const DDS::StringSeq &b) { return !operator==(a, b); } bool DDS::operator==( const DDS::DeadlineQosPolicy &a, const DDS::DeadlineQosPolicy &b) { return a.period == b.period ? true : false; } bool DDS::operator!=( const DDS::DeadlineQosPolicy &a, const DDS::DeadlineQosPolicy &b) { return !operator==(a, b); } bool DDS::operator==( const DDS::DestinationOrderQosPolicy &a, const DDS::DestinationOrderQosPolicy &b) { return a.kind == b.kind ? true : false; } bool DDS::operator!=( const DDS::DestinationOrderQosPolicy &a, const DDS::DestinationOrderQosPolicy &b) { return !operator==(a, b); } bool DDS::operator==( const DDS::DurabilityQosPolicy &a, const DDS::DurabilityQosPolicy &b) { return a.kind == b.kind ? true : false; } bool DDS::operator!=( const DDS::DurabilityQosPolicy &a, const DDS::DurabilityQosPolicy &b) { return !operator==(a, b); } bool DDS::operator==( const DDS::DurabilityServiceQosPolicy &a, const DDS::DurabilityServiceQosPolicy &b) { if (a.history_depth == b.history_depth && a.history_kind == b.history_kind && a.max_instances == b.max_instances && a.max_samples == b.max_samples && a.max_samples_per_instance == b.max_samples_per_instance && a.service_cleanup_delay == b.service_cleanup_delay) { return true; } return false; } bool DDS::operator!=( const DDS::DurabilityServiceQosPolicy &a, const DDS::DurabilityServiceQosPolicy &b) { return !operator==(a, b); } bool DDS::operator==( const DDS::EntityFactoryQosPolicy &a, const DDS::EntityFactoryQosPolicy &b) { if (a.autoenable_created_entities == b.autoenable_created_entities) { return true; } return false; } bool DDS::operator!=( const DDS::EntityFactoryQosPolicy &a, const DDS::EntityFactoryQosPolicy &b) { return !operator==(a, b); } bool DDS::operator==( const DDS::GroupDataQosPolicy &a, const DDS::GroupDataQosPolicy &b) { return a.value == b.value ? true : false; } bool DDS::operator!=( const DDS::GroupDataQosPolicy &a, const DDS::GroupDataQosPolicy &b) { return !operator==(a, b); } bool DDS::operator==( const DDS::HistoryQosPolicy &a, const DDS::HistoryQosPolicy &b) { return a.depth == b.depth && a.kind == b.kind ? true : false; } bool DDS::operator!=( const DDS::HistoryQosPolicy &a, const DDS::HistoryQosPolicy &b) { return !operator==(a, b); } bool DDS::operator==( const DDS::LatencyBudgetQosPolicy &a, const DDS::LatencyBudgetQosPolicy &b) { return a.duration == b.duration ? true : false; } bool DDS::operator!=( const DDS::LatencyBudgetQosPolicy &a, const DDS::LatencyBudgetQosPolicy &b) { return !operator==(a, b); } bool DDS::operator==( const DDS::LifespanQosPolicy &a, const DDS::LifespanQosPolicy &b) { return a.duration == b.duration ? true : false; } bool DDS::operator!=( const DDS::LifespanQosPolicy &a, const DDS::LifespanQosPolicy &b) { return !operator==(a, b); } bool DDS::operator==( const DDS::LivelinessQosPolicy &a, const DDS::LivelinessQosPolicy &b) { return a.kind == b.kind && a.lease_duration == b.lease_duration ? true : false; } bool DDS::operator!=( const DDS::LivelinessQosPolicy &a, const DDS::LivelinessQosPolicy &b) { return !operator==(a, b); } bool DDS::operator==( const DDS::OwnershipQosPolicy &a, const DDS::OwnershipQosPolicy &b) { return a.kind == b.kind ? true : false; } bool DDS::operator!=( const DDS::OwnershipQosPolicy &a, const DDS::OwnershipQosPolicy &b) { return !operator==(a, b); } bool DDS::operator==( const DDS::OwnershipStrengthQosPolicy &a, const DDS::OwnershipStrengthQosPolicy &b) { return a.value == b.value ? true : false; } bool DDS::operator!=( const DDS::OwnershipStrengthQosPolicy &a, const DDS::OwnershipStrengthQosPolicy &b) { return !operator==(a, b); } bool DDS::operator==( const DDS::PartitionQosPolicy &a, const DDS::PartitionQosPolicy &b) { return a.name == b.name ? true : false; } bool DDS::operator!=( const DDS::PartitionQosPolicy &a, const DDS::PartitionQosPolicy &b) { return !operator==(a, b); } bool DDS::operator==( const DDS::PresentationQosPolicy &a, const DDS::PresentationQosPolicy &b) { if (a.access_scope == b.access_scope && a.coherent_access == b.coherent_access && a.ordered_access == b.ordered_access) { return true; } return false; } bool DDS::operator!=( const DDS::PresentationQosPolicy &a, const DDS::PresentationQosPolicy &b) { return !operator==(a, b); } bool DDS::operator==( const DDS::ReaderDataLifecycleQosPolicy &a, const DDS::ReaderDataLifecycleQosPolicy &b) { if (a.enable_invalid_samples == b.enable_invalid_samples) { if (a.enable_invalid_samples) { if (a.autopurge_disposed_samples_delay == b.autopurge_disposed_samples_delay && a.autopurge_nowriter_samples_delay == b.autopurge_nowriter_samples_delay && a.invalid_sample_visibility.kind == b.invalid_sample_visibility.kind) { return true; } } else { return true; } } return false; } bool DDS::operator!=( const DDS::ReaderDataLifecycleQosPolicy &a, const DDS::ReaderDataLifecycleQosPolicy &b) { return !operator==(a, b); } bool DDS::operator==( const DDS::ReaderLifespanQosPolicy &a, const DDS::ReaderLifespanQosPolicy &b) { if (a.use_lifespan == b.use_lifespan) { if (a.use_lifespan) { if (a.duration == b.duration) { return true; } } else { return true; } } return false; } bool DDS::operator!=( const DDS::ReaderLifespanQosPolicy &a, const DDS::ReaderLifespanQosPolicy &b) { return !operator==(a, b); } bool DDS::operator==( const DDS::ReliabilityQosPolicy &a, const DDS::ReliabilityQosPolicy &b) { if (a.kind == b.kind && a.max_blocking_time == b.max_blocking_time && a.synchronous == b.synchronous) { return true; } return false; } bool DDS::operator!=( const DDS::ReliabilityQosPolicy &a, const DDS::ReliabilityQosPolicy &b) { return !operator==(a, b); } bool DDS::operator==( const DDS::ResourceLimitsQosPolicy &a, const DDS::ResourceLimitsQosPolicy &b) { if (a.max_instances == b.max_instances && a.max_samples == b.max_samples && a.max_samples_per_instance == b.max_samples_per_instance) { return true; } return false; } bool DDS::operator!=( const DDS::ResourceLimitsQosPolicy &a, const DDS::ResourceLimitsQosPolicy &b) { return !operator==(a, b); } bool DDS::operator==( const DDS::SchedulingQosPolicy &a, const DDS::SchedulingQosPolicy &b) { if (a.scheduling_class.kind == b.scheduling_class.kind && a.scheduling_priority == b.scheduling_priority && a.scheduling_priority_kind.kind == b.scheduling_priority_kind.kind) { return true; } return false; } bool DDS::operator!=( const DDS::SchedulingQosPolicy &a, const DDS::SchedulingQosPolicy &b) { return !operator==(a, b); } bool DDS::operator==( const DDS::ShareQosPolicy &a, const DDS::ShareQosPolicy &b) { if (a.enable == b.enable) { if (a.enable) { if (a.name == NULL && b.name == NULL) { return true; } else if (a.name != NULL && b.name != NULL) { if (strcmp (a.name, b.name) == 0) { return true; } } } else { return true; } } return false; } bool DDS::operator!=( const DDS::ShareQosPolicy &a, const DDS::ShareQosPolicy &b) { return !operator==(a, b); } bool DDS::operator==( const DDS::SubscriptionKeyQosPolicy &a, const DDS::SubscriptionKeyQosPolicy &b) { if (a.use_key_list == b.use_key_list) { if (a.use_key_list) { if (a.key_list == b.key_list) { return true; } } else { return true; } } return false; } bool DDS::operator!=( const DDS::SubscriptionKeyQosPolicy &a, const DDS::SubscriptionKeyQosPolicy &b) { return !operator==(a, b); } bool DDS::operator==( const DDS::TimeBasedFilterQosPolicy &a, const DDS::TimeBasedFilterQosPolicy &b) { return a.minimum_separation == b.minimum_separation ? true : false; } bool DDS::operator!=( const DDS::TimeBasedFilterQosPolicy &a, const DDS::TimeBasedFilterQosPolicy &b) { return !operator==(a, b); } bool DDS::operator==( const DDS::TopicDataQosPolicy &a, const DDS::TopicDataQosPolicy &b) { return a.value == b.value ? true : false; } bool DDS::operator!=( const DDS::TopicDataQosPolicy &a, const DDS::TopicDataQosPolicy &b) { return !operator==(a, b); } bool DDS::operator==( const DDS::TransportPriorityQosPolicy &a, const DDS::TransportPriorityQosPolicy &b) { return a.value == b.value ? true : false; } bool DDS::operator!=( const DDS::TransportPriorityQosPolicy &a, const DDS::TransportPriorityQosPolicy &b) { return !operator==(a, b); } bool DDS::operator==( const DDS::UserDataQosPolicy &a, const DDS::UserDataQosPolicy &b) { return a.value == b.value ? true : false; } bool DDS::operator!=( const DDS::UserDataQosPolicy &a, const DDS::UserDataQosPolicy &b) { return !operator==(a, b); } bool DDS::operator==( const DDS::ViewKeyQosPolicy &a, const DDS::ViewKeyQosPolicy &b) { if (a.use_key_list == b.use_key_list && a.key_list == b.key_list) { return true; } return false; } bool DDS::operator!=( const DDS::ViewKeyQosPolicy &a, const DDS::ViewKeyQosPolicy &b) { return !operator==(a, b); } bool DDS::operator==( const DDS::WriterDataLifecycleQosPolicy &a, const DDS::WriterDataLifecycleQosPolicy &b) { if (a.autodispose_unregistered_instances == b.autodispose_unregistered_instances && a.autopurge_suspended_samples_delay == b.autopurge_suspended_samples_delay && a.autounregister_instance_delay == b.autounregister_instance_delay) { return true; } return false; } bool DDS::operator!=( const DDS::WriterDataLifecycleQosPolicy &a, const DDS::WriterDataLifecycleQosPolicy &b) { return !operator==(a, b); } bool DDS::operator==( const DDS::DataReaderQos &a, const DDS::DataReaderQos &b) { if (a.durability == b.durability && a.deadline == b.deadline && a.latency_budget == b.latency_budget && a.liveliness == b.liveliness && a.reliability == b.reliability && a.destination_order == b.destination_order && a.history == b.history && a.resource_limits == b.resource_limits && a.user_data == b.user_data && a.ownership == b.ownership && a.time_based_filter == b.time_based_filter && a.reader_data_lifecycle == b.reader_data_lifecycle && a.subscription_keys == b.subscription_keys && a.reader_lifespan == b.reader_lifespan && a.share == b.share) { return true; } return false; } bool DDS::operator!=( const DDS::DataReaderQos &a, const DDS::DataReaderQos &b) { return !operator==(a, b); } bool DDS::operator==( const DDS::DataReaderViewQos &a, const DDS::DataReaderViewQos &b) { if (a.view_keys == b.view_keys) { return true; } return false; } bool DDS::operator!=( const DDS::DataReaderViewQos &a, const DDS::DataReaderViewQos &b) { return !operator==(a, b); } bool DDS::operator==( const DDS::DataWriterQos &a, const DDS::DataWriterQos &b) { if (a.durability == b.durability && a.deadline == b.deadline && a.latency_budget == b.latency_budget && a.liveliness == b.liveliness && a.reliability == b.reliability && a.destination_order == b.destination_order && a.history == b.history && a.resource_limits == b.resource_limits && a.transport_priority == b.transport_priority && a.lifespan == b.lifespan && a.user_data == b.user_data && a.ownership == b.ownership && a.ownership_strength == b.ownership_strength && a.writer_data_lifecycle == b.writer_data_lifecycle) { return true; } return false; } bool DDS::operator!=( const DDS::DataWriterQos &a, const DDS::DataWriterQos &b) { return !operator==(a, b); } bool DDS::operator==( const DDS::DomainParticipantQos &a, const DDS::DomainParticipantQos &b) { if (a.user_data == b.user_data && a.entity_factory == b.entity_factory && a.watchdog_scheduling == b.watchdog_scheduling && a.listener_scheduling == b.listener_scheduling) { return true; } return false; } bool DDS::operator!=( const DDS::DomainParticipantQos &a, const DDS::DomainParticipantQos &b) { return !operator==(a, b); } bool DDS::operator==( const DDS::PublisherQos &a, const DDS::PublisherQos &b) { if (a.presentation == b.presentation && a.partition == b.partition && a.group_data == b.group_data && a.entity_factory == b.entity_factory) { return true; } return false; } bool DDS::operator!=( const DDS::PublisherQos &a, const DDS::PublisherQos &b) { return !operator==(a, b); } bool DDS::operator==( const DDS::SubscriberQos &a, const DDS::SubscriberQos &b) { if (a.presentation == b.presentation && a.partition == b.partition && a.group_data == b.group_data && a.entity_factory == b.entity_factory && a.share == b.share) { return true; } return false; } bool DDS::operator!=( const DDS::SubscriberQos &a, const DDS::SubscriberQos &b) { return !operator==(a, b); } bool DDS::operator==( const DDS::TopicQos &a, const DDS::TopicQos &b) { if (a.topic_data == b.topic_data && a.durability == b.durability && a.durability_service == b.durability_service && a.deadline == b.deadline && a.latency_budget == b.latency_budget && a.liveliness == b.liveliness && a.reliability == b.reliability && a.destination_order == b.destination_order && a.history == b.history && a.resource_limits == b.resource_limits && a.transport_priority == b.transport_priority && a.lifespan == b.lifespan && a.ownership == b.ownership) { return true; } return false; } bool DDS::operator!=( const DDS::TopicQos &a, const DDS::TopicQos &b) { return !operator==(a, b); }
gpl-3.0
VirusOnline/VoragineCore
src/server/game/DungeonFinding/LFGScripts.cpp
1
6163
/* * Copyright (C) 2005-2011 MaNGOS <http://www.getmangos.com/> * * Copyright (C) 2008-2011 Trinity <http://www.trinitycore.org/> * * Copyright (C) 2010-2011 VoragineCore <http://www.projectvoragine.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 "gamePCH.h" /* * Interaction between core and LFGScripts */ #include "Common.h" #include "SharedDefines.h" #include "Player.h" #include "Group.h" #include "ScriptPCH.h" #include "LFGScripts.h" #include "LFGMgr.h" LFGScripts::LFGScripts(): GroupScript("LFGScripts"), PlayerScript("LFGScripts") {} void LFGScripts::OnAddMember(Group* group, uint64 guid) { uint64 gguid = group->GetGUID(); if (!gguid) return; sLog->outDebug("LFGScripts::OnAddMember [" UI64FMTD "]: added [" UI64FMTD "]", gguid, guid); LfgUpdateData updateData = LfgUpdateData(LFG_UPDATETYPE_CLEAR_LOCK_LIST); for (GroupReference *itr = group->GetFirstMember(); itr != NULL; itr = itr->next()) { if (Player *plrg = itr->getSource()) { plrg->GetSession()->SendLfgUpdatePlayer(updateData); plrg->GetSession()->SendLfgUpdateParty(updateData); } } // TODO - if group is queued and new player is added convert to rolecheck without notify the current players queued if (sLFGMgr->GetState(gguid) == LFG_STATE_QUEUED) sLFGMgr->Leave(NULL, group); if (sLFGMgr->GetState(guid) == LFG_STATE_QUEUED) if (Player *plr = sObjectMgr->GetPlayer(guid)) sLFGMgr->Leave(plr); } void LFGScripts::OnRemoveMember(Group* group, uint64 guid, RemoveMethod& method, uint64 kicker, const char* reason) { uint64 gguid = group->GetGUID(); if (!gguid || method == GROUP_REMOVEMETHOD_DEFAULT) return; sLog->outDebug("LFGScripts::OnRemoveMember [" UI64FMTD "]: remove [" UI64FMTD "] Method: %d Kicker: [" UI64FMTD "] Reason: %s", gguid, guid, method, kicker, (reason ? reason : "")); if (sLFGMgr->GetState(gguid) == LFG_STATE_QUEUED) { // TODO - Do not remove, just remove the one leaving and rejoin queue with all other data sLFGMgr->Leave(NULL, group); } if (!group->isLFGGroup()) return; if (method == GROUP_REMOVEMETHOD_KICK) // Player have been kicked { // TODO - Update internal kick cooldown of kicker std::string str_reason = ""; if (reason) str_reason = std::string(reason); sLFGMgr->InitBoot(group, kicker, guid, str_reason); return; } sLFGMgr->ClearState(guid); if (Player *plr = sObjectMgr->GetPlayer(guid)) { /* if (method == GROUP_REMOVEMETHOD_LEAVE) // Add deserter flag else if (group->isLfgKickActive()) // Update internal kick cooldown of kicked */ LfgUpdateData updateData = LfgUpdateData(LFG_UPDATETYPE_LEADER); plr->GetSession()->SendLfgUpdateParty(updateData); if (plr->GetMap()->IsDungeon()) // Teleport player out the dungeon sLFGMgr->TeleportPlayer(plr, true); } if (sLFGMgr->GetState(gguid) != LFG_STATE_FINISHED_DUNGEON)// Need more players to finish the dungeon sLFGMgr->OfferContinue(group); } void LFGScripts::OnDisband(Group* group) { uint64 gguid = group->GetGUID(); sLog->outDebug("LFGScripts::OnDisband [" UI64FMTD "]", gguid); sLFGMgr->RemoveGroupData(gguid); } void LFGScripts::OnChangeLeader(Group* group, uint64 newLeaderGuid, uint64 oldLeaderGuid) { uint64 gguid = group->GetGUID(); if (!gguid) return; sLog->outDebug("LFGScripts::OnChangeLeader [" UI64FMTD "]: old [" UI64FMTD "] new [" UI64FMTD "]", gguid, newLeaderGuid, oldLeaderGuid); Player *plr = sObjectMgr->GetPlayer(newLeaderGuid); LfgUpdateData updateData = LfgUpdateData(LFG_UPDATETYPE_LEADER); if (plr) plr->GetSession()->SendLfgUpdateParty(updateData); plr = sObjectMgr->GetPlayer(oldLeaderGuid); if (plr) { updateData.updateType = LFG_UPDATETYPE_GROUP_DISBAND; plr->GetSession()->SendLfgUpdateParty(updateData); } } void LFGScripts::OnInviteMember(Group* group, uint64 guid) { uint64 gguid = group->GetGUID(); if (!gguid) return; sLog->outDebug("LFGScripts::OnInviteMember [" UI64FMTD "]: invite [" UI64FMTD "] leader [" UI64FMTD "]", gguid, guid, group->GetLeaderGUID()); sLFGMgr->Leave(NULL, group); } void LFGScripts::OnLevelChanged(Player* player, uint8 /*newLevel*/) { sLFGMgr->InitializeLockedDungeons(player); } void LFGScripts::OnLogout(Player* player) { sLFGMgr->Leave(player); LfgUpdateData updateData = LfgUpdateData(LFG_UPDATETYPE_REMOVED_FROM_QUEUE); player->GetSession()->SendLfgUpdateParty(updateData); player->GetSession()->SendLfgUpdatePlayer(updateData); player->GetSession()->SendLfgUpdateSearch(false); uint64 guid = player->GetGUID(); // TODO - Do not remove, add timer before deleting sLFGMgr->RemovePlayerData(guid); } void LFGScripts::OnLogin(Player* player) { sLFGMgr->InitializeLockedDungeons(player); // TODO - Restore LfgPlayerData and send proper status to player if it was in a group } void LFGScripts::OnBindToInstance(Player* player, Difficulty difficulty, uint32 mapId, bool permanent) { MapEntry const* mapEntry = sMapStore.LookupEntry(mapId); if (mapEntry->IsDungeon() && difficulty > DUNGEON_DIFFICULTY_NORMAL) sLFGMgr->InitializeLockedDungeons(player); }
gpl-3.0
MIND-Tools/mind-compiler
annotations/src/test/resources/functional/controller/binding/bcTester2.c
1
1963
#include <mindassert.h> #include <string.h> /* ----------------------------------------------------------------------------- Implementation of the main interface. ----------------------------------------------------------------------------- */ /* int main(int argc, string[] argv) */ int METH(main, main)(int argc, char *argv[]) { void *itf_ptr; /* starts with clientMain interface bound to tested1 (through enclosing composite) */ mindassert(IS_BOUND(clientMain)); mindassert(CALL(clientMain, main)(argc, argv) == 1); /* unbound clientMain interface of enclosing composite */ mindassert(CALL(superBC, unbindFc)("clientMain") == FRACTAL_API_OK); mindassert(! IS_BOUND(clientMain)); /* rebound clientMain interface of enclosing composite on tested2 */ mindassert(CALL(clientComp[2], getFcInterface)("main", &itf_ptr) == FRACTAL_API_OK); mindassert(CALL(superBC, bindFc)("clientMain", itf_ptr) == FRACTAL_API_OK); /* clientMain is still unbound since main interface of tested2 composite is not bound internally */ mindassert(! IS_BOUND(clientMain)); /* rebound clientMain interface of enclosing composite on tested1 */ mindassert(CALL(clientComp[1], getFcInterface)("main", &itf_ptr) == FRACTAL_API_OK); mindassert(CALL(superBC, bindFc)("clientMain", itf_ptr) == FRACTAL_API_OK); mindassert(IS_BOUND(clientMain)); mindassert(CALL(clientMain, main)(argc, argv) == 1); /* unbound my clientMain interface */ mindassert(CALL(bindingController, unbindFc)("clientMain") == FRACTAL_API_OK); mindassert(! IS_BOUND(clientMain)); /* rebound clientMain interface of myself on tested0 */ mindassert(CALL(clientComp[0], getFcInterface)("main", &itf_ptr) == FRACTAL_API_OK); mindassert(CALL(bindingController, bindFc)("clientMain", itf_ptr) == FRACTAL_API_OK); mindassert(IS_BOUND(clientMain)); mindassert(CALL(clientMain, main)(argc, argv) == 0); return 0; }
gpl-3.0
DrakonPL/Andromeda
Andromeda/Audio/IrrKlang/IrrSound.cpp
1
1740
#include <Andromeda/Audio/IrrKlang/IrrSound.h> #include <Andromeda/FileSystem/FileManager.h> #include <string> namespace Andromeda { namespace Audio { IrrSound::IrrSound(std::string name) : Sound(name) { _soundSource = 0; _looped = false; _sound = 0; _engine = 0; } IrrSound::~IrrSound() { if (_soundSource != 0) { _engine->removeSoundSource(_soundSource); delete _soundSource; } } void IrrSound::SetEngine(ISoundEngine* engine) { _engine = engine; } bool IrrSound::IsPlaying() { if (_sound == 0) { return false; } return !_sound->isFinished(); } bool IrrSound::LoadWav(std::string filePath, bool streaming) { std::string loadName = FileSystem::FileManager::Instance()->GetMainDirPath() + filePath; if (streaming) _soundSource = _engine->addSoundSourceFromFile(loadName.c_str(), ESM_STREAMING); else _soundSource = _engine->addSoundSourceFromFile(loadName.c_str(), ESM_NO_STREAMING); if (_soundSource == 0) return false; return true; } bool IrrSound::LoadOgg(std::string filePath) { std::string loadName = FileSystem::FileManager::Instance()->GetMainDirPath() + filePath; _soundSource = _engine->addSoundSourceFromFile(loadName.c_str()); if (_soundSource == 0) return false; return true; } void IrrSound::UpdateVolume() { if (_sound != 0) { _sound->setVolume(_volume); } } void IrrSound::Play() { if (_soundSource != 0) { _sound = _engine->play2D(_soundSource, _looped, false, true, true); _sound->setVolume(_volume); } } void IrrSound::Stop() { if (_sound != 0) { _sound->stop(); } } void IrrSound::Pause() { } } }
gpl-3.0
petmac/decaf-emu
src/libdecaf/src/modules/gx2/gx2_surface.cpp
1
17515
#include "gx2_addrlib.h" #include "gx2_enum_string.h" #include "gx2_format.h" #include "gx2_internal_cbpool.h" #include "gx2_surface.h" #include <common/align.h> #include <common/log.h> #include <common/pow.h> #include <gsl.h> #include <libgpu/gpu_tiling.h> namespace gx2 { static uint32_t calcNumLevelsForSize(uint32_t size) { return 32 - clz(size); } static uint32_t calcNumLevels(GX2Surface *surface) { if (surface->mipLevels <= 1) { return 1; } auto levels = std::max( calcNumLevelsForSize(surface->width), calcNumLevelsForSize(surface->height)); if (surface->dim == GX2SurfaceDim::Texture3D) { levels = std::max(levels, calcNumLevelsForSize(surface->depth)); } return levels; } void GX2CalcSurfaceSizeAndAlignment(GX2Surface *surface) { ADDR_COMPUTE_SURFACE_INFO_OUTPUT output; auto isDepthBuffer = !!(surface->use & GX2SurfaceUse::DepthBuffer); auto isColorBuffer = !!(surface->use & GX2SurfaceUse::ColorBuffer); auto tileModeChanged = false; if (surface->tileMode == GX2TileMode::Default) { if (surface->dim || surface->aa || isDepthBuffer) { if (surface->dim != GX2SurfaceDim::Texture3D || isColorBuffer) { surface->tileMode = GX2TileMode::Tiled2DThin1; } else { surface->tileMode = GX2TileMode::Tiled2DThick; } tileModeChanged = true; } else { surface->tileMode = GX2TileMode::LinearAligned; } } surface->mipLevels = std::max<uint32_t>(surface->mipLevels, 1u); surface->mipLevels = std::min<uint32_t>(surface->mipLevels, calcNumLevels(surface)); surface->mipLevelOffset[0] = 0; surface->swizzle &= 0xFF00FFFF; if (surface->tileMode >= GX2TileMode::Tiled2DThin1 && surface->tileMode != GX2TileMode::LinearSpecial) { surface->swizzle |= 0xD0000; } auto lastTileMode = static_cast<GX2TileMode>(surface->tileMode); auto prevSize = 0u; auto offset0 = 0u; for (auto level = 0u; level < surface->mipLevels; ++level) { gx2::internal::getSurfaceInfo(surface, level, &output); if (level) { auto pad = 0u; if (lastTileMode >= GX2TileMode::Tiled2DThin1 && lastTileMode != GX2TileMode::LinearSpecial) { if (output.tileMode < ADDR_TM_2D_TILED_THIN1) { surface->swizzle = (level << 16) | (surface->swizzle & 0xFF00FFFF); lastTileMode = static_cast<GX2TileMode>(output.tileMode); if (level > 1) { pad = surface->swizzle & 0xFFFF; } } } pad += (output.baseAlign - (prevSize % output.baseAlign)) % output.baseAlign; if (level == 1) { offset0 = pad + prevSize; } else { surface->mipLevelOffset[level - 1] = pad + prevSize + surface->mipLevelOffset[level - 2]; } } else { if (tileModeChanged && surface->width < output.pitchAlign && surface->height < output.heightAlign) { if (surface->tileMode == GX2TileMode::Tiled2DThick) { surface->tileMode = GX2TileMode::Tiled1DThick; } else { surface->tileMode = GX2TileMode::Tiled1DThin1; } gx2::internal::getSurfaceInfo(surface, level, &output); surface->swizzle &= 0xFF00FFFF; lastTileMode = surface->tileMode; } surface->imageSize = static_cast<uint32_t>(output.surfSize); surface->alignment = output.baseAlign; surface->pitch = output.pitch; } prevSize = static_cast<uint32_t>(output.surfSize); } if (surface->mipLevels <= 1) { surface->mipmapSize = 0; } else { surface->mipmapSize = prevSize + surface->mipLevelOffset[surface->mipLevels - 2]; } surface->mipLevelOffset[0] = offset0; if (surface->format == GX2SurfaceFormat::UNORM_NV12) { auto pad = (surface->alignment - surface->imageSize % surface->alignment) % surface->alignment; surface->mipLevelOffset[0] = pad + surface->imageSize; surface->imageSize = surface->mipLevelOffset[0] + (surface->imageSize >> 1); } } void GX2CalcDepthBufferHiZInfo(GX2DepthBuffer *depthBuffer, be_val<uint32_t> *outSize, be_val<uint32_t> *outAlignment) { ADDR_COMPUTE_HTILE_INFO_INPUT input; ADDR_COMPUTE_HTILE_INFO_OUTPUT output; std::memset(&input, 0, sizeof(ADDR_COMPUTE_HTILE_INFO_INPUT)); std::memset(&output, 0, sizeof(ADDR_COMPUTE_HTILE_INFO_OUTPUT)); input.size = sizeof(ADDR_COMPUTE_HTILE_INFO_INPUT); output.size = sizeof(ADDR_COMPUTE_HTILE_INFO_OUTPUT); input.pitch = depthBuffer->surface.pitch; input.height = depthBuffer->surface.height; input.numSlices = depthBuffer->surface.depth; input.blockWidth = ADDR_HTILE_BLOCKSIZE_8; input.blockHeight = ADDR_HTILE_BLOCKSIZE_8; AddrComputeHtileInfo(gpu::getAddrLibHandle(), &input, &output); depthBuffer->hiZSize = gsl::narrow_cast<uint32_t>(output.htileBytes); if (outSize) { *outSize = depthBuffer->hiZSize; } if (outAlignment) { *outAlignment = output.baseAlign; } } void GX2CalcColorBufferAuxInfo(GX2Surface *surface, be_val<uint32_t> *outSize, be_val<uint32_t> *outAlignment) { gLog->warn("Application called GX2CalcColorBufferAuxInfo"); *outSize = 2048; *outAlignment = 2048; } void GX2SetColorBuffer(GX2ColorBuffer *colorBuffer, GX2RenderTarget target) { using latte::Register; auto reg = [](unsigned id) { return static_cast<Register>(id); }; auto cb_color_info = colorBuffer->regs.cb_color_info.value(); auto cb_color_mask = colorBuffer->regs.cb_color_mask.value(); auto cb_color_size = colorBuffer->regs.cb_color_size.value(); auto cb_color_view = colorBuffer->regs.cb_color_view.value(); auto addr = colorBuffer->surface.image.getAddress(); auto addrTile = 0u; auto addrFrag = 0u; if (colorBuffer->viewMip) { addr = colorBuffer->surface.mipmaps.getAddress(); if (colorBuffer->viewMip > 1) { addr += colorBuffer->surface.mipLevelOffset[colorBuffer->viewMip - 1]; } } if (colorBuffer->surface.tileMode >= GX2TileMode::Tiled2DThin1 && colorBuffer->surface.tileMode != GX2TileMode::LinearSpecial) { if (colorBuffer->viewMip < ((colorBuffer->surface.swizzle >> 16) & 0xFF)) { addr ^= colorBuffer->surface.swizzle & 0xFFFF; } } if (colorBuffer->surface.aa) { addrFrag = colorBuffer->aaBuffer.getAddress(); addrTile = addrFrag + colorBuffer->regs.cmask_offset; } internal::writePM4(latte::pm4::SetContextReg { reg(Register::CB_COLOR0_BASE + target * 4), addr >> 8 }); internal::writePM4(latte::pm4::SetContextReg { reg(Register::CB_COLOR0_SIZE + target * 4), cb_color_size.value }); internal::writePM4(latte::pm4::SetContextReg { reg(Register::CB_COLOR0_INFO + target * 4), cb_color_info.value }); internal::writePM4(latte::pm4::SetContextReg { reg(Register::CB_COLOR0_TILE + target * 4), addrTile >> 8 }); internal::writePM4(latte::pm4::SetContextReg { reg(Register::CB_COLOR0_FRAG + target * 4), addrFrag >> 8 }); internal::writePM4(latte::pm4::SetContextReg { reg(Register::CB_COLOR0_VIEW + target * 4), cb_color_view.value }); internal::writePM4(latte::pm4::SetContextReg { reg(Register::CB_COLOR0_MASK + target * 4), cb_color_mask.value }); } void GX2SetDepthBuffer(GX2DepthBuffer *depthBuffer) { auto db_depth_info = depthBuffer->regs.db_depth_info.value(); auto db_depth_size = depthBuffer->regs.db_depth_size.value(); auto db_depth_view = depthBuffer->regs.db_depth_view.value(); auto db_htile_surface = depthBuffer->regs.db_htile_surface.value(); auto db_prefetch_limit = depthBuffer->regs.db_prefetch_limit.value(); auto db_preload_control = depthBuffer->regs.db_preload_control.value(); auto pa_poly_offset_cntl = depthBuffer->regs.pa_poly_offset_cntl.value(); uint32_t values1[] = { db_depth_size.value, db_depth_view.value, }; internal::writePM4(latte::pm4::SetContextRegs { latte::Register::DB_DEPTH_SIZE, gsl::make_span(values1) }); auto addr = depthBuffer->surface.image.getAddress(); auto addrHiZ = depthBuffer->hiZPtr.getAddress(); if (depthBuffer->viewMip) { addr = depthBuffer->surface.mipmaps.getAddress(); if (depthBuffer->viewMip > 1) { addr += depthBuffer->surface.mipLevelOffset[depthBuffer->viewMip - 1]; } } if (depthBuffer->surface.tileMode >= GX2TileMode::Tiled2DThin1 && depthBuffer->surface.tileMode != GX2TileMode::LinearSpecial) { if (depthBuffer->viewMip < ((depthBuffer->surface.swizzle >> 16) & 0xFF)) { addr ^= depthBuffer->surface.swizzle & 0xFFFF; } } uint32_t values2[] = { addr >> 8, db_depth_info.value, addrHiZ >> 8, }; internal::writePM4(latte::pm4::SetContextRegs { latte::Register::DB_DEPTH_BASE, gsl::make_span(values2) }); internal::writePM4(latte::pm4::SetContextReg { latte::Register::DB_HTILE_SURFACE, db_htile_surface.value }); internal::writePM4(latte::pm4::SetContextReg { latte::Register::DB_PREFETCH_LIMIT, db_prefetch_limit.value }); internal::writePM4(latte::pm4::SetContextReg { latte::Register::DB_PRELOAD_CONTROL, db_preload_control.value }); internal::writePM4(latte::pm4::SetContextReg { latte::Register::PA_SU_POLY_OFFSET_DB_FMT_CNTL, pa_poly_offset_cntl.value }); uint32_t values3[] = { depthBuffer->stencilClear, bit_cast<uint32_t, float>(depthBuffer->depthClear), }; internal::writePM4(latte::pm4::SetContextRegs { latte::Register::DB_STENCIL_CLEAR, gsl::make_span(values3) }); } void GX2InitColorBufferRegs(GX2ColorBuffer *colorBuffer) { auto cb_color_info = latte::CB_COLORN_INFO::get(0); auto cb_color_size = latte::CB_COLORN_SIZE::get(0); // Update cb_color_info auto format = internal::getSurfaceFormatColorFormat(colorBuffer->surface.format); auto numberType = internal::getSurfaceFormatColorNumberType(colorBuffer->surface.format); cb_color_info = cb_color_info .FORMAT(format) .NUMBER_TYPE(numberType); // Update cb_color_size ADDR_COMPUTE_SURFACE_INFO_OUTPUT output; internal::getSurfaceInfo(&colorBuffer->surface, 0, &output); auto pitchTileMax = (output.pitch / latte::MicroTileWidth) - 1; auto sliceTileMax = ((output.pitch * output.height) / (latte::MicroTileWidth * latte::MicroTileHeight)) - 1; cb_color_size = cb_color_size .PITCH_TILE_MAX(pitchTileMax) .SLICE_TILE_MAX(sliceTileMax); // TODO: Set more regs! // Save big endian registers std::memset(&colorBuffer->regs, 0, sizeof(colorBuffer->regs)); colorBuffer->regs.cb_color_info = cb_color_info; colorBuffer->regs.cb_color_size = cb_color_size; } void GX2InitDepthBufferRegs(GX2DepthBuffer *depthBuffer) { auto db_depth_info = latte::DB_DEPTH_INFO::get(0); auto db_depth_size = latte::DB_DEPTH_SIZE::get(0); // Update db_depth_info auto format = internal::getSurfaceFormatDepthFormat(depthBuffer->surface.format); db_depth_info = db_depth_info .FORMAT(format); // Update db_depth_size ADDR_COMPUTE_SURFACE_INFO_OUTPUT output; internal::getSurfaceInfo(&depthBuffer->surface, 0, &output); auto pitchTileMax = (output.pitch / latte::MicroTileWidth) - 1; auto sliceTileMax = ((output.pitch * output.height) / (latte::MicroTileWidth * latte::MicroTileHeight)) - 1; db_depth_size = db_depth_size .PITCH_TILE_MAX(pitchTileMax) .SLICE_TILE_MAX(sliceTileMax); // TODO: Set more regs! // Save big endian registers std::memset(&depthBuffer->regs, 0, sizeof(depthBuffer->regs)); depthBuffer->regs.db_depth_info = db_depth_info; depthBuffer->regs.db_depth_size = db_depth_size; } void GX2InitDepthBufferHiZEnable(GX2DepthBuffer *depthBuffer, BOOL enable) { auto db_depth_info = depthBuffer->regs.db_depth_info.value(); db_depth_info = db_depth_info .TILE_SURFACE_ENABLE(!!enable); depthBuffer->regs.db_depth_info = db_depth_info; } uint32_t GX2GetSurfaceSwizzle(GX2Surface *surface) { return (surface->swizzle >> 8) & 0xff; } uint32_t GX2GetSurfaceSwizzleOffset(GX2Surface *surface, uint32_t level) { if (surface->tileMode < GX2TileMode::Tiled2DThin1 || surface->tileMode == GX2TileMode::LinearSpecial) { return 0; } if (level < ((surface->swizzle >> 16) & 0xFF)) { return 0; } return surface->swizzle & 0xFFFF; } void GX2SetSurfaceSwizzle(GX2Surface *surface, uint32_t swizzle) { surface->swizzle &= 0xFFFF00FF; surface->swizzle |= swizzle << 8; } uint32_t GX2GetSurfaceMipPitch(GX2Surface *surface, uint32_t level) { ADDR_COMPUTE_SURFACE_INFO_OUTPUT info; internal::getSurfaceInfo(surface, level, &info); return info.pitch; } uint32_t GX2GetSurfaceMipSliceSize(GX2Surface *surface, uint32_t level) { ADDR_COMPUTE_SURFACE_INFO_OUTPUT info; internal::getSurfaceInfo(surface, level, &info); return internal::calcSliceSize(surface, &info); } void GX2CopySurface(GX2Surface *src, uint32_t srcLevel, uint32_t srcSlice, GX2Surface *dst, uint32_t dstLevel, uint32_t dstSlice) { if (src->format == GX2SurfaceFormat::INVALID || src->width == 0 || src->height == 0) { return; } if (dst->format == GX2SurfaceFormat::INVALID) { return; } if (src->tileMode == GX2TileMode::LinearSpecial || dst->tileMode == GX2TileMode::LinearSpecial) { // LinearSpecial surfaces cause the copy to occur on the CPU. This code // assumes that if the texture was previously written by the GPU, that it // has since been invalidated into CPU memory. gx2::internal::copySurface(src, srcLevel, srcSlice, dst, dstLevel, dstSlice); return; } auto dstDim = static_cast<latte::SQ_TEX_DIM>(dst->dim.value()); auto dstFormat = static_cast<latte::SQ_DATA_FORMAT>(dst->format & 0x3f); auto dstTileMode = static_cast<latte::SQ_TILE_MODE>(dst->tileMode.value()); auto dstFormatComp = latte::SQ_FORMAT_COMP::UNSIGNED; auto dstNumFormat = latte::SQ_NUM_FORMAT::NORM; auto dstForceDegamma = false; auto dstPitch = dst->pitch; auto dstDepth = dst->depth; auto dstSamples = 0u; if (dst->format & GX2AttribFormatFlags::SIGNED) { dstFormatComp = latte::SQ_FORMAT_COMP::SIGNED; } if (dst->format & GX2AttribFormatFlags::SCALED) { dstNumFormat = latte::SQ_NUM_FORMAT::SCALED; } else if (dst->format & GX2AttribFormatFlags::INTEGER) { dstNumFormat = latte::SQ_NUM_FORMAT::INT; } if (dst->format & GX2AttribFormatFlags::DEGAMMA) { dstForceDegamma = true; } if (dstFormat >= latte::SQ_DATA_FORMAT::FMT_BC1 && dstFormat <= latte::SQ_DATA_FORMAT::FMT_BC5) { dstPitch *= 4; } if (dstDim == latte::SQ_TEX_DIM::DIM_CUBEMAP) { dstDepth /= 6; } if (dst->aa == GX2AAMode::Mode2X) { dstSamples = 2; } else if (dst->aa == GX2AAMode::Mode4X) { dstSamples = 4; } else if (dst->aa == GX2AAMode::Mode8X) { dstSamples = 8; } auto srcDim = static_cast<latte::SQ_TEX_DIM>(src->dim.value()); auto srcFormat = static_cast<latte::SQ_DATA_FORMAT>(src->format & 0x3f); auto srcTileMode = static_cast<latte::SQ_TILE_MODE>(src->tileMode.value()); auto srcFormatComp = latte::SQ_FORMAT_COMP::UNSIGNED; auto srcNumFormat = latte::SQ_NUM_FORMAT::NORM; auto srcForceDegamma = false; auto srcPitch = src->pitch; auto srcDepth = src->depth; auto srcSamples = 0u; if (src->format & GX2AttribFormatFlags::SIGNED) { srcFormatComp = latte::SQ_FORMAT_COMP::SIGNED; } if (src->format & GX2AttribFormatFlags::SCALED) { srcNumFormat = latte::SQ_NUM_FORMAT::SCALED; } else if (src->format & GX2AttribFormatFlags::INTEGER) { srcNumFormat = latte::SQ_NUM_FORMAT::INT; } if (src->format & GX2AttribFormatFlags::DEGAMMA) { srcForceDegamma = true; } if (srcFormat >= latte::SQ_DATA_FORMAT::FMT_BC1 && srcFormat <= latte::SQ_DATA_FORMAT::FMT_BC5) { srcPitch *= 4; } if (srcDim == latte::SQ_TEX_DIM::DIM_CUBEMAP) { srcDepth /= 6; } if (src->aa == GX2AAMode::Mode2X) { srcSamples = 2; } else if (src->aa == GX2AAMode::Mode4X) { srcSamples = 4; } else if (src->aa == GX2AAMode::Mode8X) { srcSamples = 8; } internal::writePM4(latte::pm4::DecafCopySurface { dst->image.getAddress(), dst->mipmaps.getAddress(), dstLevel, dstSlice, dstPitch, dst->width, dst->height, dstDepth, dstSamples, dstDim, dstFormat, dstNumFormat, dstFormatComp, dstForceDegamma ? 1u : 0u, dstTileMode, src->image.getAddress(), src->mipmaps.getAddress(), srcLevel, srcSlice, srcPitch, src->width, src->height, srcDepth, srcSamples, srcDim, srcFormat, srcNumFormat, srcFormatComp, srcForceDegamma ? 1u : 0u, srcTileMode }); } void GX2ExpandDepthBuffer(GX2DepthBuffer *buffer) { // We do not implement HiZ, so no need to do anything here } } // namespace gx2
gpl-3.0
WohlSoft/PGE-Project
Editor/main_window/testing/testing_settings.cpp
1
5281
#include "testing_settings.h" #include "ui_testing_settings.h" #include <mainwindow.h> #include <main_window/global_settings.h> #include <data_configs/data_configs.h> #include <QMessageBox> TestingSettings::TestingSettings(QWidget *parent) : QDialog(parent), ui(new Ui::TestingSettings) { ui->setupUi(this); MainWindow* mw = qobject_cast<MainWindow*>(this->parent()); if(mw) { QList<obj_player>& plr = mw->configs.main_characters; ui->p1_character->clear(); ui->p2_character->clear(); for(obj_player& p : plr) { ui->p1_character->addItem(p.name); ui->p2_character->addItem(p.name); } reloadStates1(0); reloadStates2(0); connect(ui->p1_character, static_cast<void(QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &TestingSettings::reloadStates1 ); connect(ui->p2_character, static_cast<void(QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &TestingSettings::reloadStates2 ); } ui->ex_god->setChecked(GlobalSettings::testing.xtra_god); ui->ex_flyup->setChecked(GlobalSettings::testing.xtra_flyup); ui->ex_chuck->setChecked(GlobalSettings::testing.xtra_chuck); ui->ex_debug->setChecked(GlobalSettings::testing.xtra_debug); ui->ex_showFPS->setChecked(GlobalSettings::testing.xtra_showFPS); ui->ex_physdebug->setChecked(GlobalSettings::testing.xtra_physdebug); ui->ex_freedom->setChecked(GlobalSettings::testing.xtra_worldfreedom); ui->ex_starsNum->setValue(GlobalSettings::testing.xtra_starsNum); ui->p1_character->setCurrentIndex(GlobalSettings::testing.p1_char-1); ui->p1_state->setCurrentIndex(GlobalSettings::testing.p1_state-1); ui->p1_vehicleID->setCurrentIndex(GlobalSettings::testing.p1_vehicleID); ui->p1_vehicleType->setCurrentIndex(GlobalSettings::testing.p1_vehicleType); ui->p2_character->setCurrentIndex(GlobalSettings::testing.p2_char-1); ui->p2_state->setCurrentIndex(GlobalSettings::testing.p2_state-1); ui->p2_vehicleID->setCurrentIndex(GlobalSettings::testing.p2_vehicleID); ui->p2_vehicleType->setCurrentIndex(GlobalSettings::testing.p2_vehicleType); switch(GlobalSettings::testing.numOfPlayers) { case 1:default: ui->np_1p->setChecked(true);break; case 2: ui->np_2p->setChecked(true);break; } } TestingSettings::~TestingSettings() { delete ui; } void TestingSettings::on_buttonBox_accepted() { GlobalSettings::testing.xtra_god = ui->ex_god->isChecked(); GlobalSettings::testing.xtra_flyup = ui->ex_flyup->isChecked(); GlobalSettings::testing.xtra_chuck = ui->ex_chuck->isChecked(); GlobalSettings::testing.xtra_debug = ui->ex_debug->isChecked(); GlobalSettings::testing.xtra_showFPS = ui->ex_showFPS->isChecked(); GlobalSettings::testing.xtra_physdebug = ui->ex_physdebug->isChecked(); GlobalSettings::testing.xtra_worldfreedom = ui->ex_freedom->isChecked(); GlobalSettings::testing.xtra_starsNum = ui->ex_starsNum->value(); if(ui->np_1p->isChecked()) GlobalSettings::testing.numOfPlayers = 1; else if(ui->np_2p->isChecked()) GlobalSettings::testing.numOfPlayers = 2; else GlobalSettings::testing.numOfPlayers = 1; GlobalSettings::testing.p1_char = (ui->p1_character->currentIndex()+1); GlobalSettings::testing.p1_state = (ui->p1_state->currentIndex()+1); GlobalSettings::testing.p1_vehicleID = (ui->p1_vehicleID->currentIndex()); GlobalSettings::testing.p1_vehicleType = (ui->p1_vehicleType->currentIndex()); GlobalSettings::testing.p2_char = (ui->p2_character->currentIndex()+1); GlobalSettings::testing.p2_state = (ui->p2_state->currentIndex()+1); GlobalSettings::testing.p2_vehicleID = (ui->p2_vehicleID->currentIndex()); GlobalSettings::testing.p2_vehicleType = (ui->p2_vehicleType->currentIndex()); this->close(); } void TestingSettings::reloadStates1(int index) { MainWindow* mw = qobject_cast<MainWindow*>(this->parent()); if(mw) { int character = index; if(character < 0) return; QList<obj_player>& plr = mw->configs.main_characters; if(character >= plr.size()) return; QList<obj_player_state>& states = plr[character].states; int oldIndex = ui->p1_state->currentIndex(); ui->p1_state->clear(); for(obj_player_state& p : states) { ui->p1_state->addItem(p.name); } ui->p1_state->setCurrentIndex(oldIndex); } } void TestingSettings::reloadStates2(int index) { MainWindow* mw = qobject_cast<MainWindow*>(this->parent()); if(mw) { int character = index; if(character < 0) return; QList<obj_player>& plr = mw->configs.main_characters; if(character >= plr.size()) return; QList<obj_player_state>& states = plr[character].states; int oldIndex = ui->p2_state->currentIndex(); ui->p2_state->clear(); for(obj_player_state& p : states) { ui->p2_state->addItem(p.name); } ui->p2_state->setCurrentIndex(oldIndex); } } void TestingSettings::showEvent(QShowEvent *event) { QDialog::showEvent(event); qApp->processEvents(); emit windowShown(); }
gpl-3.0
Sekuraz/NumSim
src/test_iterator.cpp
1
1947
/* * Copyright (C) 2016 Malte Brunn, Stephan Lunowa, Markus Baur * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include "typedef.hpp" #include "comm.hpp" #include "geometry.hpp" #include "iterator.hpp" #include "parameter.hpp" #ifdef USE_DEBUG_VISU #include "visu.hpp" #endif #include "grid.hpp" int main(int argc, char *argv[]) { Communicator comm(&argc, &argv); // Create parameter and geometry instances and load values Parameter param; param.Load("param.txt"); Geometry geom (comm, {6, 6}); const multi_real_t &h = geom.Mesh(); multi_real_t offset(h[0]/2, h[1]/2); Grid g (geom, offset); g.Initialize(0); #ifdef USE_DEBUG_VISU // Create and initialize the visualization Renderer visu(geom.Length(), geom.Mesh()); visu.Init(600,600); #endif for (InteriorIterator it (geom); it.Valid(); it.Next()) { g.Cell(it) = 1; geom.Update_P(g); #ifdef USE_DEBUG_VISU visu.Render(&g); #endif g.print(); std::cin.get(); g.Cell(it) = 0; } /* BoundaryIterator it (geom); for (int i = 0; i < 4; i++) { it.SetBoundary(i % 4 + 1); for(; it.Valid(); it.Next()) { g.Cell(it) = 100; visu.Render(&g); g.print(); std::cin.get(); g.Cell(it) = 0; } } */ return 0; }
gpl-3.0
spacy-dev/Spacy-Integration-Tests
FEniCS/vectorCreator.cpp
1
6580
#include <gtest.hh> #include <dolfin.h> #include <Spacy/spacy.h> #include <Spacy/Adapter/FEniCS/vectorSpace.hh> #include "LinearHeat.h" #include "L2Functional.h" using namespace Spacy; // test setup const constexpr auto scalar_degrees_of_freedom = 2; const constexpr auto degrees_of_freedom = scalar_degrees_of_freedom * scalar_degrees_of_freedom; const constexpr auto number_of_variables = 3; const auto mesh1D = std::make_shared<dolfin::UnitIntervalMesh>(MPI_COMM_WORLD, degrees_of_freedom-1); const auto mesh2D = std::make_shared<dolfin::UnitSquareMesh>(scalar_degrees_of_freedom-1, scalar_degrees_of_freedom-1); const auto dolfin_V1D = std::make_shared<LinearHeat::FunctionSpace>(mesh1D); const auto dolfin_V2D = std::make_shared<L2Functional::CoefficientSpace_x>(mesh2D); const auto V1D = Spacy::FEniCS::makeHilbertSpace(dolfin_V1D); const auto V2D = Spacy::FEniCS::makeHilbertSpace(dolfin_V2D, {0,1,2}, {}); const auto V2D_perm = Spacy::FEniCS::makeHilbertSpace(dolfin_V2D, {2,0,1}, {}); const auto V2DPrimalDual = Spacy::FEniCS::makeHilbertSpace(dolfin_V2D, {0,1}, {2}); TEST(FEniCS,SingleSpaceCreator) { const auto& V = creator<FEniCS::VectorCreator>(V1D); EXPECT_EQ( V.size(), degrees_of_freedom ); EXPECT_EQ( V.dofmap(0), 0 ); EXPECT_EQ( V.dofmap(1), 1 ); EXPECT_EQ( V.inverseDofmap(0), 0 ); EXPECT_EQ( V.inverseDofmap(1), 1 ); } TEST(FEniCS,ProductSpaceCreator) { const auto& X = creator<ProductSpace::VectorCreator>(V2D); const auto& Y = creator<FEniCS::VectorCreator>(X.subSpace(0)); const auto& U = creator<FEniCS::VectorCreator>(X.subSpace(1)); const auto& P = creator<FEniCS::VectorCreator>(X.subSpace(2)); EXPECT_EQ( Y.size(), degrees_of_freedom ); EXPECT_EQ( U.size(), degrees_of_freedom ); EXPECT_EQ( P.size(), degrees_of_freedom ); } TEST(FEniCS,ProductSpaceCreator_IdMap) { const auto& X = creator<ProductSpace::VectorCreator>(V2D); EXPECT_EQ( X.idMap(0), 0 ); EXPECT_EQ( X.idMap(1), 1 ); EXPECT_EQ( X.idMap(2), 2 ); EXPECT_EQ( X.inverseIdMap(0), 0 ); EXPECT_EQ( X.inverseIdMap(1), 1 ); EXPECT_EQ( X.inverseIdMap(2), 2 ); const auto& X_perm = creator<ProductSpace::VectorCreator>(V2D_perm); EXPECT_EQ( X_perm.idMap(0), 1 ); EXPECT_EQ( X_perm.idMap(1), 2 ); EXPECT_EQ( X_perm.idMap(2), 0 ); EXPECT_EQ( X_perm.inverseIdMap(0), 2 ); EXPECT_EQ( X_perm.inverseIdMap(1), 0 ); EXPECT_EQ( X_perm.inverseIdMap(2), 1 ); } TEST(FEniCS,ProductSpaceCreator_DofMap) { const auto& X = creator<ProductSpace::VectorCreator>(V2D); const auto& Y = creator<FEniCS::VectorCreator>(X.subSpace(0)); const auto& U = creator<FEniCS::VectorCreator>(X.subSpace(1)); const auto& P = creator<FEniCS::VectorCreator>(X.subSpace(2)); for(auto i=0; i<degrees_of_freedom; ++i) { EXPECT_EQ( Y.dofmap(i), i*number_of_variables ); EXPECT_EQ( Y.inverseDofmap(i*number_of_variables), i ); } for(auto i=0; i<degrees_of_freedom; ++i) { EXPECT_EQ( U.dofmap(i), i*number_of_variables+1 ); EXPECT_EQ( U.inverseDofmap(i*number_of_variables+1), i ); } for(auto i=0; i<degrees_of_freedom; ++i) { EXPECT_EQ( P.dofmap(i), i*number_of_variables+2 ); EXPECT_EQ( P.inverseDofmap(i*number_of_variables+2), i ); } } TEST(FEniCS,ProductSpaceCreator_DofMap_PermutedSpace) { const auto& X = creator<ProductSpace::VectorCreator>(V2D_perm); const auto& Y = creator<FEniCS::VectorCreator>(X.subSpace(X.idMap(0))); const auto& U = creator<FEniCS::VectorCreator>(X.subSpace(X.idMap(1))); const auto& P = creator<FEniCS::VectorCreator>(X.subSpace(X.idMap(2))); for(auto i=0; i<degrees_of_freedom; ++i) { EXPECT_EQ( Y.dofmap(i), i*number_of_variables ); EXPECT_EQ( Y.inverseDofmap(i*number_of_variables), i ); } for(auto i=0; i<degrees_of_freedom; ++i) { EXPECT_EQ( U.dofmap(i), i*number_of_variables+1 ); EXPECT_EQ( U.inverseDofmap(i*number_of_variables+1), i ); } for(auto i=0; i<degrees_of_freedom; ++i) { EXPECT_EQ( P.dofmap(i), i*number_of_variables+2 ); EXPECT_EQ( P.inverseDofmap(i*number_of_variables+2), i ); } } TEST(FEniCS,PrimalDualProductSpaceCreator) { const auto& X = creator<ProductSpace::VectorCreator>(V2DPrimalDual); const auto& X_primal = creator<ProductSpace::VectorCreator>(X.subSpace(0)); const auto& X_dual = creator<ProductSpace::VectorCreator>(X.subSpace(1)); const auto& Y = creator<FEniCS::VectorCreator>(X_primal.subSpace(0)); const auto& U = creator<FEniCS::VectorCreator>(X_primal.subSpace(1)); const auto& P = creator<FEniCS::VectorCreator>(X_dual.subSpace(0)); EXPECT_EQ( Y.size(), degrees_of_freedom ); EXPECT_EQ( U.size(), degrees_of_freedom ); EXPECT_EQ( P.size(), degrees_of_freedom ); } TEST(FEniCS,PrimalDualProductSpaceCreator_IdMap) { const auto& X = creator<ProductSpace::VectorCreator>(V2DPrimalDual); const auto& X_primal = creator<ProductSpace::VectorCreator>(X.subSpace(0)); const auto& X_dual = creator<ProductSpace::VectorCreator>(X.subSpace(1)); EXPECT_EQ( X.idMap(0), 0 ); EXPECT_EQ( X.idMap(1), 1 ); EXPECT_EQ( X.inverseIdMap(0), 0 ); EXPECT_EQ( X.inverseIdMap(1), 1 ); EXPECT_EQ( X_primal.idMap(0), 0 ); EXPECT_EQ( X_primal.idMap(1), 1 ); EXPECT_EQ( X_dual.idMap(2), 0 ); EXPECT_EQ( X_primal.inverseIdMap(0), 0 ); EXPECT_EQ( X_primal.inverseIdMap(1), 1 ); EXPECT_EQ( X_dual.inverseIdMap(0), 2 ); } TEST(FEniCS,PrimalDualProductSpaceCreator_DofMap) { const auto& X = creator<ProductSpace::VectorCreator>(V2DPrimalDual); const auto& X_primal = creator<ProductSpace::VectorCreator>(X.subSpace(0)); const auto& X_dual = creator<ProductSpace::VectorCreator>(X.subSpace(1)); const auto& Y = creator<FEniCS::VectorCreator>(X_primal.subSpace(0)); const auto& U = creator<FEniCS::VectorCreator>(X_primal.subSpace(1)); const auto& P = creator<FEniCS::VectorCreator>(X_dual.subSpace(0)); for(auto i=0; i<degrees_of_freedom; ++i) { EXPECT_EQ( Y.dofmap(i), i*number_of_variables ); EXPECT_EQ( Y.inverseDofmap(i*number_of_variables), i ); } for(auto i=0; i<degrees_of_freedom; ++i) { EXPECT_EQ( U.dofmap(i), i*number_of_variables+1 ); EXPECT_EQ( U.inverseDofmap(i*number_of_variables+1), i ); } for(auto i=0; i<degrees_of_freedom; ++i) { EXPECT_EQ( P.dofmap(i), i*number_of_variables+2 ); EXPECT_EQ( P.inverseDofmap(i*number_of_variables+2), i ); } }
gpl-3.0
zerpiko/libraries
SurfaceCoefficients.cpp
1
34963
#include "SurfaceCoefficients.h" #include <math.h> SurfaceCoefficients::SurfaceCoefficients (double surface_water_tension_, double precipitation_, bool moisture_movement_) { //surface_water_tension = 430 * 0.1; // constant, (m) EXPERIMENTAL //surface_water_tension = -75.2025; // constant, (m) Garrat 1994 if (moisture_movement==false) surface_water_tension=-75.2025; else surface_water_tension=surface_water_tension_; precipitation = precipitation_; moisture_movement = moisture_movement_; molar_mass_water = 0.0180153; // constant, (kg/mol) molar_mass_air = 0.02897; // constant, (kg/mol) gravity_constant = 9.81; // constant, (m/s2) gas_constant = 8.3144621; // constant, (J/molK) steffan_boltzmann = 5.67E-8; // constant, (W/m2K4) von_karman = 0.41; // constant, (dimensionless) air_density = 1.2041; // (kg/m3) air_specific_heat_capacity = 1012; // (J/kgK) water_latent_heat_of_vaporization = 2.26E6; // (J/kg) atmospheric_pressure = 101325.; // (Pa) absortivity_soil_Jansson = 0.85; // Garrat 1994, (dimensionless) absortivity_road_Jansson = 0.90; // Jansson 2006, (dimensionless) absortivity_soil_Herb = 0.85; // Herb 2008, (dimensionless) absortivity_road_Herb = 0.88; // Herb 2008, (dimensionless) //0.88 absortivity_soil_Best = 0.85; // Herb 2008, (dimensionless) absortivity_road_Best = 0.88; // Herb 2008, (dimensionless) absortivity_snow = 0.15; // Garrat 1994, fresh snow 0.05 - 0.35 emissivity_soil_Jansson = 0.97; // Garrat 1994, (dimensionless) emissivity_road_Jansson = 1.00; // Jansson 2006, (dimensionless) emissivity_soil_Herb = 0.95; // Herb 2008, (dimensionless) emissivity_road_Herb = 0.94; // Herb 2008, (dimensionless) //0.94 emissivity_soil_Best = 0.95; // Herb 2008, (dimensionless) emissivity_road_Best = 0.94; // Herb 2008, (dimensionless) emissivity_canopy_Best = 0.95; // Herb 2008, (dimensionless) emissivity_snow=0.95; // Garrat 1994 a_Jansson = 0.540; // Monteith 1961, Brunt 1932, (dimensionless) b_Jansson = 0.065; // Monteith 1961, Brunt 1932, (1/hPa) z_road_momentum_roughness = 5E-4; // (m) z_road_heat_roughness = 1E-4; // (m) z_soil_momentum_roughness = 1E-3; // (m) z_soil_heat_roughness = 1E-3; // (m) z_ref_wind = 3.0; // (m) z_ref_temperature = 3.0; // (m) coefficient_forced_convection = 0.0015; // (dimensionless) nominal value according to Herb et al 2008 0.0015 coefficient_natural_convection = 0.0015; // (m/s 1/K^0.33) nominal value according to Herb et al 2008 0.0015 coefficient_sheltering = 1.0000; // (dimensionless) psychrometric_constant = (air_specific_heat_capacity * atmospheric_pressure / ((molar_mass_water/molar_mass_air) * water_latent_heat_of_vaporization)); // (Pa/K) } double SurfaceCoefficients:: get_sky_emissivity (const std::string author, const double air_temperature, const double relative_humidity) { double vapour_pressure_air= (relative_humidity/100.) *Clasius_Clapeyron_saturated_vapour_pressure(air_temperature); double sky_emissivity=0; if (author=="Jansson")//Brunt 1932 (vapor pressure must be in hPa) { sky_emissivity= a_Jansson + b_Jansson*pow((vapour_pressure_air/100.),0.5); } else if (author=="Herb" || author=="Best") { double coefficient_cloud_cover=0.5; /* Edinger 1956? Apparently the vapor pressure must be in hPa (requires confirmation, I haven't been able to locate the reference. It is cited in Herb et al 2008. */ sky_emissivity= coefficient_cloud_cover + 0.67*(1-coefficient_cloud_cover)* pow(vapour_pressure_air/100.,0.08); } else { std::cout << "Error: author not implemented." << std::endl << "Error in get_sky_emissivity." << std::endl; throw 100; } return (sky_emissivity); } double SurfaceCoefficients:: Clasius_Clapeyron_saturated_vapour_pressure(const double temperature) { /* * Clausius-Clapeyron equation * Relates equilibrium or saturation vapor pressure and temperature to the * latent heat of the phase change, without requiring specific volume data */ return(611.* exp((water_latent_heat_of_vaporization*molar_mass_water/gas_constant)*//[Pa] ((1./273.15)-(1./(temperature+273.15))))); } double SurfaceCoefficients:: Philip_1957_surface_vapour_pressure(const double surface_temperature) { double vapour_pressure_saturation_surface= Clasius_Clapeyron_saturated_vapour_pressure(surface_temperature); double vapour_pressure_surface= vapour_pressure_saturation_surface* exp(surface_water_tension*molar_mass_water*gravity_constant /(gas_constant*(surface_temperature+273.15)));//(Pa) return (vapour_pressure_surface); } double SurfaceCoefficients:: vapour_pressure_surface_new_estimate(const double old_surface_temperature, const double new_surface_temperature) { double old_vapour_pressure_surface= Philip_1957_surface_vapour_pressure(old_surface_temperature); double constant_1= (surface_water_tension*molar_mass_water*gravity_constant/gas_constant) -(water_latent_heat_of_vaporization*molar_mass_water/gas_constant);//[K] double average_temperature= 0.5*old_surface_temperature+0.5*new_surface_temperature; double old_vapur_pressure_surface_derivative= -1.*Philip_1957_surface_vapour_pressure(average_temperature) *(constant_1/((average_temperature+273.15)*(average_temperature+273.15))); return (old_vapour_pressure_surface + (old_vapur_pressure_surface_derivative *(new_surface_temperature-old_surface_temperature))); } // double SurfaceCoefficients:: // linear_inbound_evaporative_flux (const std::string surface_type, // const std::string author, // const double new_air_temperature, // const double new_relative_humidity, // const double new_wind_speed, // const double old_surface_temperature) // { // double inbound_evaporative_coefficient; // if (author=="Jansson") // { // inbound_evaporative_coefficient = // get_evaporative_coefficient_Jansson (surface_type, // new_wind_speed); // } // else if (author=="Herb") // { // inbound_evaporative_coefficient = // get_evaporative_coefficient_Herb (surface_type, // new_air_temperature, // new_relative_humidity, // new_wind_speed, // old_surface_temperature); // } // else if (author=="Best") // { // inbound_evaporative_coefficient = // get_evaporative_coefficient_Herb (surface_type, // new_air_temperature, // new_relative_humidity, // new_wind_speed, // old_surface_temperature); // } // else // { // std::cout << "Error in linear_inbound_evaporative_flux\n" // << "Author not implemented\n"; // } // double vapor_pressure_air = // (new_relative_humidity / 100.) // * Clasius_Clapeyron_saturated_vapour_pressure (new_air_temperature) ; // [Pa] // double vapor_pressure_surface // = Philip_1957_surface_vapour_pressure (old_surface_temperature); // double constant_1 // = (surface_water_tension*molar_mass_water*gravity_constant/gas_constant) // + (water_latent_heat_of_vaporization*molar_mass_water/gas_constant); // [K] // return (inbound_evaporative_coefficient*vapor_pressure_air // - (inbound_evaporative_coefficient*vapor_pressure_surface* // (1.-(constant_1*old_surface_temperature // /((old_surface_temperature+273.15)*(old_surface_temperature+273.15)))))); // } // double SurfaceCoefficients:: // linear_outbound_evaporative_coefficient (const std::string surface_type, // const std::string author, // const double new_air_temperature, // const double new_relative_humidity, // const double new_wind_speed, // const double old_surface_temperature) // { // double inbound_evaporative_coefficient; // if (author=="Jansson") // { // inbound_evaporative_coefficient = // get_evaporative_coefficient_Jansson (surface_type, // new_wind_speed); // } // else if (author=="Herb") // { // inbound_evaporative_coefficient = // get_evaporative_coefficient_Herb (surface_type, // new_air_temperature, // new_relative_humidity, // new_wind_speed, // old_surface_temperature); // } // else if (author=="Best") // { // inbound_evaporative_coefficient = // get_evaporative_coefficient_Herb (surface_type, // new_air_temperature, // new_relative_humidity, // new_wind_speed, // old_surface_temperature); // } // else // { // std::cout << "Error in linear_inbound_evaporative_flux\n" // << "Author not implemented\n"; // } // double vapor_pressure_surface // = Philip_1957_surface_vapour_pressure (old_surface_temperature); // double constant_1 // = (surface_water_tension*molar_mass_water*gravity_constant/gas_constant) // + (water_latent_heat_of_vaporization*molar_mass_water/gas_constant); // [K] // return (inbound_evaporative_coefficient*constant_1*vapor_pressure_surface // /((old_surface_temperature+273.15)*(old_surface_temperature+273.15))); // } /*********************************************************************************/ /*************** ***************/ /*************** Jansson et al. (2006) Surface Coefficients ***************/ /*************** ***************/ /*********************************************************************************/ double SurfaceCoefficients:: get_absortivity_Jansson(const std::string surface) { double coefficient=0; if (surface=="road") coefficient=absortivity_road_Jansson; else if (surface=="soil") coefficient=absortivity_soil_Jansson; else { std::cout << "Error: surface not implemented." << std::endl << "Error in get_absortivity_Jansson." << std::endl; throw 3; } return(coefficient); } double SurfaceCoefficients:: get_infrared_inbound_coefficient_Jansson(const std::string surface_type, const double air_temperature, // (C) const double relative_humidity) // (%) { double sky_emissivity =get_sky_emissivity ("jansson", air_temperature, relative_humidity); double surface_emissivity=0.; if (surface_type=="road") surface_emissivity=emissivity_road_Jansson; else if (surface_type=="soil") surface_emissivity=emissivity_soil_Jansson; else { std::cout << "Error: surface not implemented." << std::endl << "Error in get_infrared_inbound_coefficient_Jansson." << std::endl; throw 3; } return (steffan_boltzmann*sky_emissivity*surface_emissivity); // (W/m2K4) } double SurfaceCoefficients:: get_infrared_outbound_coefficient_Jansson(const std::string surface_type) { double surface_emissivity=0.; if (surface_type=="road") surface_emissivity=emissivity_road_Jansson; else if (surface_type=="soil") surface_emissivity=emissivity_soil_Jansson; else { std::cout << "Error: surface not implemented." << std::endl << "Error in get_infrared_outbound_coefficient_Jansson." << std::endl; throw 3; } return (steffan_boltzmann*surface_emissivity); // (W/m2K4) } double SurfaceCoefficients:: get_convective_coefficient_Jansson(const std::string surface_type, const double wind_speed) { double resistance=0; if (surface_type=="road") resistance = ((1./(pow(von_karman,2)*wind_speed)) * log10(z_ref_wind/z_road_momentum_roughness) * log10(z_ref_temperature/z_road_heat_roughness)); else if (surface_type=="soil") resistance = ((1./(pow(von_karman,2)*wind_speed)) * log10(z_ref_wind/z_soil_momentum_roughness) * log10(z_ref_temperature/z_soil_heat_roughness)); else { std::cout << "Error: surface not implemented." << std::endl << "Error in get_convective_coefficient." << std::endl; throw 3; } return(air_density*air_specific_heat_capacity/resistance); } double SurfaceCoefficients:: get_evaporative_coefficient_Jansson(const std::string surface_type, const double wind_speed) { /* The evaporative coeffiecient in Jansson's formulation (turbulent formulation) is identical to the convective coefficient divided by the psychrometric constant */ return (get_convective_coefficient_Jansson(surface_type, wind_speed)/psychrometric_constant); } double SurfaceCoefficients:: get_evaporative_flux_Jansson(const std::string surface_type, const double air_temperature , const double relative_humidity, const double wind_speed , double old_surface_temperature, double new_surface_temperature, const bool new_estimate) { if (moisture_movement==false) { old_surface_temperature=10.9; new_surface_temperature=10.9; } if (surface_type=="soil") { /* The equations used for (Jansson et al 2006) for evaporation from a bare soil assume a saturated soil. This is the same assumption as in the equations used by (Herb et al 2008). This equation does not include a term to take into account the contribution of natural convection. For this reason, for low wind speeds (more usual that one would expect according to the experimental data) the convective and evaporative heat fluxes are negligible, and this in turn bring the soil to very high temperatures. However, the advantage of this formulation is that it has been modified by (Philip et al 1957) to be applied to soils by including a 'soil moisture availability factor' From thermodynamics laws Philip (1957) dereive an expression for the relative humidity of air in equilibrium with the water in the soil pore. A prerequisite for the equation to be valid is that the air close to the pore water surface is in equilibrium with the pore water. However, in a drying soil, where vapor is continously transported to the atmosphere, the vapor pressure of air adjacent to the evaporating water surface will not be in equilibrium with the liquid water in the pore, i.e. the calculated relative humidity won't be representative at the soil surface. */ double vapour_pressure_surface=0.; if (new_estimate==false) vapour_pressure_surface =Philip_1957_surface_vapour_pressure (old_surface_temperature); else vapour_pressure_surface =vapour_pressure_surface_new_estimate (old_surface_temperature, new_surface_temperature); /* An obvious drawback of this formulation is that we need to know the surface water tension at the surface (or near the surface) in order ot use it and unless we have experimental measurements or we are dealing with a fully coupled heat-moisture diffusion model, it might prove to be difficult to give a reasonable number and even more difficult to propose its variation in time. */ double evaporative_coefficient =get_evaporative_coefficient_Jansson(surface_type, wind_speed); double vapour_pressure_air =(relative_humidity/100.) * Clasius_Clapeyron_saturated_vapour_pressure (air_temperature) ; // (Pa) return(evaporative_coefficient *(vapour_pressure_air-vapour_pressure_surface)); // (W/m2) } else if (surface_type=="road") { /* Assumption: No evaporation from the pavement surface. This means that we are considering it as a nonporous surface. In principle, if there is rainfall, the surface will get wet and some evaporation will occur. So, we are also assuming that the rainfall events are scarce. This assumption, however, might be wrong as, in my experience, heavy rainfalls in the uk are uncommon, drizle is a lot more usual. */ return 0.; // (W/m2) } else { std::cout << "Error: surface not implemented." << std::endl << "Error in get_evaporative." << std::endl; throw 3; return -1; } } double SurfaceCoefficients:: get_evaporative_mass_flux_Jansson(const std::string surface_type, const double air_temperature , const double relative_humidity, const double wind_speed , const double old_surface_temperature, const double new_surface_temperature, const bool new_estimate) { return ((1./(/*air_density*/water_latent_heat_of_vaporization))* get_evaporative_flux_Jansson (surface_type,air_temperature, relative_humidity,wind_speed, old_surface_temperature,new_surface_temperature, new_estimate)); } /******************************************************************************************************/ /*********************** ***************************/ /*********************** Herb et al. (2008) Surface Coefficients ***************************/ /*********************** ***************************/ /******************************************************************************************************/ double SurfaceCoefficients:: get_absortivity_Herb(const std::string surface) { double coefficient=0; if (surface=="road") coefficient=absortivity_road_Herb; else if (surface=="soil") coefficient=absortivity_soil_Herb; else if (surface=="snow") coefficient=absortivity_snow; else { std::cout << "Error: surface not implemented." << std::endl << "Error in get_absortivity_Herb." << std::endl; throw 3; } return coefficient; } double SurfaceCoefficients:: get_infrared_inbound_coefficient_Herb(const std::string surface_type, const double air_temperature, // (C) const double relative_humidity) // (%) { double sky_emissivity =get_sky_emissivity ("Herb", air_temperature, relative_humidity); double surface_emissivity=0.; if (surface_type=="road") surface_emissivity=emissivity_road_Herb; else if (surface_type=="soil") surface_emissivity=emissivity_soil_Herb; else { std::cout << "Error: surface not implemented." << std::endl << "Error in get_infrared_coefficient_Herb." << std::endl; throw 3; } return(steffan_boltzmann*sky_emissivity*surface_emissivity); // (W/m2K4) } double SurfaceCoefficients:: get_infrared_outbound_coefficient_Herb(const std::string surface_type) { double surface_emissivity=0.; if (surface_type=="road") surface_emissivity=emissivity_road_Herb; else if (surface_type=="soil") surface_emissivity=emissivity_soil_Herb; else if (surface_type=="snow") surface_emissivity=emissivity_snow; else { std::cout << "Error: surface not implemented." << std::endl << "Error in get_infrared_outbound_coefficient_Herb." << std::endl; throw 3; } return (steffan_boltzmann*surface_emissivity);//[W/m2K4] } double SurfaceCoefficients:: get_convective_coefficient_Herb(/*const std::string surface_type,*/ const double air_temperature, // (C) const double relative_humidity, // (%) const double wind_speed, // (m/s) const double old_surface_temperature, // (C) const double new_surface_temperature, // (C) const bool new_estimate) { /* "The advantage of this formulation is that both mechanical induced turbulence and atmospheric convective transport are included" [Henderson 1981, "Modelling evaporation from reservoirs"] ... The main assumption in this formulation is that the air near the surface (soil or water reservoir) is saturated at all times. However: ... "When an early saturated soil dries, the free water in larger pores evaporates first. The remaining water is retained mainly in smaller soil pores by strong capillary forces, and the vapour pressure of the air in equilibrium with the pore water will therefore be lower than in the air close to a free water surface" [Alvenas and Janssen 1997, "Model for evaporation, moisture and temperature"] ... This means that the assumption of a soil saturated at all times should be revised if we are in weather conditions that are likely to dry the soil. For the road case the situation is different. We assume the road surface is dry except when a rain event occurs. This should be decided by the function calling this member. Clausius-Clapeyron equation Relates equilibrium or saturation vapour pressure and temperature to the latent heat of the phase change, without requiring specific volume data */ /* the 'old_surface_temperature' passed to this function is assumed to be an 'anchor temperature', this is, a temperature around which we expect the surface temperature to be around. */ double vapour_pressure_surface=0.; double mixing_ratio_surface=0.; double virtual_surface_temperature=0.; double surface_temperature=//[K] 0.5*new_surface_temperature+0.5*old_surface_temperature; if (new_estimate==false) { vapour_pressure_surface= Philip_1957_surface_vapour_pressure(surface_temperature); mixing_ratio_surface= (molar_mass_water/molar_mass_air)* vapour_pressure_surface/atmospheric_pressure;//[Pa/Pa] virtual_surface_temperature= (1.+0.6*mixing_ratio_surface)*(surface_temperature+273.15);//[K] } else { vapour_pressure_surface= vapour_pressure_surface_new_estimate(surface_temperature, surface_temperature); mixing_ratio_surface= (molar_mass_water/molar_mass_air) *vapour_pressure_surface/atmospheric_pressure;//[Pa/Pa] virtual_surface_temperature= (1.+0.6*mixing_ratio_surface)*(surface_temperature+273.15);//[K] } double saturated_vapour_pressure_air= Clasius_Clapeyron_saturated_vapour_pressure(air_temperature); double mixing_ratio_air= ((relative_humidity/100.)* (molar_mass_water/molar_mass_air) *saturated_vapour_pressure_air/atmospheric_pressure);//[Pa/Pa] double virtual_air_temperature= (1.+0.6*mixing_ratio_air)*(air_temperature+273.15);//[K] /* Ryan et al. equation for flux evaporation includes a term for natural convection. This term is proportional to the difference in virtual temperatures between the surface and air. This term is raised to a fractional power (1/3). For negative numbers (i.e. when the virtual temperature of the air is higher than the virtual temperature of the surface) would need the computation of complex numbers. However for that case, it doesn't make sense to include the term for natural convection because it would correspond to a stable temperature profile that prevents natural convection. In this case, I simply set to zero this term in order to neglect its contribution. */ double virtual_temperature_difference=0.; if (virtual_surface_temperature>virtual_air_temperature) virtual_temperature_difference =virtual_surface_temperature-virtual_air_temperature; else virtual_temperature_difference=0.; /* Specific humidity (q) is the number of grams of water vapour per unit mass of air plus water vapour. In applications, q is numerically close enough to the mixing ratio that one seldom needs to distinguish between them. [North and Erukhimova 2009, "Atmospheric Thermodynamics Elementary Physics and Chemistry" */ return (air_density*air_specific_heat_capacity *(coefficient_forced_convection*coefficient_sheltering*wind_speed + coefficient_natural_convection*pow(virtual_temperature_difference,1./3.))); // (W/m^2K) } double SurfaceCoefficients:: get_evaporative_coefficient_Herb(/*const std::string surface_type,*/ const double air_temperature, // (C) const double relative_humidity, // (%) const double wind_speed, // (m/s) const double old_surface_temperature, // (C) const double new_surface_temperature, // (C) const bool new_estimate) // (C) { /* The evaporative coeffiecient in Herb's and Best's formulations (non-turbulent formulations) is identical to the convective coefficient except that the convective coefficient is multiplied by the air's specific heat capacity while the evaporative coefficient is multiplied by the water's latent heat of vaporization */ return ((water_latent_heat_of_vaporization/air_specific_heat_capacity) *get_convective_coefficient_Herb(/*surface_type,*/air_temperature, relative_humidity,wind_speed, old_surface_temperature, new_surface_temperature, new_estimate) *((molar_mass_water/molar_mass_air)/atmospheric_pressure)); } double SurfaceCoefficients:: get_evaporative_flux_Herb(const double air_temperature, // (C) const double relative_humidity,// (%) const double wind_speed, // (m/s) double old_surface_temperature,// (C) double new_surface_temperature,// (C) const bool new_estimate)// (C) { /* the 'old_surface_temperature' passed to this function is assumed to be an 'anchor temperature', this is, a temperature around which we expect the surface temperature to be around. */ double surface_temperature=//[K] 0.5*new_surface_temperature+0.5*old_surface_temperature; double vapour_pressure_surface=0.; if (new_estimate==false) vapour_pressure_surface= Philip_1957_surface_vapour_pressure(surface_temperature); else vapour_pressure_surface= vapour_pressure_surface_new_estimate(surface_temperature, surface_temperature); double vapour_pressure_air= (relative_humidity/100.) *Clasius_Clapeyron_saturated_vapour_pressure(air_temperature) ;//[Pa] return(get_evaporative_coefficient_Herb(/*surface_type,*/air_temperature, relative_humidity,wind_speed, old_surface_temperature, new_surface_temperature, new_estimate) *(vapour_pressure_air-vapour_pressure_surface));//[W/m^2] } double SurfaceCoefficients:: get_evaporative_mass_flux_Herb(/*const std::string surface_type,*/ const double air_temperature, // (C) const double relative_humidity, // (%) const double wind_speed, // (m/s) const double old_surface_temperature, // (C) const double new_surface_temperature, // (C) const bool new_estimate) // (C) { return ((1./(water_latent_heat_of_vaporization/*/air_specific_heat_capacity*/))* get_evaporative_flux_Herb(/*surface_type,*/air_temperature, relative_humidity,wind_speed, old_surface_temperature,new_surface_temperature, new_estimate)); } /******************************************************************************************************/ /************************** *************************/ /************************** Best et al. (2008) Surface Coefficients *************************/ /************************** *************************/ /******************************************************************************************************/ double SurfaceCoefficients:: get_absortivity_Best (const std::string surface) { double coefficient=0; if (surface=="road") coefficient=absortivity_road_Best; else if (surface=="soil") coefficient=absortivity_soil_Best; else { std::cout << "Error: surface not implemented." << std::endl << "Error in get_absortivity_Best." << std::endl; throw 3; } return coefficient; } double SurfaceCoefficients:: get_infrared_inbound_coefficient_Best(const std::string surface_type, const double air_temperature, const double relative_humidity) { double sky_emissivity = get_sky_emissivity ("Best", air_temperature, relative_humidity); double surface_emissivity = 0.; if (surface_type == "road") surface_emissivity = emissivity_road_Best; else if (surface_type == "soil") surface_emissivity = emissivity_soil_Best; else if (surface_type == "canopy") surface_emissivity = emissivity_canopy_Best; else { std::cout << "Error: surface not implemented." << std::endl << "Error in get_infrared_coefficient_Best." << std::endl; throw 3; } return (steffan_boltzmann*sky_emissivity*surface_emissivity); // (W/m2K4) } double SurfaceCoefficients:: get_infrared_outbound_coefficient_Best(const std::string surface_type) { double surface_emissivity = 0.; if (surface_type == "road") surface_emissivity = emissivity_road_Best; else if (surface_type == "soil") surface_emissivity = emissivity_soil_Best; else if (surface_type == "canopy") surface_emissivity = emissivity_canopy_Best; else { std::cout << "Error: surface not implemented." << std::endl << "Error in get_infrared_outbound_coefficient_Best." << std::endl; throw 3; } return (steffan_boltzmann*surface_emissivity); // (W/m2K4) } double SurfaceCoefficients:: get_convective_coefficient_Best(const double air_temperature, // (C) const double relative_humidity, // (%) const double wind_speed, // (m/s) const double old_surface_temperature, // (C) const double new_surface_temperature, // (C) const bool new_estimate) { /* The convective coeffiecients in Herb's and Best's formulations (non-turbulent formulations) are identical, so there is no necessity to repeat code here, just call Herb's convective coefficient function */ return (get_convective_coefficient_Herb(air_temperature, relative_humidity,wind_speed, old_surface_temperature, new_surface_temperature, new_estimate)); } double SurfaceCoefficients:: get_evaporative_coefficient_Best(const double air_temperature, // (C) const double relative_humidity, // (%) const double wind_speed, // (m/s) const double old_surface_temperature, // (C) const double new_surface_temperature, // (C) const bool new_estimate) { /* The evaporative coeffiecients in Herb's and Best's formulations (non-turbulent formulations) are identical, so there is no necessity to repeat code here, just call Herb's evaporative coefficient function */ return (get_evaporative_coefficient_Herb(air_temperature, relative_humidity,wind_speed, old_surface_temperature, new_surface_temperature, new_estimate)); } double SurfaceCoefficients:: get_evaporative_flux_Best(const double air_temperature, // (C) const double relative_humidity, // (%) const double wind_speed, // (m/s) double old_surface_temperature, // (C) double new_surface_temperature, // (C) const bool new_estimate) // (C) { /* the 'old_surface_temperature' passed to this function is assumed to be an 'anchor temperature', this is, a temperature around which we expect the surface temperature to be around. */ double surface_temperature=//[K] 0.5*new_surface_temperature+0.5*old_surface_temperature; double vapour_pressure_surface=0.; if (new_estimate==false) vapour_pressure_surface= Philip_1957_surface_vapour_pressure(surface_temperature); else vapour_pressure_surface= vapour_pressure_surface_new_estimate(surface_temperature, surface_temperature); double vapour_pressure_air= (relative_humidity/100.) *Clasius_Clapeyron_saturated_vapour_pressure(air_temperature);//[Pa] return(get_evaporative_coefficient_Best(air_temperature, relative_humidity,wind_speed, old_surface_temperature, new_surface_temperature, new_estimate) *(vapour_pressure_air-vapour_pressure_surface));//[W/m^2] } double SurfaceCoefficients:: get_convective_coefficient_canopy_Best(const double wind_speed)//(m/s) { return (0.01*(wind_speed+0.3)*air_density*air_specific_heat_capacity); // (W/m^2K) } double SurfaceCoefficients:: get_evaporative_flux_canopy_Best(const double air_temperature, // (C) const double relative_humidity, // (%) const double wind_speed, // (m/s) const double solar_radiation, // (W/m2) const double surface_temperature, // (C) const bool derivative) { double maximum_solar_radiation = 1000.; double moisture_content = 0.24; double wilting_point = 0.5*moisture_content; double stomata_resistance = 200.*(maximum_solar_radiation/(solar_radiation+0.3*maximum_solar_radiation) + pow(wilting_point/moisture_content,2)); double saturated_vapor_partial_pressure_surface=0.; // if (moisture_movement==true) saturated_vapor_partial_pressure_surface =Clasius_Clapeyron_saturated_vapour_pressure(surface_temperature); // else // saturated_vapor_partial_pressure_surface // =Clasius_Clapeyron_saturated_vapour_pressure(/*surface_temperature*/10.9); double saturated_vapor_partial_pressure_air = Clasius_Clapeyron_saturated_vapour_pressure (air_temperature); double mixing_ratio_surface = (molar_mass_water/molar_mass_air) * saturated_vapor_partial_pressure_surface/atmospheric_pressure; // (Pa/Pa) double mixing_ratio_air = ((relative_humidity/100.) * (molar_mass_water/molar_mass_air) * saturated_vapor_partial_pressure_air/atmospheric_pressure); // (Pa/Pa) if (derivative == false) return (air_density * water_latent_heat_of_vaporization * (0.01*(wind_speed+0.3)/(1.+stomata_resistance*0.01*(wind_speed+0.3))) * (mixing_ratio_air - mixing_ratio_surface) ); // (W/m^2) else return(-1. * air_density * water_latent_heat_of_vaporization * (0.01*(wind_speed+0.3)/(1.+stomata_resistance*0.01*(wind_speed+0.3))) * mixing_ratio_surface * ((water_latent_heat_of_vaporization*molar_mass_water/gas_constant) /pow(surface_temperature+273.15,2))); } double SurfaceCoefficients:: get_evaporative_mass_flux_Best(const double air_temperature, // (C) const double relative_humidity, // (%) const double wind_speed, // (m/s) const double old_surface_temperature, // (C) const double new_surface_temperature, // (C) const bool new_estimate) // (C) { return ((1./(water_latent_heat_of_vaporization/*/air_specific_heat_capacity*/))* get_evaporative_flux_Best(/*surface_type,*/air_temperature, relative_humidity,wind_speed, old_surface_temperature,new_surface_temperature, new_estimate)); }
gpl-3.0
jjiangweilan/TileMap_Outline_Generator
ContourGenerator.cpp
1
7303
// // ContourGenerator.cpp // MarioGame // // Created by jiehong jiang on 5/31/17. // // #include "ContourGenerator.hpp" #include "cocos2d.h" #include <vector> #include <algorithm> #include <set> USING_NS_CC; #define CREATE_CONNECTED_LINES(_axis) \ for (Line l : lines){ \ if (l.p1._axis == l.p2._axis && l.p1._axis == para){ \ result.insert(l); \ } \ } #define GET_CONTOUR_FOR(_axis, _max) \ for (int i = 0; i <= _max; i++) { \ std::set<Line, LineComp> cALines = getLine(i, _axis); \ for (std::set<Line, LineComp>::iterator iter = cALines.begin(); iter != cALines.end();iter++){ \ std::set<Line, LineComp>::iterator next = ++iter;--iter; \ Line c(iter->p1, iter->p2); \ for(;next != cALines.end();next++,iter++){ \ if (next->p1 == c.p2) { \ c.p2 = next->p2; \ } \ else break; \ } \ group.push_back(c); \ } \ } \ bool LineComp::operator()(const Line &l1, const Line &l2) const{ if(l1.p1.x != l2.p2.x){ return l1.p1.x < l2.p2.x; } else{ return l1.p1.y < l2.p2.y; } } std::vector<Line> ContourGenerator::getContour(){ std::vector<Line> group; Size size = targetLayer->getLayerSize(); GET_CONTOUR_FOR('x', size.width); GET_CONTOUR_FOR('y', size.height); return group; } std::set<Line, LineComp> ContourGenerator::getLine(int para, char axis){ std::set<Line, LineComp> result; if (axis == 'x'){ CREATE_CONNECTED_LINES(x); //connct edges in this axis. } else if (axis == 'y'){ CREATE_CONNECTED_LINES(y); } return result; } ContourGenerator::ContourGenerator(cocos2d::TMXLayer* layer){ targetLayer = layer; Size size = layer->getLayerSize(); for (int c = 0; c < size.width; c++) { for (int r = 0; r < size.height; r++) { auto tile = layer->getTileAt(Vec2(c, r)); //this is the start point of one contour if (tile != NULL && tile->getUserData() == NULL){ std::set<Vec2> coordinates = MooreNeighbor::mooreNeighbor(Vec2(c, r), layer); populateLines(coordinates); } } } } bool ContourGenerator::add(Line edge){ //find out whether the line is a overlapped edge std::vector<Line>::iterator iter = std::find_if(lines.begin(), lines.end(), [&] (const Line &l) -> bool { return ((l.p1 == edge.p1 && l.p2 == edge.p2) || (l.p1 == edge.p2 && l.p2 == edge.p1)); }); //if the line is overlapped delete the same line in the lines //if two edges are overlapped, it means there is no need to create the physicsbody for it. if (iter != lines.end()){ lines.erase(iter); return false; } lines.push_back(edge); return true; } void ContourGenerator::populateLines(const std::set<cocos2d::Vec2>& coordinates){ for(cocos2d::Vec2 x1 : coordinates){ cocos2d::Vec2 x2 = x1 + cocos2d::Vec2(1, 0); cocos2d::Vec2 x3 = x1 + cocos2d::Vec2(0, 1); cocos2d::Vec2 x4 = x1 + cocos2d::Vec2(1, 1); Line l(x1, x2); add(l); l = Line(x1, x3); add(l); l = Line(x3, x4); add(l); l = Line(x2, x4); add(l); } } namespace NEIGHBOR { const Vec2 LEFT = Vec2(-1, 0); //1 const Vec2 TOP_LEFT = Vec2(-1, -1); //2 const Vec2 BOTTOM_LEFT = Vec2(-1, 1); //3 const Vec2 TOP = Vec2(0, -1); //4 const Vec2 BOTTOM = Vec2(0, 1); const Vec2 TOP_RIGHT = Vec2(1, -1); const Vec2 RIGHT = Vec2(1, 0); const Vec2 BOTTOM_RIGHT = Vec2(1, 1); } cocos2d::Vec2 ContourGenerator::MooreNeighbor::ClockWiseTravel::current = Vec2(-1,-1); int ContourGenerator::MooreNeighbor::ClockWiseTravel::travelTime = 0; cocos2d::Vec2 ContourGenerator::MooreNeighbor::ClockWiseTravel::origin = Vec2(-1,-1); cocos2d::Vec2 ContourGenerator::MooreNeighbor::enter = Vec2(-1, -1); bool ContourGenerator::MooreNeighbor::ClockWiseTravel::firstTravel = true; std::set<Vec2> ContourGenerator::MooreNeighbor::mooreNeighbor(cocos2d::Vec2 cCoordinate, cocos2d::TMXLayer* layer){ std::set<Vec2> neighborSet; if(layer->getTileAt(cCoordinate) == NULL) return neighborSet; enter = cCoordinate; ClockWiseTravel::firstTravel = false; //to handle special case ClockWiseTravel::current = cCoordinate + NEIGHBOR::LEFT; travel(cCoordinate, neighborSet, layer); return neighborSet; } void ContourGenerator::MooreNeighbor::travel(Vec2 cCoordinate,std::set<Vec2>& counterCoordinates, TMXLayer* layer) { //base case actual test: cCoordinate == enter //this termination method needs improvement ClockWiseTravel::origin = cCoordinate; ClockWiseTravel::travelTime = 1; if(cCoordinate == enter && ClockWiseTravel::current == ClockWiseTravel::origin + NEIGHBOR::LEFT && !counterCoordinates.empty()){ return; } counterCoordinates.insert(cCoordinate); layer->getTileAt(cCoordinate)->setUserData(&TileChecked::check); while (ClockWiseTravel::travel()) { if (ClockWiseTravel::origin == enter && ClockWiseTravel::current == enter + NEIGHBOR::TOP_LEFT && ClockWiseTravel::firstTravel == false) return; ClockWiseTravel::firstTravel = false; if(ClockWiseTravel::current.x < 0 || ClockWiseTravel::current.y < 0 || ClockWiseTravel::current.x >= layer->getLayerSize().width || ClockWiseTravel::current.y >= layer->getLayerSize().height)continue; if (layer->getTileAt(ClockWiseTravel::current) != NULL){ cCoordinate = ClockWiseTravel::current; ClockWiseTravel::traceBack(); travel(cCoordinate, counterCoordinates, layer); break; } } } void ContourGenerator::MooreNeighbor::ClockWiseTravel::traceBack(){ if (current == (origin + NEIGHBOR::LEFT)) current += NEIGHBOR::BOTTOM; else if (current == (origin + NEIGHBOR::TOP_LEFT)) current += NEIGHBOR::BOTTOM; else if (current == (origin + NEIGHBOR::TOP)) current += NEIGHBOR::LEFT; else if (current == (origin + NEIGHBOR::TOP_RIGHT)) current += NEIGHBOR::LEFT; else if (current == (origin + NEIGHBOR::RIGHT)) current += NEIGHBOR::TOP; else if (current == (origin + NEIGHBOR::BOTTOM_RIGHT)) current += NEIGHBOR::TOP; else if (current == (origin + NEIGHBOR::BOTTOM)) current += NEIGHBOR::RIGHT; else if (current == (origin + NEIGHBOR::BOTTOM_LEFT)) current += NEIGHBOR::RIGHT; } bool ContourGenerator::MooreNeighbor::ClockWiseTravel::travel(){ if (travelTime == 9)return false; if (current == (origin + NEIGHBOR::LEFT)) current += NEIGHBOR::TOP; else if (current == (origin + NEIGHBOR::TOP_LEFT)) current += NEIGHBOR::RIGHT; else if (current == (origin + NEIGHBOR::TOP)) current += NEIGHBOR::RIGHT; else if (current == (origin + NEIGHBOR::TOP_RIGHT)) current += NEIGHBOR::BOTTOM; else if (current == (origin + NEIGHBOR::RIGHT)) current += NEIGHBOR::BOTTOM; else if (current == (origin + NEIGHBOR::BOTTOM_RIGHT)) current += NEIGHBOR::LEFT; else if (current == (origin + NEIGHBOR::BOTTOM)) current += NEIGHBOR::LEFT; else if (current == (origin + NEIGHBOR::BOTTOM_LEFT)) current += NEIGHBOR::TOP; ++travelTime; return true; } bool TileChecked::check = false;
gpl-3.0
luebbers/reconos
core/ecos/ecos-patched/ecos/packages/devs/eth/powerpc/adder/current/src/adder_eth.c
1
8946
//========================================================================== // // adder_eth.c // // Ethernet device driver specifics for Analogue & Micro Adder (PPC850) // //========================================================================== //####ECOSGPLCOPYRIGHTBEGIN#### // ------------------------------------------- // This file is part of eCos, the Embedded Configurable Operating System. // Copyright (C) 1998, 1999, 2000, 2001, 2002 Red Hat, Inc. // Copyright (C) 2002 Gary Thomas // // eCos 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. // // eCos 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 eCos; if not, write to the Free Software Foundation, Inc., // 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. // // As a special exception, if other files instantiate templates or use macros // or inline functions from this file, or you compile this file and link it // with other works to produce a work based on this file, this file does not // by itself cause the resulting work to be covered by the GNU General Public // License. However the source code for this file must still be made available // in accordance with section (3) of the GNU General Public License. // // This exception does not invalidate any other reasons why a work based on // this file might be covered by the GNU General Public License. // // Alternative licenses for eCos may be arranged by contacting Red Hat, Inc. // at http://sources.redhat.com/ecos/ecos-license/ // ------------------------------------------- //####ECOSGPLCOPYRIGHTEND#### //####BSDCOPYRIGHTBEGIN#### // // ------------------------------------------- // // Portions of this software may have been derived from OpenBSD or other sources, // and are covered by the appropriate copyright disclaimers included herein. // // ------------------------------------------- // //####BSDCOPYRIGHTEND#### //========================================================================== //#####DESCRIPTIONBEGIN#### // // Author(s): gthomas // Contributors: gthomas // Date: 2002-11-25 // Purpose: // Description: platform driver specifics for A&M Adder // // //####DESCRIPTIONEND#### // //========================================================================== // Ethernet device driver support for PHY on Adder/MPC850 #include <pkgconf/system.h> #include <cyg/infra/cyg_type.h> #include <cyg/infra/diag.h> #include <cyg/hal/hal_arch.h> #include <cyg/hal/hal_cache.h> #include <cyg/hal/hal_if.h> #include <cyg/hal/drv_api.h> #include CYGDAT_DEVS_QUICC_ETH_INL // Platform specifics #include <cyg/hal/quicc/ppc8xx.h> // QUICC structure definitions // MII interface #define MII_Start 0x40000000 #define MII_Read 0x20000000 #define MII_Write 0x10000000 #define MII_Cmd 0x30000000 #define MII_Phy(phy) (phy << 23) #define MII_Reg(reg) (reg << 18) #define MII_TA 0x00020000 // Transceiver mode #define PHY_BMCR 0x00 // Register number #define PHY_BMCR_RESET 0x8000 #define PHY_BMCR_LOOPBACK 0x4000 #define PHY_BMCR_100MB 0x2000 #define PHY_BMCR_AUTO_NEG 0x1000 #define PHY_BMCR_POWER_DOWN 0x0800 #define PHY_BMCR_ISOLATE 0x0400 #define PHY_BMCR_RESTART 0x0200 #define PHY_BMCR_FULL_DUPLEX 0x0100 #define PHY_BMCR_COLL_TEST 0x0080 #define PHY_BMSR 0x01 // Status register #define PHY_BMSR_AUTO_NEG 0x0020 #define PHY_BMSR_LINK 0x0004 // Bits in port D - used for 2 wire MII interface #define MII_DATA 0x1000 #define MII_CLOCK 0x0800 #define MII_SET_DATA(val) \ if (val) { \ eppc->pio_pddat |= MII_DATA; \ } else { \ eppc->pio_pddat &= ~MII_DATA; \ } #define MII_GET_DATA() \ ((eppc->pio_pddat & MII_DATA) != 0) #define MII_SET_CLOCK(val) \ if (val) { \ eppc->pio_pddat |= MII_CLOCK; \ } else { \ eppc->pio_pddat &= ~MII_CLOCK; \ } static cyg_uint32 phy_cmd(cyg_uint32 cmd) { volatile EPPC *eppc = (volatile EPPC *)eppc_base(); cyg_uint32 retval; int i, off; bool is_read = ((cmd & MII_Cmd) == MII_Read); // Set both bits as output eppc->pio_pddir |= MII_DATA | MII_CLOCK; // Preamble for (i = 0; i < 32; i++) { MII_SET_CLOCK(0); MII_SET_DATA(1); CYGACC_CALL_IF_DELAY_US(1); MII_SET_CLOCK(1); CYGACC_CALL_IF_DELAY_US(1); } // Command/data for (i = 0, off = 31; i < (is_read ? 14 : 32); i++, --off) { MII_SET_CLOCK(0); MII_SET_DATA((cmd >> off) & 0x00000001); CYGACC_CALL_IF_DELAY_US(1); MII_SET_CLOCK(1); CYGACC_CALL_IF_DELAY_US(1); } retval = cmd; // If read, fetch data register if (is_read) { retval >>= 16; MII_SET_CLOCK(0); eppc->pio_pddir &= ~MII_DATA; // Data bit is now input CYGACC_CALL_IF_DELAY_US(1); MII_SET_CLOCK(1); CYGACC_CALL_IF_DELAY_US(1); MII_SET_CLOCK(0); CYGACC_CALL_IF_DELAY_US(1); for (i = 0, off = 15; i < 16; i++, off--) { MII_SET_CLOCK(1); retval <<= 1; retval |= MII_GET_DATA(); CYGACC_CALL_IF_DELAY_US(1); MII_SET_CLOCK(0); CYGACC_CALL_IF_DELAY_US(1); } } // Set both bits as output eppc->pio_pddir |= MII_DATA | MII_CLOCK; // Postamble for (i = 0; i < 32; i++) { MII_SET_CLOCK(0); MII_SET_DATA(1); CYGACC_CALL_IF_DELAY_US(1); MII_SET_CLOCK(1); CYGACC_CALL_IF_DELAY_US(1); } return retval; } // // PHY unit access (via MII channel) // static void phy_write(int reg, int addr, unsigned short data) { phy_cmd(MII_Start | MII_Write | MII_Phy(addr) | MII_Reg(reg) | MII_TA | data); } static bool phy_read(int reg, int addr, unsigned short *val) { cyg_uint32 ret; ret = phy_cmd(MII_Start | MII_Read | MII_Phy(addr) | MII_Reg(reg) | MII_TA); *val = ret; return true; } bool _adder_reset_phy(void) { volatile EPPC *eppc = (volatile EPPC *)eppc_base(); int phy_timeout = 5*1000; // Wait 5 seconds max for link to clear bool phy_ok; unsigned short phy_state = 0; int phy_unit = -1; int i; // Reset PHY (transceiver) eppc->pip_pbdat &= ~0x00004000; // Reset PHY chip CYGACC_CALL_IF_DELAY_US(15000); // > 10ms eppc->pip_pbdat |= 0x00004000; // Enable PHY chip phy_ok = false; // Try and discover how this PHY is wired for (i = 0; i < 0x20; i++) { phy_read(PHY_BMCR, i, &phy_state); if ((phy_state & PHY_BMCR_RESET) == 0) { phy_unit = i; break; } } if (phy_unit < 0) { diag_printf("QUICC ETH - Can't locate PHY\n"); return false; } else { #if 0 diag_printf("QUICC ETH - using PHY %d\n", phy_unit); #endif } if (phy_read(PHY_BMSR, phy_unit, &phy_state)) { if ((phy_state & PHY_BMSR_LINK) != PHY_BMSR_LINK) { unsigned short reset_mode; phy_write(PHY_BMCR, phy_unit, PHY_BMCR_RESET); for (i = 0; i < 10; i++) { phy_ok = phy_read(PHY_BMCR, phy_unit, &phy_state); if (!phy_ok) break; if (!(phy_state & PHY_BMCR_RESET)) break; } if (!phy_ok || (phy_state & PHY_BMCR_RESET)) { diag_printf("QUICC/ETH: Can't get PHY unit to soft reset: %x\n", phy_state); return false; } reset_mode = PHY_BMCR_RESTART | PHY_BMCR_AUTO_NEG | PHY_BMCR_FULL_DUPLEX; phy_write(PHY_BMCR, phy_unit, reset_mode); while (phy_timeout-- >= 0) { phy_ok = phy_read(PHY_BMSR, phy_unit, &phy_state); if (phy_ok && (phy_state & PHY_BMSR_LINK)) { break; } else { CYGACC_CALL_IF_DELAY_US(10000); // 10ms } } if (phy_timeout <= 0) { diag_printf("** QUICC/ETH Warning: PHY LINK UP failed\n"); } } else { diag_printf("** QUICC/ETH Info: PHY LINK already UP \n"); } } return phy_ok; }
gpl-3.0
p01arst0rm/decorum-linux
_resources/kernels/xnu-arm/osfmk/i386/AT386/model_dep.c
1
37329
/* * Copyright (c) 2000-2010 Apple Computer, Inc. All rights reserved. * * @APPLE_OSREFERENCE_LICENSE_HEADER_START@ * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. The rights granted to you under the License * may not be used to create, or enable the creation or redistribution of, * unlawful or unlicensed copies of an Apple operating system, or to * circumvent, violate, or enable the circumvention or violation of, any * terms of an Apple operating system software license agreement. * * Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_OSREFERENCE_LICENSE_HEADER_END@ */ /* * @OSF_COPYRIGHT@ */ /* * Mach Operating System * Copyright (c) 1991,1990,1989, 1988 Carnegie Mellon University * All Rights Reserved. * * Permission to use, copy, modify and distribute this software and its * documentation is hereby granted, provided that both the copyright * notice and this permission notice appear in all copies of the * software, derivative works or modified versions, and any portions * thereof, and that both notices appear in supporting documentation. * * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS" * CONDITION. CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND FOR * ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE. * * Carnegie Mellon requests users of this software to return to * * Software Distribution Coordinator or Software.Distribution@CS.CMU.EDU * School of Computer Science * Carnegie Mellon University * Pittsburgh PA 15213-3890 * * any improvements or extensions that they make and grant Carnegie Mellon * the rights to redistribute these changes. */ /* */ /* * File: model_dep.c * Author: Avadis Tevanian, Jr., Michael Wayne Young * * Copyright (C) 1986, Avadis Tevanian, Jr., Michael Wayne Young * * Basic initialization for I386 - ISA bus machines. */ #include <platforms.h> #include <mach/i386/vm_param.h> #include <string.h> #include <mach/vm_param.h> #include <mach/vm_prot.h> #include <mach/machine.h> #include <mach/time_value.h> #include <kern/spl.h> #include <kern/assert.h> #include <kern/debug.h> #include <kern/misc_protos.h> #include <kern/startup.h> #include <kern/clock.h> #include <kern/cpu_data.h> #include <kern/machine.h> #include <i386/postcode.h> #include <i386/mp_desc.h> #include <i386/misc_protos.h> #include <i386/thread.h> #include <i386/trap.h> #include <i386/machine_routines.h> #include <i386/mp.h> /* mp_rendezvous_break_lock */ #include <i386/cpuid.h> #include <i386/fpu.h> #include <i386/machine_cpu.h> #include <i386/pmap.h> #if CONFIG_MTRR #include <i386/mtrr.h> #endif #include <i386/ucode.h> #include <i386/pmCPU.h> #include <architecture/i386/pio.h> /* inb() */ #include <pexpert/i386/boot.h> #include <vm/pmap.h> #include <vm/vm_map.h> #include <vm/vm_kern.h> #include <IOKit/IOPlatformExpert.h> #include <IOKit/IOHibernatePrivate.h> #include <pexpert/i386/efi.h> #include <kern/thread.h> #include <kern/sched.h> #include <mach-o/loader.h> #include <mach-o/nlist.h> #include <libkern/kernel_mach_header.h> #include <libkern/OSKextLibPrivate.h> #if DEBUG #define DPRINTF(x...) kprintf(x) #else #define DPRINTF(x...) #endif static void machine_conf(void); extern int max_unsafe_quanta; extern int max_poll_quanta; extern unsigned int panic_is_inited; int db_run_mode; volatile int pbtcpu = -1; hw_lock_data_t pbtlock; /* backtrace print lock */ uint32_t pbtcnt = 0; volatile int panic_double_fault_cpu = -1; #if defined (__i386__) #define PRINT_ARGS_FROM_STACK_FRAME 1 #elif defined (__x86_64__) #define PRINT_ARGS_FROM_STACK_FRAME 0 #else #error unsupported architecture #endif typedef struct _cframe_t { struct _cframe_t *prev; uintptr_t caller; #if PRINT_ARGS_FROM_STACK_FRAME unsigned args[0]; #endif } cframe_t; static unsigned panic_io_port; static unsigned commit_paniclog_to_nvram; unsigned int debug_boot_arg; void machine_startup(void) { int boot_arg; #if 0 if( PE_get_hotkey( kPEControlKey )) halt_in_debugger = halt_in_debugger ? 0 : 1; #endif if (PE_parse_boot_argn("debug", &debug_boot_arg, sizeof (debug_boot_arg))) { panicDebugging = TRUE; if (debug_boot_arg & DB_HALT) halt_in_debugger=1; if (debug_boot_arg & DB_PRT) disable_debug_output=FALSE; if (debug_boot_arg & DB_SLOG) systemLogDiags=TRUE; if (debug_boot_arg & DB_LOG_PI_SCRN) logPanicDataToScreen=TRUE; } else { debug_boot_arg = 0; } if (!PE_parse_boot_argn("nvram_paniclog", &commit_paniclog_to_nvram, sizeof (commit_paniclog_to_nvram))) commit_paniclog_to_nvram = 1; /* * Entering the debugger will put the CPUs into a "safe" * power mode. */ if (PE_parse_boot_argn("pmsafe_debug", &boot_arg, sizeof (boot_arg))) pmsafe_debug = boot_arg; #if NOTYET hw_lock_init(&debugger_lock); /* initialize debugger lock */ #endif hw_lock_init(&pbtlock); /* initialize print backtrace lock */ if (PE_parse_boot_argn("preempt", &boot_arg, sizeof (boot_arg))) { default_preemption_rate = boot_arg; } if (PE_parse_boot_argn("unsafe", &boot_arg, sizeof (boot_arg))) { max_unsafe_quanta = boot_arg; } if (PE_parse_boot_argn("poll", &boot_arg, sizeof (boot_arg))) { max_poll_quanta = boot_arg; } if (PE_parse_boot_argn("yield", &boot_arg, sizeof (boot_arg))) { sched_poll_yield_shift = boot_arg; } /* The I/O port to issue a read from, in the event of a panic. Useful for * triggering logic analyzers. */ if (PE_parse_boot_argn("panic_io_port", &boot_arg, sizeof (boot_arg))) { /*I/O ports range from 0 through 0xFFFF */ panic_io_port = boot_arg & 0xffff; } machine_conf(); /* * Start the system. */ kernel_bootstrap(); /*NOTREACHED*/ } static void machine_conf(void) { machine_info.memory_size = (typeof(machine_info.memory_size))mem_size; } extern void *gPEEFIRuntimeServices; extern void *gPEEFISystemTable; /*- * COPYRIGHT (C) 1986 Gary S. Brown. You may use this program, or * code or tables extracted from it, as desired without restriction. * * First, the polynomial itself and its table of feedback terms. The * polynomial is * X^32+X^26+X^23+X^22+X^16+X^12+X^11+X^10+X^8+X^7+X^5+X^4+X^2+X^1+X^0 * * Note that we take it "backwards" and put the highest-order term in * the lowest-order bit. The X^32 term is "implied"; the LSB is the * X^31 term, etc. The X^0 term (usually shown as "+1") results in * the MSB being 1 * * Note that the usual hardware shift register implementation, which * is what we're using (we're merely optimizing it by doing eight-bit * chunks at a time) shifts bits into the lowest-order term. In our * implementation, that means shifting towards the right. Why do we * do it this way? Because the calculated CRC must be transmitted in * order from highest-order term to lowest-order term. UARTs transmit * characters in order from LSB to MSB. By storing the CRC this way * we hand it to the UART in the order low-byte to high-byte; the UART * sends each low-bit to hight-bit; and the result is transmission bit * by bit from highest- to lowest-order term without requiring any bit * shuffling on our part. Reception works similarly * * The feedback terms table consists of 256, 32-bit entries. Notes * * The table can be generated at runtime if desired; code to do so * is shown later. It might not be obvious, but the feedback * terms simply represent the results of eight shift/xor opera * tions for all combinations of data and CRC register values * * The values must be right-shifted by eight bits by the "updcrc * logic; the shift must be unsigned (bring in zeroes). On some * hardware you could probably optimize the shift in assembler by * using byte-swap instructions * polynomial $edb88320 * * * CRC32 code derived from work by Gary S. Brown. */ static uint32_t crc32_tab[] = { 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d }; static uint32_t crc32(uint32_t crc, const void *buf, size_t size) { const uint8_t *p; p = buf; crc = crc ^ ~0U; while (size--) crc = crc32_tab[(crc ^ *p++) & 0xFF] ^ (crc >> 8); return crc ^ ~0U; } static void efi_set_tables_64(EFI_SYSTEM_TABLE_64 * system_table) { EFI_RUNTIME_SERVICES_64 *runtime; uint32_t hdr_cksum; uint32_t cksum; DPRINTF("Processing 64-bit EFI tables at %p\n", system_table); do { DPRINTF("Header:\n"); DPRINTF(" Signature: 0x%016llx\n", system_table->Hdr.Signature); DPRINTF(" Revision: 0x%08x\n", system_table->Hdr.Revision); DPRINTF(" HeaderSize: 0x%08x\n", system_table->Hdr.HeaderSize); DPRINTF(" CRC32: 0x%08x\n", system_table->Hdr.CRC32); DPRINTF("RuntimeServices: 0x%016llx\n", system_table->RuntimeServices); if (system_table->Hdr.Signature != EFI_SYSTEM_TABLE_SIGNATURE) { kprintf("Bad EFI system table signature\n"); break; } // Verify signature of the system table hdr_cksum = system_table->Hdr.CRC32; system_table->Hdr.CRC32 = 0; cksum = crc32(0L, system_table, system_table->Hdr.HeaderSize); DPRINTF("System table calculated CRC32 = 0x%x, header = 0x%x\n", cksum, hdr_cksum); system_table->Hdr.CRC32 = hdr_cksum; if (cksum != hdr_cksum) { kprintf("Bad EFI system table checksum\n"); break; } gPEEFISystemTable = system_table; if (!cpu_mode_is64bit()) { kprintf("Skipping 64-bit EFI runtime services for 32-bit legacy mode\n"); break; } if(system_table->RuntimeServices == 0) { kprintf("No runtime table present\n"); break; } DPRINTF("RuntimeServices table at 0x%qx\n", system_table->RuntimeServices); // 64-bit virtual address is OK for 64-bit EFI and 64/32-bit kernel. runtime = (EFI_RUNTIME_SERVICES_64 *) (uintptr_t)system_table->RuntimeServices; DPRINTF("Checking runtime services table %p\n", runtime); if (runtime->Hdr.Signature != EFI_RUNTIME_SERVICES_SIGNATURE) { kprintf("Bad EFI runtime table signature\n"); break; } // Verify signature of runtime services table hdr_cksum = runtime->Hdr.CRC32; runtime->Hdr.CRC32 = 0; cksum = crc32(0L, runtime, runtime->Hdr.HeaderSize); DPRINTF("Runtime table calculated CRC32 = 0x%x, header = 0x%x\n", cksum, hdr_cksum); runtime->Hdr.CRC32 = hdr_cksum; if (cksum != hdr_cksum) { kprintf("Bad EFI runtime table checksum\n"); break; } gPEEFIRuntimeServices = runtime; } while (FALSE); } static void efi_set_tables_32(EFI_SYSTEM_TABLE_32 * system_table) { EFI_RUNTIME_SERVICES_32 *runtime; uint32_t hdr_cksum; uint32_t cksum; DPRINTF("Processing 32-bit EFI tables at %p\n", system_table); do { DPRINTF("Header:\n"); DPRINTF(" Signature: 0x%016llx\n", system_table->Hdr.Signature); DPRINTF(" Revision: 0x%08x\n", system_table->Hdr.Revision); DPRINTF(" HeaderSize: 0x%08x\n", system_table->Hdr.HeaderSize); DPRINTF(" CRC32: 0x%08x\n", system_table->Hdr.CRC32); DPRINTF("RuntimeServices: 0x%08x\n", system_table->RuntimeServices); if (system_table->Hdr.Signature != EFI_SYSTEM_TABLE_SIGNATURE) { kprintf("Bad EFI system table signature\n"); break; } // Verify signature of the system table hdr_cksum = system_table->Hdr.CRC32; system_table->Hdr.CRC32 = 0; DPRINTF("System table at %p HeaderSize 0x%x\n", system_table, system_table->Hdr.HeaderSize); cksum = crc32(0L, system_table, system_table->Hdr.HeaderSize); DPRINTF("System table calculated CRC32 = 0x%x, header = 0x%x\n", cksum, hdr_cksum); system_table->Hdr.CRC32 = hdr_cksum; if (cksum != hdr_cksum) { kprintf("Bad EFI system table checksum\n"); break; } gPEEFISystemTable = system_table; if(system_table->RuntimeServices == 0) { kprintf("No runtime table present\n"); break; } DPRINTF("RuntimeServices table at 0x%x\n", system_table->RuntimeServices); // 32-bit virtual address is OK for 32-bit EFI and 32-bit kernel. // For a 64-bit kernel, booter provides a virtual address mod 4G runtime = (EFI_RUNTIME_SERVICES_32 *) #ifdef __x86_64__ (system_table->RuntimeServices | VM_MIN_KERNEL_ADDRESS); #else system_table->RuntimeServices; #endif DPRINTF("Runtime table addressed at %p\n", runtime); if (runtime->Hdr.Signature != EFI_RUNTIME_SERVICES_SIGNATURE) { kprintf("Bad EFI runtime table signature\n"); break; } // Verify signature of runtime services table hdr_cksum = runtime->Hdr.CRC32; runtime->Hdr.CRC32 = 0; cksum = crc32(0L, runtime, runtime->Hdr.HeaderSize); DPRINTF("Runtime table calculated CRC32 = 0x%x, header = 0x%x\n", cksum, hdr_cksum); runtime->Hdr.CRC32 = hdr_cksum; if (cksum != hdr_cksum) { kprintf("Bad EFI runtime table checksum\n"); break; } DPRINTF("Runtime functions\n"); DPRINTF(" GetTime : 0x%x\n", runtime->GetTime); DPRINTF(" SetTime : 0x%x\n", runtime->SetTime); DPRINTF(" GetWakeupTime : 0x%x\n", runtime->GetWakeupTime); DPRINTF(" SetWakeupTime : 0x%x\n", runtime->SetWakeupTime); DPRINTF(" SetVirtualAddressMap : 0x%x\n", runtime->SetVirtualAddressMap); DPRINTF(" ConvertPointer : 0x%x\n", runtime->ConvertPointer); DPRINTF(" GetVariable : 0x%x\n", runtime->GetVariable); DPRINTF(" GetNextVariableName : 0x%x\n", runtime->GetNextVariableName); DPRINTF(" SetVariable : 0x%x\n", runtime->SetVariable); DPRINTF(" GetNextHighMonotonicCount: 0x%x\n", runtime->GetNextHighMonotonicCount); DPRINTF(" ResetSystem : 0x%x\n", runtime->ResetSystem); gPEEFIRuntimeServices = runtime; } while (FALSE); } /* Map in EFI runtime areas. */ static void efi_init(void) { boot_args *args = (boot_args *)PE_state.bootArgs; kprintf("Initializing EFI runtime services\n"); do { vm_offset_t vm_size, vm_addr; vm_map_offset_t phys_addr; EfiMemoryRange *mptr; unsigned int msize, mcount; unsigned int i; msize = args->MemoryMapDescriptorSize; mcount = args->MemoryMapSize / msize; DPRINTF("efi_init() kernel base: 0x%x size: 0x%x\n", args->kaddr, args->ksize); DPRINTF(" efiSystemTable physical: 0x%x virtual: %p\n", args->efiSystemTable, (void *) ml_static_ptovirt(args->efiSystemTable)); DPRINTF(" efiRuntimeServicesPageStart: 0x%x\n", args->efiRuntimeServicesPageStart); DPRINTF(" efiRuntimeServicesPageCount: 0x%x\n", args->efiRuntimeServicesPageCount); DPRINTF(" efiRuntimeServicesVirtualPageStart: 0x%016llx\n", args->efiRuntimeServicesVirtualPageStart); mptr = (EfiMemoryRange *)ml_static_ptovirt(args->MemoryMap); for (i=0; i < mcount; i++, mptr = (EfiMemoryRange *)(((vm_offset_t)mptr) + msize)) { if (((mptr->Attribute & EFI_MEMORY_RUNTIME) == EFI_MEMORY_RUNTIME) ) { vm_size = (vm_offset_t)i386_ptob((uint32_t)mptr->NumberOfPages); vm_addr = (vm_offset_t) mptr->VirtualStart; #ifdef __x86_64__ /* For K64 on EFI32, shadow-map into high KVA */ if (vm_addr < VM_MIN_KERNEL_ADDRESS) vm_addr |= VM_MIN_KERNEL_ADDRESS; #endif phys_addr = (vm_map_offset_t) mptr->PhysicalStart; DPRINTF(" Type: %x phys: %p EFIv: %p kv: %p size: %p\n", mptr->Type, (void *) (uintptr_t) phys_addr, (void *) (uintptr_t) mptr->VirtualStart, (void *) vm_addr, (void *) vm_size); pmap_map_bd(vm_addr, phys_addr, phys_addr + round_page(vm_size), (mptr->Type == kEfiRuntimeServicesCode) ? VM_PROT_READ | VM_PROT_EXECUTE : VM_PROT_READ|VM_PROT_WRITE, (mptr->Type == EfiMemoryMappedIO) ? VM_WIMG_IO : VM_WIMG_USE_DEFAULT); } } if (args->Version != kBootArgsVersion2) panic("Incompatible boot args version %d revision %d\n", args->Version, args->Revision); DPRINTF("Boot args version %d revision %d mode %d\n", args->Version, args->Revision, args->efiMode); if (args->efiMode == kBootArgsEfiMode64) { efi_set_tables_64((EFI_SYSTEM_TABLE_64 *) ml_static_ptovirt(args->efiSystemTable)); } else { efi_set_tables_32((EFI_SYSTEM_TABLE_32 *) ml_static_ptovirt(args->efiSystemTable)); } } while (FALSE); return; } /* Remap EFI runtime areas. */ void hibernate_newruntime_map(void * map, vm_size_t map_size, uint32_t system_table_offset) { boot_args *args = (boot_args *)PE_state.bootArgs; kprintf("Reinitializing EFI runtime services\n"); do { vm_offset_t vm_size, vm_addr; vm_map_offset_t phys_addr; EfiMemoryRange *mptr; unsigned int msize, mcount; unsigned int i; gPEEFISystemTable = 0; gPEEFIRuntimeServices = 0; system_table_offset += ptoa_32(args->efiRuntimeServicesPageStart); kprintf("Old system table 0x%x, new 0x%x\n", (uint32_t)args->efiSystemTable, system_table_offset); args->efiSystemTable = system_table_offset; kprintf("Old map:\n"); msize = args->MemoryMapDescriptorSize; mcount = args->MemoryMapSize / msize; mptr = (EfiMemoryRange *)ml_static_ptovirt(args->MemoryMap); for (i=0; i < mcount; i++, mptr = (EfiMemoryRange *)(((vm_offset_t)mptr) + msize)) { if ((mptr->Attribute & EFI_MEMORY_RUNTIME) == EFI_MEMORY_RUNTIME) { vm_size = (vm_offset_t)i386_ptob((uint32_t)mptr->NumberOfPages); vm_addr = (vm_offset_t) mptr->VirtualStart; #ifdef __x86_64__ /* K64 on EFI32 */ if (vm_addr < VM_MIN_KERNEL_ADDRESS) vm_addr |= VM_MIN_KERNEL_ADDRESS; #endif phys_addr = (vm_map_offset_t) mptr->PhysicalStart; kprintf("mapping[%u] %qx @ %lx, %llu\n", mptr->Type, phys_addr, (unsigned long)vm_addr, mptr->NumberOfPages); } } pmap_remove(kernel_pmap, i386_ptob(args->efiRuntimeServicesPageStart), i386_ptob(args->efiRuntimeServicesPageStart + args->efiRuntimeServicesPageCount)); kprintf("New map:\n"); msize = args->MemoryMapDescriptorSize; mcount = (unsigned int )(map_size / msize); mptr = map; for (i=0; i < mcount; i++, mptr = (EfiMemoryRange *)(((vm_offset_t)mptr) + msize)) { if ((mptr->Attribute & EFI_MEMORY_RUNTIME) == EFI_MEMORY_RUNTIME) { vm_size = (vm_offset_t)i386_ptob((uint32_t)mptr->NumberOfPages); vm_addr = (vm_offset_t) mptr->VirtualStart; #ifdef __x86_64__ if (vm_addr < VM_MIN_KERNEL_ADDRESS) vm_addr |= VM_MIN_KERNEL_ADDRESS; #endif phys_addr = (vm_map_offset_t) mptr->PhysicalStart; kprintf("mapping[%u] %qx @ %lx, %llu\n", mptr->Type, phys_addr, (unsigned long)vm_addr, mptr->NumberOfPages); pmap_map(vm_addr, phys_addr, phys_addr + round_page(vm_size), (mptr->Type == kEfiRuntimeServicesCode) ? VM_PROT_READ | VM_PROT_EXECUTE : VM_PROT_READ|VM_PROT_WRITE, (mptr->Type == EfiMemoryMappedIO) ? VM_WIMG_IO : VM_WIMG_USE_DEFAULT); } } if (args->Version != kBootArgsVersion2) panic("Incompatible boot args version %d revision %d\n", args->Version, args->Revision); kprintf("Boot args version %d revision %d mode %d\n", args->Version, args->Revision, args->efiMode); if (args->efiMode == kBootArgsEfiMode64) { efi_set_tables_64((EFI_SYSTEM_TABLE_64 *) ml_static_ptovirt(args->efiSystemTable)); } else { efi_set_tables_32((EFI_SYSTEM_TABLE_32 *) ml_static_ptovirt(args->efiSystemTable)); } } while (FALSE); kprintf("Done reinitializing EFI runtime services\n"); return; } /* * Find devices. The system is alive. */ void machine_init(void) { #if __x86_64__ /* Now with VM up, switch to dynamically allocated cpu data */ cpu_data_realloc(); #endif /* Ensure panic buffer is initialized. */ debug_log_init(); /* * Display CPU identification */ cpuid_cpu_display("CPU identification"); cpuid_feature_display("CPU features"); cpuid_extfeature_display("CPU extended features"); /* * Initialize EFI runtime services. */ efi_init(); smp_init(); /* * Set up to use floating point. */ init_fpu(); /* * Configure clock devices. */ clock_config(); #if CONFIG_MTRR /* * Initialize MTRR from boot processor. */ mtrr_init(); /* * Set up PAT for boot processor. */ pat_init(); #endif /* * Free lowmem pages and complete other setup */ pmap_lowmem_finalize(); } /* * Halt a cpu. */ void halt_cpu(void) { halt_all_cpus(FALSE); } int reset_mem_on_reboot = 1; /* * Halt the system or reboot. */ void halt_all_cpus(boolean_t reboot) { if (reboot) { printf("MACH Reboot\n"); PEHaltRestart( kPERestartCPU ); } else { printf("CPU halted\n"); PEHaltRestart( kPEHaltCPU ); } while(1); } /* Issue an I/O port read if one has been requested - this is an event logic * analyzers can use as a trigger point. */ void panic_io_port_read(void) { if (panic_io_port) (void)inb(panic_io_port); } /* For use with the MP rendezvous mechanism */ uint64_t panic_restart_timeout = ~(0ULL); #define PANIC_RESTART_TIMEOUT (3ULL * NSEC_PER_SEC) static void machine_halt_cpu(void) { uint64_t deadline; panic_io_port_read(); /* Halt here forever if we're not rebooting */ if (!PE_reboot_on_panic() && panic_restart_timeout == ~(0ULL)) { pmCPUHalt(PM_HALT_DEBUG); return; } if (PE_reboot_on_panic()) deadline = mach_absolute_time() + PANIC_RESTART_TIMEOUT; else deadline = mach_absolute_time() + panic_restart_timeout; while (mach_absolute_time() < deadline) cpu_pause(); kprintf("Invoking PE_halt_restart\n"); /* Attempt restart via ACPI RESET_REG; at the time of this * writing, this is routine is chained through AppleSMC-> * AppleACPIPlatform */ if (PE_halt_restart) (*PE_halt_restart)(kPERestartCPU); pmCPUHalt(PM_HALT_DEBUG); } void DebuggerWithContext( __unused unsigned int reason, __unused void *ctx, const char *message) { Debugger(message); } void Debugger( const char *message) { unsigned long pi_size = 0; void *stackptr; int cn = cpu_number(); hw_atomic_add(&debug_mode, 1); if (!panic_is_inited) { postcode(PANIC_HLT); asm("hlt"); } printf("Debugger called: <%s>\n", message); kprintf("Debugger called: <%s>\n", message); /* * Skip the graphical panic box if no panic string. * This is the case if we're being called from * host_reboot(,HOST_REBOOT_DEBUGGER) * as a quiet way into the debugger. */ if (panicstr) { disable_preemption(); /* Issue an I/O port read if one has been requested - this is an event logic * analyzers can use as a trigger point. */ panic_io_port_read(); /* Obtain current frame pointer */ #if defined (__i386__) __asm__ volatile("movl %%ebp, %0" : "=m" (stackptr)); #elif defined (__x86_64__) __asm__ volatile("movq %%rbp, %0" : "=m" (stackptr)); #endif /* Print backtrace - callee is internally synchronized */ panic_i386_backtrace(stackptr, ((panic_double_fault_cpu == cn) ? 80: 48), NULL, FALSE, NULL); /* everything should be printed now so copy to NVRAM */ if( debug_buf_size > 0) { /* Optionally sync the panic log, if any, to NVRAM * This is the default. */ if (commit_paniclog_to_nvram) { unsigned int bufpos; uintptr_t cr0; debug_putc(0); /* Now call the compressor */ /* XXX Consider using the WKdm compressor in the * future, rather than just packing - would need to * be co-ordinated with crashreporter, which decodes * this post-restart. The compressor should be * capable of in-place compression. */ bufpos = packA(debug_buf, (unsigned int) (debug_buf_ptr - debug_buf), debug_buf_size); /* If compression was successful, * use the compressed length */ pi_size = bufpos ? bufpos : (unsigned) (debug_buf_ptr - debug_buf); /* Save panic log to non-volatile store * Panic info handler must truncate data that is * too long for this platform. * This call must save data synchronously, * since we can subsequently halt the system. */ /* The following sequence is a workaround for: * <rdar://problem/5915669> SnowLeopard10A67: AppleEFINVRAM should not invoke * any routines that use floating point (MMX in this case) when saving panic * logs to nvram/flash. */ cr0 = get_cr0(); clear_ts(); kprintf("Attempting to commit panic log to NVRAM\n"); pi_size = PESavePanicInfo((unsigned char *)debug_buf, (uint32_t)pi_size ); set_cr0(cr0); /* Uncompress in-place, to permit examination of * the panic log by debuggers. */ if (bufpos) { unpackA(debug_buf, bufpos); } } } if (!panicDebugging) { unsigned cnum; /* Clear the MP rendezvous function lock, in the event * that a panic occurred while in that codepath. */ mp_rendezvous_break_lock(); /* Non-maskably interrupt all other processors * If a restart timeout is specified, this processor * will attempt a restart. */ kprintf("Invoking machine_halt_cpu on CPU %d\n", cn); for (cnum = 0; cnum < real_ncpus; cnum++) { if (cnum != (unsigned) cn) { cpu_NMI_interrupt(cnum); } } machine_halt_cpu(); /* NOT REACHED */ } } __asm__("int3"); hw_atomic_sub(&debug_mode, 1); } char * machine_boot_info(char *buf, __unused vm_size_t size) { *buf ='\0'; return buf; } /* Routines for address - symbol translation. Not called unless the "keepsyms" * boot-arg is supplied. */ static int panic_print_macho_symbol_name(kernel_mach_header_t *mh, vm_address_t search, const char *module_name) { kernel_nlist_t *sym = NULL; struct load_command *cmd; kernel_segment_command_t *orig_ts = NULL, *orig_le = NULL; struct symtab_command *orig_st = NULL; unsigned int i; char *strings, *bestsym = NULL; vm_address_t bestaddr = 0, diff, curdiff; /* Assume that if it's loaded and linked into the kernel, it's a valid Mach-O */ cmd = (struct load_command *) &mh[1]; for (i = 0; i < mh->ncmds; i++) { if (cmd->cmd == LC_SEGMENT_KERNEL) { kernel_segment_command_t *orig_sg = (kernel_segment_command_t *) cmd; if (strncmp(SEG_TEXT, orig_sg->segname, sizeof(orig_sg->segname)) == 0) orig_ts = orig_sg; else if (strncmp(SEG_LINKEDIT, orig_sg->segname, sizeof(orig_sg->segname)) == 0) orig_le = orig_sg; else if (strncmp("", orig_sg->segname, sizeof(orig_sg->segname)) == 0) orig_ts = orig_sg; /* pre-Lion i386 kexts have a single unnamed segment */ } else if (cmd->cmd == LC_SYMTAB) orig_st = (struct symtab_command *) cmd; cmd = (struct load_command *) ((uintptr_t) cmd + cmd->cmdsize); } if ((orig_ts == NULL) || (orig_st == NULL) || (orig_le == NULL)) return 0; if ((search < orig_ts->vmaddr) || (search >= orig_ts->vmaddr + orig_ts->vmsize)) { /* search out of range for this mach header */ return 0; } sym = (kernel_nlist_t *)(uintptr_t)(orig_le->vmaddr + orig_st->symoff - orig_le->fileoff); strings = (char *)(uintptr_t)(orig_le->vmaddr + orig_st->stroff - orig_le->fileoff); diff = search; for (i = 0; i < orig_st->nsyms; i++) { if (sym[i].n_type & N_STAB) continue; if (sym[i].n_value <= search) { curdiff = search - (vm_address_t)sym[i].n_value; if (curdiff < diff) { diff = curdiff; bestaddr = sym[i].n_value; bestsym = strings + sym[i].n_un.n_strx; } } } if (bestsym != NULL) { if (diff != 0) { kdb_printf("%s : %s + 0x%lx", module_name, bestsym, (unsigned long)diff); } else { kdb_printf("%s : %s", module_name, bestsym); } return 1; } return 0; } extern kmod_info_t * kmod; /* the list of modules */ static void panic_print_kmod_symbol_name(vm_address_t search) { u_int i; if (gLoadedKextSummaries == NULL) return; for (i = 0; i < gLoadedKextSummaries->numSummaries; ++i) { OSKextLoadedKextSummary *summary = gLoadedKextSummaries->summaries + i; if ((search >= summary->address) && (search < (summary->address + summary->size))) { kernel_mach_header_t *header = (kernel_mach_header_t *)(uintptr_t) summary->address; if (panic_print_macho_symbol_name(header, search, summary->name) == 0) { kdb_printf("%s + %llu", summary->name, (unsigned long)search - summary->address); } break; } } } static void panic_print_symbol_name(vm_address_t search) { /* try searching in the kernel */ if (panic_print_macho_symbol_name(&_mh_execute_header, search, "mach_kernel") == 0) { /* that failed, now try to search for the right kext */ panic_print_kmod_symbol_name(search); } } /* Generate a backtrace, given a frame pointer - this routine * should walk the stack safely. The trace is appended to the panic log * and conditionally, to the console. If the trace contains kernel module * addresses, display the module name, load address and dependencies. */ #define DUMPFRAMES 32 #define PBT_TIMEOUT_CYCLES (5 * 1000 * 1000 * 1000ULL) void panic_i386_backtrace(void *_frame, int nframes, const char *msg, boolean_t regdump, x86_saved_state_t *regs) { cframe_t *frame = (cframe_t *)_frame; vm_offset_t raddrs[DUMPFRAMES]; vm_offset_t PC = 0; int frame_index; volatile uint32_t *ppbtcnt = &pbtcnt; uint64_t bt_tsc_timeout; boolean_t keepsyms = FALSE; int cn = cpu_number(); if(pbtcpu != cn) { hw_atomic_add(&pbtcnt, 1); /* Spin on print backtrace lock, which serializes output * Continue anyway if a timeout occurs. */ hw_lock_to(&pbtlock, LockTimeOutTSC*2); pbtcpu = cn; } PE_parse_boot_argn("keepsyms", &keepsyms, sizeof (keepsyms)); if (msg != NULL) { kdb_printf("%s", msg); } if ((regdump == TRUE) && (regs != NULL)) { #if defined(__x86_64__) x86_saved_state64_t *ss64p = saved_state64(regs); kdb_printf( "RAX: 0x%016llx, RBX: 0x%016llx, RCX: 0x%016llx, RDX: 0x%016llx\n" "RSP: 0x%016llx, RBP: 0x%016llx, RSI: 0x%016llx, RDI: 0x%016llx\n" "R8: 0x%016llx, R9: 0x%016llx, R10: 0x%016llx, R11: 0x%016llx\n" "R12: 0x%016llx, R13: 0x%016llx, R14: 0x%016llx, R15: 0x%016llx\n" "RFL: 0x%016llx, RIP: 0x%016llx, CS: 0x%016llx, SS: 0x%016llx\n", ss64p->rax, ss64p->rbx, ss64p->rcx, ss64p->rdx, ss64p->isf.rsp, ss64p->rbp, ss64p->rsi, ss64p->rdi, ss64p->r8, ss64p->r9, ss64p->r10, ss64p->r11, ss64p->r12, ss64p->r13, ss64p->r14, ss64p->r15, ss64p->isf.rflags, ss64p->isf.rip, ss64p->isf.cs, ss64p->isf.ss); PC = ss64p->isf.rip; #else x86_saved_state32_t *ss32p = saved_state32(regs); kdb_printf( "EAX: 0x%08x, EBX: 0x%08x, ECX: 0x%08x, EDX: 0x%08x\n" "CR2: 0x%08x, EBP: 0x%08x, ESI: 0x%08x, EDI: 0x%08x\n" "EFL: 0x%08x, EIP: 0x%08x, CS: 0x%08x, DS: 0x%08x\n", ss32p->eax,ss32p->ebx,ss32p->ecx,ss32p->edx, ss32p->cr2,ss32p->ebp,ss32p->esi,ss32p->edi, ss32p->efl,ss32p->eip,ss32p->cs, ss32p->ds); PC = ss32p->eip; #endif } kdb_printf("Backtrace (CPU %d), " #if PRINT_ARGS_FROM_STACK_FRAME "Frame : Return Address (4 potential args on stack)\n", cn); #else "Frame : Return Address\n", cn); #endif for (frame_index = 0; frame_index < nframes; frame_index++) { vm_offset_t curframep = (vm_offset_t) frame; if (!curframep) break; if (curframep & 0x3) { kdb_printf("Unaligned frame\n"); goto invalid; } if (!kvtophys(curframep) || !kvtophys(curframep + sizeof(cframe_t) - 1)) { kdb_printf("No mapping exists for frame pointer\n"); goto invalid; } kdb_printf("%p : 0x%lx ", frame, frame->caller); if (frame_index < DUMPFRAMES) raddrs[frame_index] = frame->caller; #if PRINT_ARGS_FROM_STACK_FRAME if (kvtophys((vm_offset_t)&(frame->args[3]))) kdb_printf("(0x%x 0x%x 0x%x 0x%x) ", frame->args[0], frame->args[1], frame->args[2], frame->args[3]); #endif /* Display address-symbol translation only if the "keepsyms" * boot-arg is suppplied, since we unload LINKEDIT otherwise. * This routine is potentially unsafe; also, function * boundary identification is unreliable after a strip -x. */ if (keepsyms) panic_print_symbol_name((vm_address_t)frame->caller); kdb_printf("\n"); frame = frame->prev; } if (frame_index >= nframes) kdb_printf("\tBacktrace continues...\n"); goto out; invalid: kdb_printf("Backtrace terminated-invalid frame pointer %p\n",frame); out: /* Identify kernel modules in the backtrace and display their * load addresses and dependencies. This routine should walk * the kmod list safely. */ if (frame_index) kmod_panic_dump((vm_offset_t *)&raddrs[0], frame_index); if (PC != 0) kmod_panic_dump(&PC, 1); panic_display_system_configuration(); /* Release print backtrace lock, to permit other callers in the * event of panics on multiple processors. */ hw_lock_unlock(&pbtlock); hw_atomic_sub(&pbtcnt, 1); /* Wait for other processors to complete output * Timeout and continue after PBT_TIMEOUT_CYCLES. */ bt_tsc_timeout = rdtsc64() + PBT_TIMEOUT_CYCLES; while(*ppbtcnt && (rdtsc64() < bt_tsc_timeout)); }
gpl-3.0
davidcastells/BigInteger
c_apint/apint_mod.cpp
1
1581
/* * Copyright (C) 2017 Universitat Autonoma de Barcelona - David Castells-Rufas <david.castells@uab.cat> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "../big_integer_apint.h" ap_uint<NUM_BIG_INTEGER_APINT_BITS> big_integer_apint_mod(ap_uint<NUM_BIG_INTEGER_APINT_BITS> ap_x, ap_uint<NUM_BIG_INTEGER_APINT_BITS> ap_y) { ap_uint<NUM_BIG_INTEGER_APINT_BITS*2> x2 = ap_x; ap_uint<NUM_BIG_INTEGER_APINT_BITS*2> y2 = ap_y; y2 <<= NUM_BIG_INTEGER_APINT_BITS; ap_uint<NUM_BIG_INTEGER_APINT_BITS*2> r2 = 0; { // get the length of y r2 = x2; for (int i=0; i < NUM_BIG_INTEGER_APINT_BITS; i++) { r2 <<= 1; if (r2 >= y2) r2 -= y2; } ap_uint<NUM_BIG_INTEGER_APINT_BITS> ap_r; ap_r = (r2 >> NUM_BIG_INTEGER_APINT_BITS); return ap_r; } }
gpl-3.0
Makki1/old-svn
avr/sketchbook/GiraRM_Debug/freebus/freebus_lpc/89LPC922/sniffer/fb_snif.c
1
1510
/* * __________ ________________ __ _______ * / ____/ __ \/ ____/ ____/ __ )/ / / / ___/ * / /_ / /_/ / __/ / __/ / __ / / / /\__ \ * / __/ / _, _/ /___/ /___/ /_/ / /_/ /___/ / * /_/ /_/ |_/_____/_____/_____/\____//____/ * * Copyright (c) 2008 Andreas Krebs <kubi@krebsworld.de> * * 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. * */ // Versionen: 1.00 erste Version #include <P89LPC922.h> #include "../com/fb_hal_lpc.h" #include "../com/fb_prot.h" #include "../com/fb_rs232.h" #include "fb_app_snif.h" void main(void) { unsigned char n; restart_hw(); // Hardware zurücksetzen restart_prot(); // Protokoll-relevante Parameter zurücksetzen restart_app(); // Anwendungsspezifische Einstellungen zurücksetzen rs_init(); // serielle Schnittstelle initialisieren do { if (RI) { RI=0; rs_send(eeprom[SBUF]); } TASTER=1; // Pin als Eingang schalten um Taster abzufragen if(!TASTER) { // Taster gedrückt for(n=0;n<100;n++) {} while(!TASTER); // warten bis Taster losgelassen progmode=!progmode; } TASTER=!progmode; // LED entsprechend schalten (low=LED an) for(n=0;n<100;n++) {} } while(1); }
gpl-3.0
patwonder/craft-othello
Craft Engine/Solver_stability.cpp
1
52674
/* ************************************************************************* Craft is an othello program with relatively high AI. Copyright (C) 2008-2011 Patrick This file is part of Craft. Craft 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. Craft 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 Craft. If not, see <http://www.gnu.org/licenses/>. Craft-Othello on Google Code: <http://code.google.com/p/craft-othello/> Patrick's E-mail: patrick880905@sina.com Patrick's Blog: <http://blog.sina.com.cn/patwonder> ************************************************************************* */ /* ******************************************************************************** Solver_stability.cpp 作者:Patrick 概述:包含类 Solver 关于稳定子部分的数据定义。 Solver 是 Craft 的核心 AI 引擎。 ******************************************************************************** */ #include "StdAfx.h" #include "Solver.h" using namespace CraftEngine; #ifdef STABILITY #ifdef COMPACT unsigned char Solver::stab_my[6561] = { #else unsigned int Solver::stab_my[6561] = { #endif 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 15, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 31, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 15, 0, 0, 1, 0, 0, 1, 0, 0, 3, 2, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 15, 0, 0, 1, 0, 0, 1, 0, 0, 3, 2, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 63, 0, 0, 1, 0, 0, 1, 0, 0, 3, 2, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 6, 4, 5, 4, 0, 1, 0, 0, 3, 2, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 15, 14, 12, 13, 12, 0, 9, 8, 8, 11, 10, 8, 9, 8, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 6, 4, 5, 4, 0, 1, 0, 0, 3, 2, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 15, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 31, 0, 0, 1, 0, 0, 1, 0, 0, 3, 2, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 6, 4, 5, 4, 0, 1, 0, 0, 3, 2, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 15, 0, 0, 1, 0, 0, 1, 0, 0, 3, 2, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 15, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 31, 0, 0, 1, 0, 0, 1, 0, 0, 3, 2, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 6, 4, 5, 4, 0, 1, 0, 0, 3, 2, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 15, 0, 0, 1, 0, 0, 1, 0, 0, 3, 2, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 15, 0, 0, 1, 0, 0, 1, 0, 0, 3, 2, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 127, 0, 0, 1, 0, 0, 1, 0, 0, 3, 2, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 6, 4, 5, 4, 0, 1, 0, 0, 3, 2, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 15, 14, 12, 13, 12, 0, 9, 8, 8, 11, 10, 8, 9, 8, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 6, 4, 5, 4, 0, 1, 0, 0, 3, 2, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 15, 0, 0, 1, 0, 0, 1, 0, 0, 3, 2, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 2, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 31, 30, 28, 29, 28, 0, 25, 24, 24, 27, 26, 24, 25, 24, 0, 1, 0, 0, 19, 16, 16, 17, 16, 16, 17, 16, 16, 23, 22, 20, 21, 20, 0, 17, 16, 16, 19, 18, 16, 17, 16, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 15, 14, 12, 13, 12, 0, 9, 8, 8, 11, 10, 8, 9, 8, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 6, 4, 5, 4, 0, 1, 0, 0, 3, 2, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 15, 0, 0, 1, 0, 0, 1, 0, 0, 3, 2, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 31, 0, 0, 1, 0, 0, 1, 0, 0, 3, 2, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 6, 4, 5, 4, 0, 1, 0, 0, 3, 2, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 2, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 15, 14, 12, 13, 12, 0, 9, 8, 8, 11, 10, 8, 9, 8, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 6, 4, 5, 4, 0, 1, 0, 0, 3, 2, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 15, 0, 0, 1, 0, 0, 1, 0, 0, 3, 2, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 6, 4, 5, 4, 0, 1, 0, 0, 3, 2, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 2, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 63, 62, 60, 61, 60, 0, 57, 56, 56, 59, 58, 56, 57, 56, 0, 1, 0, 0, 51, 48, 48, 49, 48, 48, 49, 48, 48, 55, 54, 52, 53, 52, 0, 49, 48, 48, 51, 50, 48, 49, 48, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 39, 32, 32, 33, 32, 0, 33, 32, 0, 35, 34, 32, 33, 32, 0, 33, 32, 32, 35, 32, 32, 33, 32, 32, 33, 32, 32, 47, 46, 44, 45, 44, 32, 41, 40, 40, 43, 42, 40, 41, 40, 0, 1, 0, 0, 35, 32, 32, 33, 32, 32, 33, 32, 32, 39, 38, 36, 37, 36, 0, 33, 32, 32, 35, 34, 32, 33, 32, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 15, 0, 0, 1, 0, 0, 1, 0, 0, 3, 2, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 6, 4, 5, 4, 0, 1, 0, 0, 3, 2, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 2, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 31, 30, 28, 29, 28, 0, 25, 24, 24, 27, 26, 24, 25, 24, 0, 1, 0, 0, 19, 16, 16, 17, 16, 16, 17, 16, 16, 23, 22, 20, 21, 20, 0, 17, 16, 16, 19, 18, 16, 17, 16, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 2, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 15, 14, 12, 13, 12, 0, 9, 8, 8, 11, 10, 8, 9, 8, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 6, 4, 5, 4, 0, 1, 0, 0, 3, 2, 0, 1, 0, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 135, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 143, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 135, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 135, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 159, 128, 128, 129, 128, 128, 129, 128, 128, 131, 130, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 135, 134, 132, 133, 132, 128, 129, 128, 128, 131, 130, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 135, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 143, 128, 128, 129, 128, 128, 129, 128, 128, 131, 130, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 135, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 135, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 143, 128, 128, 129, 128, 128, 129, 128, 128, 131, 130, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 135, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 135, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 191, 128, 128, 129, 128, 128, 129, 128, 128, 131, 130, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 135, 134, 132, 133, 132, 128, 129, 128, 128, 131, 130, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 135, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 143, 142, 140, 141, 140, 128, 137, 136, 136, 139, 138, 136, 137, 136, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 135, 134, 132, 133, 132, 128, 129, 128, 128, 131, 130, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 135, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 143, 128, 128, 129, 128, 128, 129, 128, 128, 131, 130, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 135, 134, 132, 133, 132, 128, 129, 128, 128, 131, 130, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 135, 128, 128, 129, 128, 128, 129, 128, 128, 131, 130, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 159, 158, 156, 157, 156, 128, 153, 152, 152, 155, 154, 152, 153, 152, 128, 129, 128, 128, 147, 144, 144, 145, 144, 144, 145, 144, 144, 151, 150, 148, 149, 148, 128, 145, 144, 144, 147, 146, 144, 145, 144, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 135, 128, 128, 129, 128, 128, 129, 128, 128, 131, 130, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 143, 142, 140, 141, 140, 128, 137, 136, 136, 139, 138, 136, 137, 136, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 135, 134, 132, 133, 132, 128, 129, 128, 128, 131, 130, 128, 129, 128, 192, 193, 192, 192, 195, 192, 192, 193, 192, 192, 193, 192, 192, 199, 192, 192, 193, 192, 192, 193, 192, 192, 195, 192, 192, 193, 192, 192, 193, 192, 192, 195, 192, 192, 193, 192, 192, 193, 192, 192, 207, 192, 192, 193, 192, 192, 193, 192, 192, 195, 194, 192, 193, 192, 192, 193, 192, 192, 195, 192, 192, 193, 192, 192, 193, 192, 192, 199, 192, 192, 193, 192, 192, 193, 192, 192, 195, 192, 192, 193, 192, 192, 193, 192, 192, 195, 192, 192, 193, 192, 192, 193, 192, 192, 199, 192, 192, 193, 192, 192, 193, 192, 192, 195, 192, 192, 193, 192, 192, 193, 192, 192, 195, 192, 192, 193, 192, 192, 193, 192, 192, 223, 192, 192, 193, 192, 192, 193, 192, 192, 195, 194, 192, 193, 192, 192, 193, 192, 192, 195, 192, 192, 193, 192, 192, 193, 192, 192, 199, 198, 196, 197, 196, 192, 193, 192, 192, 195, 194, 192, 193, 192, 192, 193, 192, 192, 195, 192, 192, 193, 192, 192, 193, 192, 192, 199, 192, 192, 193, 192, 192, 193, 192, 192, 195, 194, 192, 193, 192, 192, 193, 192, 192, 195, 192, 192, 193, 192, 192, 193, 192, 192, 207, 206, 204, 205, 204, 192, 201, 200, 200, 203, 202, 200, 201, 200, 192, 193, 192, 192, 195, 192, 192, 193, 192, 192, 193, 192, 192, 199, 198, 196, 197, 196, 192, 193, 192, 192, 195, 194, 192, 193, 192, 224, 225, 224, 224, 227, 224, 224, 225, 224, 224, 225, 224, 224, 231, 224, 224, 225, 224, 224, 225, 224, 224, 227, 224, 224, 225, 224, 224, 225, 224, 224, 227, 224, 224, 225, 224, 224, 225, 224, 224, 239, 224, 224, 225, 224, 224, 225, 224, 224, 227, 226, 224, 225, 224, 224, 225, 224, 224, 227, 224, 224, 225, 224, 224, 225, 224, 224, 231, 230, 228, 229, 228, 224, 225, 224, 224, 227, 226, 224, 225, 224, 240, 241, 240, 240, 243, 240, 240, 241, 240, 240, 241, 240, 240, 247, 240, 240, 241, 240, 240, 241, 240, 240, 243, 242, 240, 241, 240, 248, 249, 248, 248, 251, 248, 248, 249, 248, 252, 253, 252, 254, 255, 254, 252, 253, 252, 248, 249, 248, 248, 251, 250, 248, 249, 248, 240, 241, 240, 240, 243, 240, 240, 241, 240, 240, 241, 240, 240, 247, 246, 244, 245, 244, 240, 241, 240, 240, 243, 242, 240, 241, 240, 224, 225, 224, 224, 227, 224, 224, 225, 224, 224, 225, 224, 224, 231, 224, 224, 225, 224, 224, 225, 224, 224, 227, 226, 224, 225, 224, 224, 225, 224, 224, 227, 224, 224, 225, 224, 224, 225, 224, 224, 239, 238, 236, 237, 236, 224, 233, 232, 232, 235, 234, 232, 233, 232, 224, 225, 224, 224, 227, 224, 224, 225, 224, 224, 225, 224, 224, 231, 230, 228, 229, 228, 224, 225, 224, 224, 227, 226, 224, 225, 224, 192, 193, 192, 192, 195, 192, 192, 193, 192, 192, 193, 192, 192, 199, 192, 192, 193, 192, 192, 193, 192, 192, 195, 192, 192, 193, 192, 192, 193, 192, 192, 195, 192, 192, 193, 192, 192, 193, 192, 192, 207, 192, 192, 193, 192, 192, 193, 192, 192, 195, 194, 192, 193, 192, 192, 193, 192, 192, 195, 192, 192, 193, 192, 192, 193, 192, 192, 199, 198, 196, 197, 196, 192, 193, 192, 192, 195, 194, 192, 193, 192, 192, 193, 192, 192, 195, 192, 192, 193, 192, 192, 193, 192, 192, 199, 192, 192, 193, 192, 192, 193, 192, 192, 195, 194, 192, 193, 192, 192, 193, 192, 192, 195, 192, 192, 193, 192, 192, 193, 192, 192, 223, 222, 220, 221, 220, 192, 217, 216, 216, 219, 218, 216, 217, 216, 192, 193, 192, 192, 211, 208, 208, 209, 208, 208, 209, 208, 208, 215, 214, 212, 213, 212, 192, 209, 208, 208, 211, 210, 208, 209, 208, 192, 193, 192, 192, 195, 192, 192, 193, 192, 192, 193, 192, 192, 199, 192, 192, 193, 192, 192, 193, 192, 192, 195, 194, 192, 193, 192, 192, 193, 192, 192, 195, 192, 192, 193, 192, 192, 193, 192, 192, 207, 206, 204, 205, 204, 192, 201, 200, 200, 203, 202, 200, 201, 200, 192, 193, 192, 192, 195, 192, 192, 193, 192, 192, 193, 192, 192, 199, 198, 196, 197, 196, 192, 193, 192, 192, 195, 194, 192, 193, 192, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 135, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 143, 128, 128, 129, 128, 128, 129, 128, 128, 131, 130, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 135, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 135, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 159, 128, 128, 129, 128, 128, 129, 128, 128, 131, 130, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 135, 134, 132, 133, 132, 128, 129, 128, 128, 131, 130, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 135, 128, 128, 129, 128, 128, 129, 128, 128, 131, 130, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 143, 142, 140, 141, 140, 128, 137, 136, 136, 139, 138, 136, 137, 136, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 135, 134, 132, 133, 132, 128, 129, 128, 128, 131, 130, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 135, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 143, 128, 128, 129, 128, 128, 129, 128, 128, 131, 130, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 135, 134, 132, 133, 132, 128, 129, 128, 128, 131, 130, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 135, 128, 128, 129, 128, 128, 129, 128, 128, 131, 130, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 191, 190, 188, 189, 188, 128, 185, 184, 184, 187, 186, 184, 185, 184, 128, 129, 128, 128, 179, 176, 176, 177, 176, 176, 177, 176, 176, 183, 182, 180, 181, 180, 128, 177, 176, 176, 179, 178, 176, 177, 176, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 167, 160, 160, 161, 160, 128, 161, 160, 128, 163, 162, 160, 161, 160, 128, 161, 160, 160, 163, 160, 160, 161, 160, 160, 161, 160, 160, 175, 174, 172, 173, 172, 160, 169, 168, 168, 171, 170, 168, 169, 168, 128, 129, 128, 128, 163, 160, 160, 161, 160, 160, 161, 160, 160, 167, 166, 164, 165, 164, 128, 161, 160, 160, 163, 162, 160, 161, 160, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 135, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 143, 128, 128, 129, 128, 128, 129, 128, 128, 131, 130, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 135, 134, 132, 133, 132, 128, 129, 128, 128, 131, 130, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 135, 128, 128, 129, 128, 128, 129, 128, 128, 131, 130, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 159, 158, 156, 157, 156, 128, 153, 152, 152, 155, 154, 152, 153, 152, 128, 129, 128, 128, 147, 144, 144, 145, 144, 144, 145, 144, 144, 151, 150, 148, 149, 148, 128, 145, 144, 144, 147, 146, 144, 145, 144, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 135, 128, 128, 129, 128, 128, 129, 128, 128, 131, 130, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 143, 142, 140, 141, 140, 128, 137, 136, 136, 139, 138, 136, 137, 136, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 135, 134, 132, 133, 132, 128, 129, 128, 128, 131, 130, 128, 129, 128, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 15, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 31, 0, 0, 1, 0, 0, 1, 0, 0, 3, 2, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 6, 4, 5, 4, 0, 1, 0, 0, 3, 2, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 15, 0, 0, 1, 0, 0, 1, 0, 0, 3, 2, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 15, 0, 0, 1, 0, 0, 1, 0, 0, 3, 2, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 63, 0, 0, 1, 0, 0, 1, 0, 0, 3, 2, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 6, 4, 5, 4, 0, 1, 0, 0, 3, 2, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 15, 14, 12, 13, 12, 0, 9, 8, 8, 11, 10, 8, 9, 8, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 6, 4, 5, 4, 0, 1, 0, 0, 3, 2, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 15, 0, 0, 1, 0, 0, 1, 0, 0, 3, 2, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 6, 4, 5, 4, 0, 1, 0, 0, 3, 2, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 2, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 31, 30, 28, 29, 28, 0, 25, 24, 24, 27, 26, 24, 25, 24, 0, 1, 0, 0, 19, 16, 16, 17, 16, 16, 17, 16, 16, 23, 22, 20, 21, 20, 0, 17, 16, 16, 19, 18, 16, 17, 16, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 2, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 15, 14, 12, 13, 12, 0, 9, 8, 8, 11, 10, 8, 9, 8, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 6, 4, 5, 4, 0, 1, 0, 0, 3, 2, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 15, 0, 0, 1, 0, 0, 1, 0, 0, 3, 2, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 31, 0, 0, 1, 0, 0, 1, 0, 0, 3, 2, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 6, 4, 5, 4, 0, 1, 0, 0, 3, 2, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 2, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 15, 14, 12, 13, 12, 0, 9, 8, 8, 11, 10, 8, 9, 8, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 6, 4, 5, 4, 0, 1, 0, 0, 3, 2, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 15, 0, 0, 1, 0, 0, 1, 0, 0, 3, 2, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 6, 4, 5, 4, 0, 1, 0, 0, 3, 2, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 2, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 127, 126, 124, 125, 124, 0, 121, 120, 120, 123, 122, 120, 121, 120, 0, 1, 0, 0, 115, 112, 112, 113, 112, 112, 113, 112, 112, 119, 118, 116, 117, 116, 0, 113, 112, 112, 115, 114, 112, 113, 112, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 103, 96, 96, 97, 96, 0, 97, 96, 0, 99, 98, 96, 97, 96, 0, 97, 96, 96, 99, 96, 96, 97, 96, 96, 97, 96, 96, 111, 110, 108, 109, 108, 96, 105, 104, 104, 107, 106, 104, 105, 104, 0, 1, 0, 0, 99, 96, 96, 97, 96, 96, 97, 96, 96, 103, 102, 100, 101, 100, 0, 97, 96, 96, 99, 98, 96, 97, 96, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 79, 64, 64, 65, 64, 0, 65, 64, 64, 67, 66, 64, 65, 64, 0, 1, 0, 0, 67, 64, 64, 65, 64, 0, 1, 0, 0, 71, 70, 68, 69, 68, 0, 65, 64, 0, 67, 66, 64, 65, 64, 0, 1, 0, 0, 67, 64, 64, 65, 64, 64, 65, 64, 64, 71, 64, 64, 65, 64, 0, 65, 64, 64, 67, 66, 64, 65, 64, 0, 65, 64, 64, 67, 64, 64, 65, 64, 64, 65, 64, 64, 95, 94, 92, 93, 92, 64, 89, 88, 88, 91, 90, 88, 89, 88, 64, 65, 64, 64, 83, 80, 80, 81, 80, 80, 81, 80, 80, 87, 86, 84, 85, 84, 64, 81, 80, 80, 83, 82, 80, 81, 80, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 71, 64, 64, 65, 64, 0, 65, 64, 0, 67, 66, 64, 65, 64, 0, 65, 64, 64, 67, 64, 64, 65, 64, 64, 65, 64, 64, 79, 78, 76, 77, 76, 64, 73, 72, 72, 75, 74, 72, 73, 72, 0, 1, 0, 0, 67, 64, 64, 65, 64, 64, 65, 64, 64, 71, 70, 68, 69, 68, 0, 65, 64, 64, 67, 66, 64, 65, 64, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 15, 0, 0, 1, 0, 0, 1, 0, 0, 3, 2, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 31, 0, 0, 1, 0, 0, 1, 0, 0, 3, 2, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 6, 4, 5, 4, 0, 1, 0, 0, 3, 2, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 2, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 15, 14, 12, 13, 12, 0, 9, 8, 8, 11, 10, 8, 9, 8, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 6, 4, 5, 4, 0, 1, 0, 0, 3, 2, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 15, 0, 0, 1, 0, 0, 1, 0, 0, 3, 2, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 6, 4, 5, 4, 0, 1, 0, 0, 3, 2, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 2, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 63, 62, 60, 61, 60, 0, 57, 56, 56, 59, 58, 56, 57, 56, 0, 1, 0, 0, 51, 48, 48, 49, 48, 48, 49, 48, 48, 55, 54, 52, 53, 52, 0, 49, 48, 48, 51, 50, 48, 49, 48, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 39, 32, 32, 33, 32, 0, 33, 32, 0, 35, 34, 32, 33, 32, 0, 33, 32, 32, 35, 32, 32, 33, 32, 32, 33, 32, 32, 47, 46, 44, 45, 44, 32, 41, 40, 40, 43, 42, 40, 41, 40, 0, 1, 0, 0, 35, 32, 32, 33, 32, 32, 33, 32, 32, 39, 38, 36, 37, 36, 0, 33, 32, 32, 35, 34, 32, 33, 32, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 15, 0, 0, 1, 0, 0, 1, 0, 0, 3, 2, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 6, 4, 5, 4, 0, 1, 0, 0, 3, 2, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 2, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 31, 30, 28, 29, 28, 0, 25, 24, 24, 27, 26, 24, 25, 24, 0, 1, 0, 0, 19, 16, 16, 17, 16, 16, 17, 16, 16, 23, 22, 20, 21, 20, 0, 17, 16, 16, 19, 18, 16, 17, 16, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 2, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 15, 14, 12, 13, 12, 0, 9, 8, 8, 11, 10, 8, 9, 8, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 6, 4, 5, 4, 0, 1, 0, 0, 3, 2, 0, 1, 0 }; #ifdef COMPACT unsigned char Solver::stab_op[6561] = { #else unsigned int Solver::stab_op[6561] = { #endif 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 15, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 2, 3, 0, 0, 1, 0, 0, 1, 0, 0, 15, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 31, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 15, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 2, 3, 0, 0, 1, 0, 0, 1, 0, 0, 15, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 2, 3, 0, 0, 1, 4, 4, 5, 0, 6, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 2, 3, 0, 0, 1, 0, 0, 1, 0, 0, 31, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 2, 3, 0, 0, 1, 0, 0, 1, 0, 0, 15, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 2, 3, 0, 0, 1, 4, 4, 5, 0, 6, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 8, 9, 8, 8, 9, 8, 10, 11, 0, 0, 1, 12, 12, 13, 0, 14, 15, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 2, 3, 0, 0, 1, 4, 4, 5, 0, 6, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 2, 3, 0, 0, 1, 0, 0, 1, 0, 0, 63, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 2, 3, 0, 0, 1, 0, 0, 1, 0, 0, 15, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 2, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 2, 3, 0, 0, 1, 4, 4, 5, 0, 6, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 8, 9, 8, 8, 9, 8, 10, 11, 0, 0, 1, 12, 12, 13, 0, 14, 15, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 2, 3, 0, 0, 1, 4, 4, 5, 0, 6, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 2, 3, 0, 0, 1, 0, 0, 1, 0, 0, 31, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 2, 3, 0, 0, 1, 4, 4, 5, 0, 6, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 2, 3, 0, 0, 1, 0, 0, 1, 0, 0, 15, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 2, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 2, 3, 0, 0, 1, 4, 4, 5, 0, 6, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 8, 9, 8, 8, 9, 8, 10, 11, 0, 0, 1, 12, 12, 13, 0, 14, 15, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 2, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 16, 16, 17, 0, 16, 19, 0, 16, 17, 16, 16, 17, 16, 18, 19, 16, 16, 17, 20, 20, 21, 16, 22, 23, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 24, 25, 24, 24, 25, 24, 26, 27, 0, 0, 1, 28, 28, 29, 0, 30, 31, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 2, 3, 0, 0, 1, 4, 4, 5, 0, 6, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 2, 3, 0, 0, 1, 0, 0, 1, 0, 0, 15, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 32, 33, 32, 32, 33, 0, 34, 35, 0, 0, 1, 32, 32, 33, 0, 32, 39, 0, 0, 1, 32, 32, 33, 0, 32, 35, 0, 32, 33, 32, 32, 33, 32, 34, 35, 32, 32, 33, 36, 36, 37, 32, 38, 39, 0, 32, 33, 32, 32, 33, 32, 32, 35, 32, 40, 41, 40, 40, 41, 40, 42, 43, 32, 32, 33, 44, 44, 45, 32, 46, 47, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 2, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 48, 48, 49, 0, 48, 51, 0, 48, 49, 48, 48, 49, 48, 50, 51, 48, 48, 49, 52, 52, 53, 48, 54, 55, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 56, 57, 56, 56, 57, 56, 58, 59, 0, 0, 1, 60, 60, 61, 0, 62, 63, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 15, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 2, 3, 0, 0, 1, 0, 0, 1, 0, 0, 15, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 2, 3, 0, 0, 1, 4, 4, 5, 0, 6, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 2, 3, 0, 0, 1, 0, 0, 1, 0, 0, 31, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 2, 3, 0, 0, 1, 0, 0, 1, 0, 0, 15, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 2, 3, 0, 0, 1, 4, 4, 5, 0, 6, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 8, 9, 8, 8, 9, 8, 10, 11, 0, 0, 1, 12, 12, 13, 0, 14, 15, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 2, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 16, 16, 17, 0, 16, 19, 0, 16, 17, 16, 16, 17, 16, 18, 19, 16, 16, 17, 20, 20, 21, 16, 22, 23, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 24, 25, 24, 24, 25, 24, 26, 27, 0, 0, 1, 28, 28, 29, 0, 30, 31, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 2, 3, 0, 0, 1, 0, 0, 1, 0, 0, 15, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 2, 3, 0, 0, 1, 4, 4, 5, 0, 6, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 8, 9, 8, 8, 9, 8, 10, 11, 0, 0, 1, 12, 12, 13, 0, 14, 15, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 2, 3, 0, 0, 1, 4, 4, 5, 0, 6, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 2, 3, 0, 0, 1, 0, 0, 1, 0, 0, 127, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 15, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 2, 3, 0, 0, 1, 0, 0, 1, 0, 0, 15, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 2, 3, 0, 0, 1, 4, 4, 5, 0, 6, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 2, 3, 0, 0, 1, 0, 0, 1, 0, 0, 31, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 2, 3, 0, 0, 1, 4, 4, 5, 0, 6, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 2, 3, 0, 0, 1, 0, 0, 1, 0, 0, 15, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 2, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 2, 3, 0, 0, 1, 4, 4, 5, 0, 6, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 8, 9, 8, 8, 9, 8, 10, 11, 0, 0, 1, 12, 12, 13, 0, 14, 15, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 2, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 16, 16, 17, 0, 16, 19, 0, 16, 17, 16, 16, 17, 16, 18, 19, 16, 16, 17, 20, 20, 21, 16, 22, 23, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 24, 25, 24, 24, 25, 24, 26, 27, 0, 0, 1, 28, 28, 29, 0, 30, 31, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 2, 3, 0, 0, 1, 0, 0, 1, 0, 0, 15, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 2, 3, 0, 0, 1, 4, 4, 5, 0, 6, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 8, 9, 8, 8, 9, 8, 10, 11, 0, 0, 1, 12, 12, 13, 0, 14, 15, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 2, 3, 0, 0, 1, 4, 4, 5, 0, 6, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 2, 3, 0, 0, 1, 0, 0, 1, 0, 0, 63, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 2, 3, 0, 0, 1, 0, 0, 1, 0, 0, 15, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 2, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 2, 3, 0, 0, 1, 4, 4, 5, 0, 6, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 8, 9, 8, 8, 9, 8, 10, 11, 0, 0, 1, 12, 12, 13, 0, 14, 15, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 2, 3, 0, 0, 1, 4, 4, 5, 0, 6, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 2, 3, 0, 0, 1, 0, 0, 1, 0, 0, 31, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 2, 3, 0, 0, 1, 4, 4, 5, 0, 6, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 2, 3, 0, 0, 1, 0, 0, 1, 0, 0, 15, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 2, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 2, 3, 0, 0, 1, 4, 4, 5, 0, 6, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 8, 9, 8, 8, 9, 8, 10, 11, 0, 0, 1, 12, 12, 13, 0, 14, 15, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 2, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 16, 16, 17, 0, 16, 19, 0, 16, 17, 16, 16, 17, 16, 18, 19, 16, 16, 17, 20, 20, 21, 16, 22, 23, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 24, 25, 24, 24, 25, 24, 26, 27, 0, 0, 1, 28, 28, 29, 0, 30, 31, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 2, 3, 0, 0, 1, 4, 4, 5, 0, 6, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 2, 3, 0, 0, 1, 0, 0, 1, 0, 0, 15, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 32, 33, 32, 32, 33, 0, 34, 35, 0, 0, 1, 32, 32, 33, 0, 32, 39, 0, 0, 1, 32, 32, 33, 0, 32, 35, 0, 32, 33, 32, 32, 33, 32, 34, 35, 32, 32, 33, 36, 36, 37, 32, 38, 39, 0, 32, 33, 32, 32, 33, 32, 32, 35, 32, 40, 41, 40, 40, 41, 40, 42, 43, 32, 32, 33, 44, 44, 45, 32, 46, 47, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 2, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 48, 48, 49, 0, 48, 51, 0, 48, 49, 48, 48, 49, 48, 50, 51, 48, 48, 49, 52, 52, 53, 48, 54, 55, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 56, 57, 56, 56, 57, 56, 58, 59, 0, 0, 1, 60, 60, 61, 0, 62, 63, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 2, 3, 0, 0, 1, 0, 0, 1, 0, 0, 15, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 2, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 2, 3, 0, 0, 1, 4, 4, 5, 0, 6, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 8, 9, 8, 8, 9, 8, 10, 11, 0, 0, 1, 12, 12, 13, 0, 14, 15, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 2, 3, 0, 0, 1, 4, 4, 5, 0, 6, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 2, 3, 0, 0, 1, 0, 0, 1, 0, 0, 31, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 64, 64, 65, 0, 64, 67, 0, 64, 65, 64, 64, 65, 0, 66, 67, 0, 0, 1, 68, 68, 69, 0, 70, 71, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 64, 65, 64, 64, 65, 64, 66, 67, 0, 0, 1, 64, 64, 65, 0, 64, 79, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 64, 65, 64, 64, 65, 0, 66, 67, 0, 0, 1, 64, 64, 65, 0, 64, 71, 0, 0, 1, 64, 64, 65, 0, 64, 67, 0, 64, 65, 64, 64, 65, 64, 66, 67, 64, 64, 65, 68, 68, 69, 64, 70, 71, 0, 64, 65, 64, 64, 65, 64, 64, 67, 64, 72, 73, 72, 72, 73, 72, 74, 75, 64, 64, 65, 76, 76, 77, 64, 78, 79, 0, 0, 1, 64, 64, 65, 0, 64, 67, 0, 64, 65, 64, 64, 65, 64, 66, 67, 64, 64, 65, 64, 64, 65, 64, 64, 71, 64, 64, 65, 80, 80, 81, 64, 80, 83, 64, 80, 81, 80, 80, 81, 80, 82, 83, 80, 80, 81, 84, 84, 85, 80, 86, 87, 0, 64, 65, 64, 64, 65, 64, 64, 67, 64, 88, 89, 88, 88, 89, 88, 90, 91, 64, 64, 65, 92, 92, 93, 64, 94, 95, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 2, 3, 0, 0, 1, 4, 4, 5, 0, 6, 7, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 2, 3, 0, 0, 1, 0, 0, 1, 0, 0, 15, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 96, 97, 96, 96, 97, 0, 98, 99, 0, 0, 1, 96, 96, 97, 0, 96, 103, 0, 0, 1, 96, 96, 97, 0, 96, 99, 0, 96, 97, 96, 96, 97, 96, 98, 99, 96, 96, 97, 100, 100, 101, 96, 102, 103, 0, 96, 97, 96, 96, 97, 96, 96, 99, 96, 104, 105, 104, 104, 105, 104, 106, 107, 96, 96, 97, 108, 108, 109, 96, 110, 111, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 0, 1, 0, 0, 1, 0, 2, 3, 0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0, 1, 112, 112, 113, 0, 112, 115, 0, 112, 113, 112, 112, 113, 112, 114, 115, 112, 112, 113, 116, 116, 117, 112, 118, 119, 0, 0, 1, 0, 0, 1, 0, 0, 3, 0, 120, 121, 120, 120, 121, 120, 122, 123, 0, 0, 1, 124, 124, 125, 0, 126, 127, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 135, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 135, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 143, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 135, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 135, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 130, 131, 128, 128, 129, 128, 128, 129, 128, 128, 143, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 135, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 130, 131, 128, 128, 129, 132, 132, 133, 128, 134, 135, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 130, 131, 128, 128, 129, 128, 128, 129, 128, 128, 159, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 135, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 130, 131, 128, 128, 129, 132, 132, 133, 128, 134, 135, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 130, 131, 128, 128, 129, 128, 128, 129, 128, 128, 143, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 130, 131, 128, 128, 129, 128, 128, 129, 128, 128, 135, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 130, 131, 128, 128, 129, 132, 132, 133, 128, 134, 135, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 136, 137, 136, 136, 137, 136, 138, 139, 128, 128, 129, 140, 140, 141, 128, 142, 143, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 130, 131, 128, 128, 129, 128, 128, 129, 128, 128, 135, 128, 128, 129, 144, 144, 145, 128, 144, 147, 128, 144, 145, 144, 144, 145, 144, 146, 147, 144, 144, 145, 148, 148, 149, 144, 150, 151, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 152, 153, 152, 152, 153, 152, 154, 155, 128, 128, 129, 156, 156, 157, 128, 158, 159, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 135, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 135, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 130, 131, 128, 128, 129, 128, 128, 129, 128, 128, 143, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 135, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 130, 131, 128, 128, 129, 132, 132, 133, 128, 134, 135, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 136, 137, 136, 136, 137, 136, 138, 139, 128, 128, 129, 140, 140, 141, 128, 142, 143, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 135, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 130, 131, 128, 128, 129, 132, 132, 133, 128, 134, 135, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 130, 131, 128, 128, 129, 128, 128, 129, 128, 128, 191, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 135, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 135, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 130, 131, 128, 128, 129, 128, 128, 129, 128, 128, 143, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 130, 131, 128, 128, 129, 128, 128, 129, 128, 128, 135, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 130, 131, 128, 128, 129, 132, 132, 133, 128, 134, 135, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 136, 137, 136, 136, 137, 136, 138, 139, 128, 128, 129, 140, 140, 141, 128, 142, 143, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 135, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 130, 131, 128, 128, 129, 132, 132, 133, 128, 134, 135, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 130, 131, 128, 128, 129, 128, 128, 129, 128, 128, 159, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 135, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 130, 131, 128, 128, 129, 132, 132, 133, 128, 134, 135, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 130, 131, 128, 128, 129, 128, 128, 129, 128, 128, 143, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 130, 131, 128, 128, 129, 128, 128, 129, 128, 128, 135, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 130, 131, 128, 128, 129, 132, 132, 133, 128, 134, 135, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 136, 137, 136, 136, 137, 136, 138, 139, 128, 128, 129, 140, 140, 141, 128, 142, 143, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 130, 131, 128, 128, 129, 128, 128, 129, 128, 128, 135, 128, 128, 129, 144, 144, 145, 128, 144, 147, 128, 144, 145, 144, 144, 145, 144, 146, 147, 144, 144, 145, 148, 148, 149, 144, 150, 151, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 152, 153, 152, 152, 153, 152, 154, 155, 128, 128, 129, 156, 156, 157, 128, 158, 159, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 128, 135, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 130, 131, 128, 128, 129, 132, 132, 133, 128, 134, 135, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 130, 131, 128, 128, 129, 128, 128, 129, 128, 128, 143, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 160, 161, 160, 160, 161, 128, 162, 163, 128, 128, 129, 160, 160, 161, 128, 160, 167, 128, 128, 129, 160, 160, 161, 128, 160, 163, 128, 160, 161, 160, 160, 161, 160, 162, 163, 160, 160, 161, 164, 164, 165, 160, 166, 167, 128, 160, 161, 160, 160, 161, 160, 160, 163, 160, 168, 169, 168, 168, 169, 168, 170, 171, 160, 160, 161, 172, 172, 173, 160, 174, 175, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 128, 129, 128, 128, 129, 128, 130, 131, 128, 128, 129, 128, 128, 129, 128, 128, 135, 128, 128, 129, 176, 176, 177, 128, 176, 179, 128, 176, 177, 176, 176, 177, 176, 178, 179, 176, 176, 177, 180, 180, 181, 176, 182, 183, 128, 128, 129, 128, 128, 129, 128, 128, 131, 128, 184, 185, 184, 184, 185, 184, 186, 187, 128, 128, 129, 188, 188, 189, 128, 190, 191, 192, 192, 193, 192, 192, 193, 192, 192, 195, 192, 192, 193, 192, 192, 193, 192, 192, 195, 192, 192, 193, 192, 192, 193, 192, 192, 199, 192, 192, 193, 192, 192, 193, 192, 192, 195, 192, 192, 193, 192, 192, 193, 192, 192, 195, 192, 192, 193, 192, 192, 193, 192, 192, 199, 192, 192, 193, 192, 192, 193, 192, 192, 195, 192, 192, 193, 192, 192, 193, 192, 194, 195, 192, 192, 193, 192, 192, 193, 192, 192, 207, 192, 192, 193, 192, 192, 193, 192, 192, 195, 192, 192, 193, 192, 192, 193, 192, 194, 195, 192, 192, 193, 192, 192, 193, 192, 192, 199, 192, 192, 193, 192, 192, 193, 192, 192, 195, 192, 192, 193, 192, 192, 193, 192, 194, 195, 192, 192, 193, 196, 196, 197, 192, 198, 199, 192, 192, 193, 192, 192, 193, 192, 192, 195, 192, 200, 201, 200, 200, 201, 200, 202, 203, 192, 192, 193, 204, 204, 205, 192, 206, 207, 192, 192, 193, 192, 192, 193, 192, 192, 195, 192, 192, 193, 192, 192, 193, 192, 192, 195, 192, 192, 193, 192, 192, 193, 192, 192, 199, 192, 192, 193, 192, 192, 193, 192, 192, 195, 192, 192, 193, 192, 192, 193, 192, 194, 195, 192, 192, 193, 196, 196, 197, 192, 198, 199, 192, 192, 193, 192, 192, 193, 192, 192, 195, 192, 192, 193, 192, 192, 193, 192, 194, 195, 192, 192, 193, 192, 192, 193, 192, 192, 223, 192, 192, 193, 192, 192, 193, 192, 192, 195, 192, 192, 193, 192, 192, 193, 192, 192, 195, 192, 192, 193, 192, 192, 193, 192, 192, 199, 192, 192, 193, 192, 192, 193, 192, 192, 195, 192, 192, 193, 192, 192, 193, 192, 194, 195, 192, 192, 193, 196, 196, 197, 192, 198, 199, 192, 192, 193, 192, 192, 193, 192, 192, 195, 192, 192, 193, 192, 192, 193, 192, 194, 195, 192, 192, 193, 192, 192, 193, 192, 192, 207, 192, 192, 193, 192, 192, 193, 192, 192, 195, 192, 192, 193, 192, 192, 193, 192, 194, 195, 192, 192, 193, 192, 192, 193, 192, 192, 199, 192, 192, 193, 192, 192, 193, 192, 192, 195, 192, 192, 193, 192, 192, 193, 192, 194, 195, 192, 192, 193, 196, 196, 197, 192, 198, 199, 192, 192, 193, 192, 192, 193, 192, 192, 195, 192, 200, 201, 200, 200, 201, 200, 202, 203, 192, 192, 193, 204, 204, 205, 192, 206, 207, 192, 192, 193, 192, 192, 193, 192, 192, 195, 192, 192, 193, 192, 192, 193, 192, 194, 195, 192, 192, 193, 192, 192, 193, 192, 192, 199, 192, 192, 193, 208, 208, 209, 192, 208, 211, 192, 208, 209, 208, 208, 209, 208, 210, 211, 208, 208, 209, 212, 212, 213, 208, 214, 215, 192, 192, 193, 192, 192, 193, 192, 192, 195, 192, 216, 217, 216, 216, 217, 216, 218, 219, 192, 192, 193, 220, 220, 221, 192, 222, 223, 224, 224, 225, 224, 224, 225, 224, 224, 227, 224, 224, 225, 224, 224, 225, 224, 224, 227, 224, 224, 225, 224, 224, 225, 224, 224, 231, 224, 224, 225, 224, 224, 225, 224, 224, 227, 224, 224, 225, 224, 224, 225, 224, 226, 227, 224, 224, 225, 228, 228, 229, 224, 230, 231, 224, 224, 225, 224, 224, 225, 224, 224, 227, 224, 224, 225, 224, 224, 225, 224, 226, 227, 224, 224, 225, 224, 224, 225, 224, 224, 239, 224, 224, 225, 224, 224, 225, 224, 224, 227, 224, 224, 225, 224, 224, 225, 224, 226, 227, 224, 224, 225, 224, 224, 225, 224, 224, 231, 224, 224, 225, 224, 224, 225, 224, 224, 227, 224, 224, 225, 224, 224, 225, 224, 226, 227, 224, 224, 225, 228, 228, 229, 224, 230, 231, 224, 224, 225, 224, 224, 225, 224, 224, 227, 224, 232, 233, 232, 232, 233, 232, 234, 235, 224, 224, 225, 236, 236, 237, 224, 238, 239, 240, 240, 241, 240, 240, 241, 240, 240, 243, 240, 240, 241, 240, 240, 241, 240, 242, 243, 240, 240, 241, 240, 240, 241, 240, 240, 247, 240, 240, 241, 240, 240, 241, 240, 240, 243, 240, 240, 241, 240, 240, 241, 240, 242, 243, 240, 240, 241, 244, 244, 245, 240, 246, 247, 248, 248, 249, 248, 248, 249, 248, 248, 251, 248, 248, 249, 248, 248, 249, 248, 250, 251, 252, 252, 253, 252, 252, 253, 254, 254, 255 }; #endif // STABILITY
gpl-3.0
ClaudioNahmad/Servicio-Social
Parametros/CosmoMC/prerrequisitos/openmpi-2.0.2/ompi/mpi/fortran/mpif-h/pack_external_size_f.c
1
4029
/* * Copyright (c) 2004-2005 The Trustees of Indiana University and Indiana * University Research and Technology * Corporation. All rights reserved. * Copyright (c) 2004-2005 The University of Tennessee and The University * of Tennessee Research Foundation. All rights * reserved. * Copyright (c) 2004-2005 High Performance Computing Center Stuttgart, * University of Stuttgart. All rights reserved. * Copyright (c) 2004-2005 The Regents of the University of California. * All rights reserved. * Copyright (c) 2007-2012 Cisco Systems, Inc. All rights reserved. * Copyright (c) 2015 Research Organization for Information Science * and Technology (RIST). All rights reserved. * $COPYRIGHT$ * * Additional copyrights may follow * * $HEADER$ */ #include "ompi_config.h" #include "ompi/mpi/fortran/mpif-h/bindings.h" #include "ompi/constants.h" #include "ompi/communicator/communicator.h" #include "ompi/mpi/fortran/base/constants.h" #include "ompi/mpi/fortran/base/strings.h" #if OMPI_BUILD_MPI_PROFILING #if OPAL_HAVE_WEAK_SYMBOLS #pragma weak PMPI_PACK_EXTERNAL_SIZE = ompi_pack_external_size_f #pragma weak pmpi_pack_external_size = ompi_pack_external_size_f #pragma weak pmpi_pack_external_size_ = ompi_pack_external_size_f #pragma weak pmpi_pack_external_size__ = ompi_pack_external_size_f #pragma weak PMPI_Pack_external_size_f = ompi_pack_external_size_f #pragma weak PMPI_Pack_external_size_f08 = ompi_pack_external_size_f #else OMPI_GENERATE_F77_BINDINGS (PMPI_PACK_EXTERNAL_SIZE, pmpi_pack_external_size, pmpi_pack_external_size_, pmpi_pack_external_size__, pompi_pack_external_size_f, (char *datarep, MPI_Fint *incount, MPI_Fint *datatype, MPI_Aint *size, MPI_Fint *ierr, int datarep_len), (datarep, incount, datatype, size, ierr, datarep_len) ) #endif #endif #if OPAL_HAVE_WEAK_SYMBOLS #pragma weak MPI_PACK_EXTERNAL_SIZE = ompi_pack_external_size_f #pragma weak mpi_pack_external_size = ompi_pack_external_size_f #pragma weak mpi_pack_external_size_ = ompi_pack_external_size_f #pragma weak mpi_pack_external_size__ = ompi_pack_external_size_f #pragma weak MPI_Pack_external_size_f = ompi_pack_external_size_f #pragma weak MPI_Pack_external_size_f08 = ompi_pack_external_size_f #else #if ! OMPI_BUILD_MPI_PROFILING OMPI_GENERATE_F77_BINDINGS (MPI_PACK_EXTERNAL_SIZE, mpi_pack_external_size, mpi_pack_external_size_, mpi_pack_external_size__, ompi_pack_external_size_f, (char *datarep, MPI_Fint *incount, MPI_Fint *datatype, MPI_Aint *size, MPI_Fint *ierr, int datarep_len), (datarep, incount, datatype, size, ierr, datarep_len) ) #else #define ompi_pack_external_size_f pompi_pack_external_size_f #endif #endif void ompi_pack_external_size_f(char *datarep, MPI_Fint *incount, MPI_Fint *datatype, MPI_Aint *size, MPI_Fint *ierr, int datarep_len) { int ret, c_ierr; char *c_datarep; MPI_Datatype type = PMPI_Type_f2c(*datatype); /* Convert the fortran string */ if (OMPI_SUCCESS != (ret = ompi_fortran_string_f2c(datarep, datarep_len, &c_datarep))) { c_ierr = OMPI_ERRHANDLER_INVOKE(MPI_COMM_WORLD, ret, "MPI_PACK_EXTERNAL"); if (NULL != ierr) *ierr = OMPI_INT_2_FINT(c_ierr); return; } c_ierr = PMPI_Pack_external_size(c_datarep, OMPI_FINT_2_INT(*incount), type, size); if (NULL != ierr) *ierr = OMPI_INT_2_FINT(c_ierr); free(c_datarep); }
gpl-3.0
davidhorrocks/hoxs64
hoxs64/cvirwindow.cpp
1
25185
#include "cvirwindow.h" /*F+F+++F+++F+++F+++F+++F+++F+++F+++F+++F+++F+++F+++F+++F+++F+++F+++F+++F+++F Function: WindowProc Summary: Standard WindowProc callback function that forwards Windows messages on to the CVirWindow::WindowProc method. This Window procedure expects that it will receive a "this" pointer as the lpCreateParams member passed as part of the WM_NCCREATE message. It saves the "this" pointer in the GWL_USERDATA field of the window structure. Args: HWND hWnd, Window handle. UINT uMsg, Windows message. WPARAM wParam, First message parameter (word sized). LPARAM lParam); Second message parameter (long sized). Returns: LRESULT. Windows window procedure callback return value. F---F---F---F---F---F---F---F---F---F---F---F---F---F---F---F---F---F---F-F*/ LRESULT CALLBACK WindowProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { LRESULT lr; LRESULT br; // Get a pointer to the window class object. CVirWindow* pWin = (CVirWindow*)(LONG_PTR)GetWindowLongPtr(hWnd, GWLP_USERDATA); switch (uMsg) { case WM_NCCREATE: // Since this is the first time that we can get ahold of // a pointer to the window class object, all messages that might // have been sent before this are never seen by the Windows object // and only get passed on to the DefWindowProc // Get the initial creation pointer to the window object pWin = (CVirWindow*)((CREATESTRUCT*)lParam)->lpCreateParams; // Set it's protected m_hWnd member variable to ensure that // member functions have access to the correct window handle. pWin->m_hWnd = hWnd; // Set its USERDATA to point to the window object #pragma warning(disable:4244) SetWindowLongPtr(hWnd, GWLP_USERDATA, (LONG_PTR)pWin); #pragma warning(default:4244) br = (BOOL)pWin->WindowProc(hWnd, uMsg, wParam, lParam); if (br) { //pWin->m_pKeepAlive = pWin->shared_from_this(); return br; } else { SetWindowLongPtr(hWnd, GWLP_USERDATA, 0); return FALSE; } break; case WM_NCDESTROY: // This is our signal to destroy the window object. if (pWin) { lr = pWin->WindowProc(hWnd, uMsg, wParam, lParam); SetWindowLongPtr(hWnd, GWLP_USERDATA, 0); pWin->m_hWnd = 0; //pWin->m_pKeepAlive.reset(); pWin->WindowRelease(); pWin = 0; return lr; } break; default: break; } // Call its message proc method. if (NULL != pWin) return (pWin->WindowProc(hWnd, uMsg, wParam, lParam)); else return (DefWindowProc(hWnd, uMsg, wParam, lParam)); } LRESULT CALLBACK MdiFrameWindowProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { LRESULT lr; LRESULT br; // Get a pointer to the window class object. CVirMdiFrameWindow* pWin = reinterpret_cast<CVirMdiFrameWindow*>((LONG_PTR)GetWindowLongPtr(hWnd, GWLP_USERDATA)); switch (uMsg) { case WM_NCCREATE: // Since this is the first time that we can get ahold of // a pointer to the window class object, all messages that might // have been sent before this are never seen by the Windows object // and only get passed on to the DefWindowProc // Get the initial creation pointer to the window object pWin = (CVirMdiFrameWindow*)((CREATESTRUCT*)lParam)->lpCreateParams; // Set it's protected m_hWnd member variable to ensure that // member functions have access to the correct window handle. pWin->m_hWnd = hWnd; // Set its USERDATA to point to the window object #pragma warning(disable:4244) SetWindowLongPtr(hWnd, GWLP_USERDATA, (LONG_PTR)pWin); #pragma warning(default:4244) br = (BOOL)pWin->MdiFrameWindowProc(hWnd, pWin->m_hWndMDIClient, uMsg, wParam, lParam); if (br) { //pWin->m_pKeepAlive = pWin->shared_from_this(); return br; } else { SetWindowLongPtr(hWnd, GWLP_USERDATA, 0); return FALSE; } break; case WM_DESTROY: if (pWin) { lr = pWin->MdiFrameWindowProc(hWnd, pWin->m_hWndMDIClient, uMsg, wParam, lParam); pWin->m_hWndMDIClient = 0; return lr; } break; case WM_NCDESTROY: // This is our signal to destroy the window object. if (pWin) { lr = pWin->MdiFrameWindowProc(hWnd, pWin->m_hWndMDIClient, uMsg, wParam, lParam); SetWindowLongPtr(hWnd, GWLP_USERDATA, 0); pWin->m_hWnd = 0; //pWin->m_pKeepAlive.reset(); pWin->WindowRelease(); pWin = nullptr; return lr; } break; default: break; } // Call its message proc method. if (NULL != pWin) return (pWin->MdiFrameWindowProc(hWnd, pWin->m_hWndMDIClient, uMsg, wParam, lParam)); else return (DefFrameProc(hWnd, 0, uMsg, wParam, lParam)); } LRESULT CALLBACK MdiChildWindowProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { LRESULT lr; LRESULT br; MDICREATESTRUCT* pMdiCreateStruct; // Get a pointer to the window class object. CVirMdiChildWindow* pWin = (CVirMdiChildWindow*)(LONG_PTR)GetWindowLongPtr(hWnd, GWLP_USERDATA); switch (uMsg) { case WM_NCCREATE: // Since this is the first time that we can get ahold of // a pointer to the window class object, all messages that might // have been sent before this are never seen by the Windows object // and only get passed on to the DefWindowProc // Get the initial creation pointer to the window object pMdiCreateStruct = (MDICREATESTRUCT*)((CREATESTRUCT*)lParam)->lpCreateParams; pWin = (CVirMdiChildWindow*)pMdiCreateStruct->lParam; // Set it's protected m_hWnd member variable to ensure that // member functions have access to the correct window handle. pWin->m_hWnd = hWnd; // Set its USERDATA to point to the window object #pragma warning(disable:4244) SetWindowLongPtr(hWnd, GWLP_USERDATA, (LONG_PTR)pWin); #pragma warning(default:4244) br = (BOOL)pWin->WindowProc(hWnd, uMsg, wParam, lParam); if (br) { //pWin->m_pKeepAlive = pWin->shared_from_this(); return br; } else { SetWindowLongPtr(hWnd, GWLP_USERDATA, 0); return FALSE; } break; case WM_NCDESTROY: // This is our signal to destroy the window object. if (pWin) { lr = pWin->WindowProc(hWnd, uMsg, wParam, lParam); SetWindowLongPtr(hWnd, GWLP_USERDATA, 0); pWin->m_hWnd = 0; //pWin->m_pKeepAlive.reset(); pWin->WindowRelease(); pWin = 0; return lr; } break; default: break; } // Call its message proc method. if (NULL != pWin) return (pWin->WindowProc(hWnd, uMsg, wParam, lParam)); else return (DefMDIChildProc(hWnd, uMsg, wParam, lParam)); } LRESULT CALLBACK GlobalSubClassWindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { CVirWindow* pWin = NULL; if (hWnd != NULL) { pWin = (CVirWindow*)(LONG_PTR)GetWindowLongPtr(hWnd, GWLP_USERDATA); if (NULL != pWin) return (pWin->SubclassWindowProc(hWnd, uMsg, wParam, lParam)); } return 0; } WNDPROC CBaseVirWindow::SubclassChildWindow(HWND hWnd) { #pragma warning(disable:4244) SetWindowLongPtr(hWnd, GWLP_USERDATA, (LONG_PTR)this); WNDPROC pOldProc = (WNDPROC)(LONG_PTR)SetWindowLongPtr(hWnd, GWLP_WNDPROC, (LONG_PTR) ::GlobalSubClassWindowProc); #pragma warning(default:4244) return pOldProc; } WNDPROC CBaseVirWindow::SubclassChildWindow(HWND hWnd, WNDPROC proc) { #pragma warning(disable:4244) SetWindowLongPtr(hWnd, GWLP_USERDATA, (LONG_PTR)this); WNDPROC pOldProc = (WNDPROC)(LONG_PTR)SetWindowLongPtr(hWnd, GWLP_WNDPROC, (LONG_PTR)proc); #pragma warning(default:4244) return pOldProc; } LRESULT CBaseVirWindow::SubclassWindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { return 0; } int CBaseVirWindow::SetSize(int w, int h) { return (int)SetWindowPos(m_hWnd, HWND_NOTOPMOST, 0, 0, w, h, SWP_NOMOVE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOACTIVATE); } /*M+M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M Method: CVirWindow::Create Summary: Envelopes the Windows' CreateWindow call. Uses its window-creation data pointer to pass the 'this' pointer. Args: LPTSTR lpszClassName, Address of registered class name. LPTSTR lpszWindowName, Address of window name/title. DWORD dwStyle, Window style. int x, Horizontal position of window. int y, Vertical position of window. int nWidth, Window width. int nHeight, Window height. HWND hwndParent, Handle of parent or owner window. HMENU hmenu, Handle of menu, or child window identifier. HINSTANCE hinst) Handle of application instance. Modifies: m_hWnd, m_hInst. Returns: HWND (Window handle) of the created window. M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M-M*/ HWND CVirWindow::CreateVirWindow( DWORD dwExStyle, LPCTSTR lpszClassName, LPCTSTR lpszWindowName, DWORD dwStyle, int x, int y, int nWidth, int nHeight, HWND hWndParent, HMENU hMenu, HINSTANCE hInst) { // Remember the passed instance handle in a member variable of the // C++ Window object. m_hInst = hInst; // Call the Win32 API to create the window. m_hWnd = ::CreateWindowEx( dwExStyle, lpszClassName, lpszWindowName, dwStyle, x, y, nWidth, nHeight, hWndParent, hMenu, hInst, this); return (m_hWnd); } void CVirWindow::GetMinWindowSize(int& w, int& h) { w = 0; h = 0; } HWND CVirMdiFrameWindow::CreateMDIClientWindow(UINT clientId, UINT firstChildId, int iWindowMenuIndex) { CLIENTCREATESTRUCT ccs; // Retrieve the handle to the window menu and assign the // first child window identifier. ZeroMemory(&ccs, sizeof(ccs)); ccs.hWindowMenu = GetSubMenu(GetMenu(m_hWnd), iWindowMenuIndex); ccs.idFirstChild = firstChildId; // Create the MDI client window. m_hWndMDIClient = ::CreateWindowEx(0, TEXT("MDICLIENT"), (LPCTSTR)NULL, WS_CHILD | WS_CLIPCHILDREN | WS_VSCROLL | WS_HSCROLL | WS_VISIBLE, 0, 0, 0, 0, m_hWnd, (HMENU)LongToPtr(clientId), m_hInst, (LPSTR)&ccs); return m_hWndMDIClient; } /*F+F+++F+++F+++F+++F+++F+++F+++F+++F+++F+++F+++F+++F+++F+++F+++F+++F+++F+++F Function: DialogProc Summary: The general dialog procedure callback function. Used by all CVirDialog class objects. This procedure is the DialogProc. registered for all dialogs created with the CVirDialog class. It uses the parameter passed with the WM_INITDIALOG message to identify the dialog classes' "this" pointer which it then stores in the window structure's GWL_USERDATA field. All subsequent messages can then be forwarded on to the correct dialog class's DialogProc method by using the pointer stored in the GWL_USERDATA field. Args: HWND hWndDlg, Handle of dialog box. UINT uMsg, Message. WPARAM wParam, First message parameter (word sized). LPARAM lParam); Second message parameter (long sized). Returns: BOOL. Return of the CVirDialog::DialogProc method. F---F---F---F---F---F---F---F---F---F---F---F---F---F---F---F---F---F---F-F*/ INT_PTR CALLBACK DialogProc( HWND hWndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) { // Get a pointer to the window class object. CVirDialog* pdlg = (CVirDialog*)(LONG_PTR)GetWindowLongPtr(hWndDlg, GWLP_USERDATA); BOOL br; switch (uMsg) { case WM_INITDIALOG: // Get a pointer to the window class object. pdlg = (CVirDialog*)lParam; #pragma warning(disable:4244) SetWindowLongPtr(hWndDlg, GWLP_USERDATA, (LONG_PTR)pdlg); #pragma warning(default:4244) pdlg->m_hWnd = hWndDlg; br = pdlg->DialogProc(hWndDlg, uMsg, wParam, lParam); if (br) { //pdlg->m_pKeepAlive = pdlg->shared_from_this(); return br; } else { SetWindowLongPtr(hWndDlg, GWLP_USERDATA, 0); return FALSE; } // Set the USERDATA to point to the class object. break; case WM_NCDESTROY: // This is our signal to destroy the window object. if (pdlg) { LRESULT lr = pdlg->DialogProc(hWndDlg, uMsg, wParam, lParam); SetWindowLongPtr(hWndDlg, GWLP_USERDATA, 0); pdlg->m_hWnd = 0; //pdlg->m_pKeepAlive.reset(); pdlg->WindowRelease(); pdlg = 0; return lr; } break; default: break; } // Call its message proc method. if (pdlg != (CVirDialog*)0) return (pdlg->DialogProc(hWndDlg, uMsg, wParam, lParam)); else return (FALSE); } CVirDialog::CVirDialog() noexcept { m_bIsModeless = false; m_hInst = NULL; m_hWnd = NULL; } /*M+M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M Method: CVirDialog::ShowDialog Summary: Creates the dialog so that it's DialogProc member function can be invoked. The dialog box object exists until deleted by the caller. It can be shown any number of times. This function is analgous to Windows' DialogBox function. The main difference being that you don't specify a DialogProc; you override the pure virtal function CVirDialog::DialogProc. Args: HINSTANCE hInst, Handle of the module instance. Needed to specify the module instance for fetching the dialog template resource (ie, from either a host EXE or DLL). LPTSTR lpszTemplate, Identifies the dialog box template. HWND hwndOwner) Handle of the owner window. Modifies: m_hInst. Returns: Return value from the DialogBoxParam Windows API function. M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M-M*/ INT_PTR CVirDialog::ShowDialog( HINSTANCE hInst, LPTSTR lpszTemplate, HWND hWndOwner) { INT_PTR iResult; // Assign the module instance handle in the Dialog object. m_hInst = hInst; // Create and show the dialog on screen. Load the dialog resource // from the specified module instance (could be a module other than // that of the EXE that is running--the resources could be in a DLL // that is calling this ShowDialog). Pass the 'this' pointer to the // dialog object so that it can be assigned inside the dialog object // during WM_INITDIALOG and later available to the dailog procedure // via the GWL_USERDATA associated with the dialog window. iResult = ::DialogBoxParam( hInst, lpszTemplate, hWndOwner, (DLGPROC)::DialogProc, (LPARAM)this); return (iResult); } /*M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M-M*/ HWND CVirDialog::ShowModelessDialog( HINSTANCE hInst, LPCTSTR szTemplate, HWND hWndOwner) { HWND iResult; m_bIsModeless = true; m_hInst = hInst; iResult = ::CreateDialogParam( hInst, szTemplate, hWndOwner, (DLGPROC)::DialogProc, (LPARAM)this); return (iResult); } /*M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M-M*/ HWND CVirDialog::ShowModelessDialogIndirect( HINSTANCE hInst, LPCDLGTEMPLATE lpTemplate, HWND hWndOwner) { HWND iResult; m_bIsModeless = true; m_hInst = hInst; iResult = ::CreateDialogIndirectParam( hInst, lpTemplate, hWndOwner, (DLGPROC)::DialogProc, (LPARAM)this); return (iResult); } /**************************************************************************/ CTabPageDialog::CTabPageDialog() noexcept { m_hInst = 0; m_hWnd = 0; m_lpTemplate = 0; m_lpTemplateEx = 0; m_pagetext = nullptr; m_bIsCreated = false; m_pageindex = 0; m_dlgId = 0; m_owner = nullptr; } CTabPageDialog::~CTabPageDialog() noexcept { if (m_pagetext) { delete[] m_pagetext; m_pagetext = NULL; } } HRESULT CTabPageDialog::init(CTabDialog* owner, int dlgId, LPTSTR szText, int pageindex) { m_owner = owner; m_dlgId = dlgId; m_pageindex = pageindex; m_pagetext = new TCHAR[lstrlen(szText) + 1]; if (m_pagetext == NULL) return E_OUTOFMEMORY; lstrcpy(m_pagetext, szText); m_lpTemplate = G::DoLockDlgRes(m_hInst, MAKEINTRESOURCE(dlgId)); if (m_lpTemplate) { m_lpTemplateEx = (LPCDLGTEMPLATEEX)m_lpTemplate; if (m_lpTemplateEx->signature == 0xffff) m_lpTemplate = 0; else m_lpTemplateEx = 0; return S_OK; } else return E_FAIL; } BOOL CTabPageDialog::DialogProc(HWND hWndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) { return m_owner->OnPageEvent(this, hWndDlg, uMsg, wParam, lParam); } /**************************************************************************/ CTabDialog::CTabDialog() noexcept { m_hwndDisplay = 0; m_hWnd = 0; m_hInst = 0; m_hwndTab = 0; m_tabctl_id = 0; m_current_page_index = -1; m_rcDisplay = { 0,0,0,0 }; } CTabDialog::~CTabDialog() { FreePages(); } void CTabDialog::FreePages() noexcept { m_vecpages.clear(); } INT_PTR CTabDialog::ShowDialog(HINSTANCE hInst, LPTSTR lpszTemplate, HWND hWndOwner) { INT_PTR iResult; // Assign the module instance handle in the Dialog object. m_hInst = hInst; iResult = ::DialogBoxParam(hInst, lpszTemplate, hWndOwner, (DLGPROC)::DialogProc, (LPARAM)this); return (iResult); } void CTabDialog::SetTabID(int tabctl_id) { m_tabctl_id = tabctl_id; } HRESULT CTabDialog::SetPages(int pagecount, struct tabpageitem* pageitem) { int i; HRESULT hr; FreePages(); m_vecpages.reserve(pagecount); if (m_vecpages.capacity() == 0) return E_OUTOFMEMORY; for (i = 0; i < pagecount; i++) { shared_ptr<CTabPageDialog> pTabPageDialog = shared_ptr<CTabPageDialog>(new CTabPageDialog()); if (pTabPageDialog == 0) { FreePages(); return E_OUTOFMEMORY; } m_vecpages.push_back(pTabPageDialog); hr = m_vecpages[i]->init(this, pageitem[i].pageid, pageitem[i].lpszText, i); if (FAILED(hr)) { FreePages(); return hr; } } return S_OK; } BOOL CTabDialog::OnChildDialogInit(HWND hwndDlg) { HWND hwndParent = GetParent(hwndDlg); if (hwndParent == NULL) { return FALSE; } SetWindowPos(hwndDlg, HWND_TOP, m_rcDisplay.left, m_rcDisplay.top, 0, 0, SWP_NOSIZE); return TRUE; } BOOL CTabDialog::OnTabbedDialogInit(HWND hwndDlg) { DWORD dwDlgBase = GetDialogBaseUnits(); TCITEM tie; RECT rcTab, rcTemp; HWND hwndButtonOK; HWND hwndButtonCancel; RECT rcButtonOK; RECT rcButtonCancel; SIZE sizeButtonOK = { 0 , 0 }; SIZE sizeButtonCancel = { 0 , 0 }; size_t i; BOOL bResult = FALSE; const LONG DialogMargin = 2; // Create the tab control. InitCommonControls(); if (m_tabctl_id) { m_hwndTab = GetDlgItem(hwndDlg, m_tabctl_id); if (m_hwndTab == NULL) { return FALSE; } } else return FALSE; SetRectEmpty(&rcTemp); rcTemp.right = DialogMargin; rcTemp.bottom = DialogMargin; MapDialogRect(hwndDlg, &rcTemp); int cxMargin = abs(rcTemp.right - rcTemp.left); int cyMargin = abs(rcTemp.bottom - rcTemp.top); // Add a tab for each of the three child dialog boxes. if (m_vecpages.size() > 0) { for (i = m_vecpages.size(); i > 0; i--) { tie.mask = TCIF_TEXT | TCIF_IMAGE; tie.iImage = -1; tie.pszText = m_vecpages[i - 1]->m_pagetext; TabCtrl_InsertItem(m_hwndTab, 0, &tie); } } // Lock the resources for the three child dialog boxes. //apRes[0] = DoLockDlgRes(m_hInst, MAKEINTRESOURCE(IDD_KEYPAGE1)); // Determine the bounding rectangle for all child dialog boxes. SetRectEmpty(&rcTab); for (i = 0; i < m_vecpages.size(); i++) { if (m_vecpages[i]->m_lpTemplate != 0) { if (m_vecpages[i]->m_lpTemplate->cx > rcTab.right) rcTab.right = m_vecpages[i]->m_lpTemplate->cx; if (m_vecpages[i]->m_lpTemplate->cy > rcTab.bottom) rcTab.bottom = m_vecpages[i]->m_lpTemplate->cy; } else if (m_vecpages[i]->m_lpTemplateEx != 0) { if (m_vecpages[i]->m_lpTemplateEx->cx > rcTab.right) rcTab.right = m_vecpages[i]->m_lpTemplateEx->cx; if (m_vecpages[i]->m_lpTemplateEx->cy > rcTab.bottom) rcTab.bottom = m_vecpages[i]->m_lpTemplateEx->cy; } } MapDialogRect(hwndDlg, &rcTab); // Calculate how large to make the tab control, so // the display area can accommodate all the child dialog boxes. TabCtrl_AdjustRect(m_hwndTab, TRUE, &rcTab); OffsetRect(&rcTab, cxMargin - rcTab.left, cyMargin - rcTab.top); // Calculate the display rectangle. CopyRect(&m_rcDisplay, &rcTab); TabCtrl_AdjustRect(m_hwndTab, FALSE, &m_rcDisplay); // Set the size and position of the tab control, buttons, // and dialog box. SetWindowPos(m_hwndTab, NULL, rcTab.left, rcTab.top, rcTab.right - rcTab.left, rcTab.bottom - rcTab.top, SWP_NOZORDER); hwndButtonOK = GetDlgItem(hwndDlg, IDOK); if (hwndButtonOK) { GetWindowRect(hwndButtonOK, &rcButtonOK); sizeButtonOK.cx = rcButtonOK.right - rcButtonOK.left; sizeButtonOK.cy = rcButtonOK.bottom - rcButtonOK.top; } hwndButtonCancel = GetDlgItem(hwndDlg, IDCANCEL); if (hwndButtonCancel) { GetWindowRect(hwndButtonCancel, &rcButtonCancel); sizeButtonCancel.cx = rcButtonCancel.right - rcButtonCancel.left; sizeButtonCancel.cy = rcButtonCancel.bottom - rcButtonCancel.top; } if (false) { // Move the OK button below the tab control. if (hwndButtonOK) { SetWindowPos(hwndButtonOK, NULL, rcTab.left, rcTab.bottom + cyMargin, 0, 0, SWP_NOSIZE | SWP_NOZORDER); // Move the Cancel button to the right of the OK. if (hwndButtonCancel) { SetWindowPos(hwndButtonCancel, NULL, rcTab.left + sizeButtonOK.cx + cxMargin, rcTab.bottom + cyMargin, 0, 0, SWP_NOSIZE | SWP_NOZORDER); } } } else { if (hwndButtonCancel) { // Move the Cancel button below the tab control. SetWindowPos(hwndButtonCancel, NULL, rcTab.right - sizeButtonCancel.cx, rcTab.bottom + cyMargin, 0, 0, SWP_NOSIZE | SWP_NOZORDER); if (hwndButtonOK) { // Move the OK button to the left of the Cancel. SetWindowPos(hwndButtonOK, NULL, rcTab.right - sizeButtonCancel.cx - sizeButtonOK.cx - cxMargin, rcTab.bottom + cyMargin, 0, 0, SWP_NOSIZE | SWP_NOZORDER); } } } DWORD dwStyle = GetWindowLongW(hwndDlg, GWL_STYLE); DWORD dwStyleEx = GetWindowLongW(hwndDlg, GWL_EXSTYLE); RECT rcFrame; CopyRect(&rcFrame, &rcTab); AdjustWindowRectEx(&rcFrame, dwStyle, FALSE, dwStyleEx); // Size the dialog box. SetWindowPos(hwndDlg, NULL, 0, 0, rcFrame.right - rcFrame.left + 2 * cxMargin, rcFrame.bottom - rcFrame.top + sizeButtonOK.cy + 3 * cyMargin, SWP_NOMOVE | SWP_NOZORDER); // Simulate selection of the first item. TabCtrl_SetCurSel(m_hwndTab, 0); return OnSelChanged(hwndDlg); } BOOL CTabDialog::OnSelChanged(HWND hwndDlg) { size_t iSel; // Destroy the current child dialog box, if any. if (IsWindow(m_hwndDisplay)) { ShowWindow(m_hwndDisplay, SW_HIDE); //UpdateWindow(m_hwndDisplay); } m_hwndDisplay = NULL; iSel = m_current_page_index = TabCtrl_GetCurSel(m_hwndTab); if (iSel >= m_vecpages.size()) return FALSE; if (!m_vecpages[iSel]->m_bIsCreated) { // Create the new child dialog box. if (m_vecpages[iSel]->m_lpTemplate != 0) m_hwndDisplay = CreateDialogIndirectParam(m_hInst, m_vecpages[iSel]->m_lpTemplate, hwndDlg, ::DialogProc, (LPARAM)(this->m_vecpages[iSel].get())); else if (m_vecpages[iSel]->m_lpTemplateEx != 0) m_hwndDisplay = CreateDialogIndirectParam(m_hInst, (LPCDLGTEMPLATE)m_vecpages[iSel]->m_lpTemplateEx, hwndDlg, ::DialogProc, (LPARAM)(this->m_vecpages[iSel].get())); if (m_hwndDisplay) m_vecpages[iSel]->m_bIsCreated = true; } else { m_hwndDisplay = m_vecpages[iSel]->m_hWnd; } if (m_hwndDisplay != NULL) { RECT rcDisplay; ZeroMemory(&rcDisplay, sizeof(rcDisplay)); if (GetWindowRect(m_hwndTab, &rcDisplay)) { if (ScreenToClient(m_hwndTab, (LPPOINT)&rcDisplay.left)) { if (ScreenToClient(m_hwndTab, (LPPOINT)&rcDisplay.right)) { TabCtrl_AdjustRect(m_hwndTab, FALSE, &rcDisplay); SetWindowPos(m_hwndDisplay, NULL, rcDisplay.left, rcDisplay.top, rcDisplay.right - rcDisplay.left, rcDisplay.bottom - rcDisplay.top, SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOMOVE); } } } ShowWindow(m_hwndDisplay, SW_SHOW); //UpdateWindow(m_hwndDisplay); } if (m_hwndDisplay) return TRUE; else return FALSE; } shared_ptr<CTabPageDialog> CTabDialog::GetPage(int i) { return m_vecpages[i]; } HRESULT CTabDialog::CreateAllPages() { size_t i; HRESULT hr = S_OK; HWND hWnd = nullptr; for (i = 0; i < m_vecpages.size(); i++) { if (!m_vecpages[i]->m_bIsCreated) { if (m_vecpages[i]->m_lpTemplate != 0) { hWnd = CreateDialogIndirectParam(m_hInst, m_vecpages[i]->m_lpTemplate, m_hWnd, ::DialogProc, (LPARAM)(this->m_vecpages[i].get())); } else if (m_vecpages[i]->m_lpTemplateEx != 0) { hWnd = CreateDialogIndirectParam(m_hInst, (LPCDLGTEMPLATE)m_vecpages[i]->m_lpTemplateEx, m_hWnd, ::DialogProc, (LPARAM)(this->m_vecpages[i].get())); } if (hWnd) { m_vecpages[i]->m_bIsCreated = true; ShowWindow(hWnd, SW_HIDE); } else { hr = E_FAIL; } } } return hr; }
gpl-3.0
pLinkSS/pLink-SS
ProteinIndex/CTermOnlineDigestion.cpp
1
15481
#include "MSufSort.h" #include "../include/sdk.h" #include "../include/option.h" #include "CTermOnlineDigestion.h" namespace ProteinIndex { CCTermOnlineDigestion::CCTermOnlineDigestion() { m_chDat = 0;LCP = 0;SA = 0;nClvy = 0;m_tMass =0; beg = 0; } CCTermOnlineDigestion::~CCTermOnlineDigestion() { Close(); } inline bool CCTermOnlineDigestion::_IsDiv(size_t p) { return DIVPEP == m_chDat[p]; } inline bool CCTermOnlineDigestion::_IsEnzyme(size_t p) { return (string::npos != m_strCleave.find(m_chDat[p]) ); } inline bool CCTermOnlineDigestion::_IsLeftTerm(size_t p) { return DIVPEP == m_chDat[p] || ('M' == m_chDat[p] && DIVPEP == m_chDat[p -1]) ; } inline bool CCTermOnlineDigestion::_IsRightTerm(size_t p) { return (DIVPEP == m_chDat[p + 1]); } inline bool CCTermOnlineDigestion::_IsLeft(size_t p)//todo { return ( _IsLeftTerm(p) || _IsEnzyme(p)); } inline bool CCTermOnlineDigestion::_IsRight(size_t p) { return (_IsRightTerm(p) || _IsEnzyme(p)); } inline bool CCTermOnlineDigestion::_IsPep(size_t s, size_t e) { size_t l = e - s + 1, Mass = (m_tMass[e] + (m_tMassMod - m_tMass[s - 1])) & m_tMassMod ; return (l >= m_pIndexItem.tMinPepLength && l <= m_pIndexItem.tMaxPepLength && Mass >= m_pIndexItem.tMinPepMass && Mass <= m_pIndexItem.tMaxPepMass ); } bool CCTermOnlineDigestion::InitPara(PINDEX_HEAD &pIndexHead,PINDEX_ITEM &pIndexItem, CMetaHandler &pMetaHandler) { m_pIndexHead = pIndexHead; m_pIndexItem = pIndexItem; m_pMetaHandler = pMetaHandler; if(m_pIndexItem.tMinPepMass < DEFAULT_MULTPLIER ) { m_pIndexItem.tMinPepMass *= DEFAULT_MULTPLIER; m_pIndexItem.tMaxPepMass *= DEFAULT_MULTPLIER; } CEnzymeConf enzyme_conf(m_pIndexHead.stEnzymeList); if(!enzyme_conf.GetEnzyme(m_pIndexItem.vtEnzymeNames[0], enzyme)) { proteomics_sdk::CErrInfo err_info("CCTermOnlineDigestion", "InitPara","Can't get enzyme!"); throw runtime_error(err_info.Get().c_str()); } m_strCleave = enzyme.GetCleaveString(); m_strNotCleave = enzyme.GetNotCleave(); //cout << "m_strCleave:" << m_strCleave << endl; CPepCalcFunc PepFunc; PepFunc.Init(m_pIndexHead.strAAList); m_tAAMass = new size_t[200]; m_tAAMass[(int)DIVPEP] = 0; for(size_t t = 0; t < 26; ++t) { m_tAAMass[t + 'A'] = size_t( PepFunc.GetfAAMass((char)(t + 'A'), m_pIndexItem.bMono) * DEFAULT_MULTPLIER + 0.5); } m_uCurFileID = -1; } bool CCTermOnlineDigestion::Close() { _DeleteAll(); } void CCTermOnlineDigestion::_DeleteAll() { try { if(NULL != m_chDat) { delete[] m_chDat; m_chDat = 0; } if(NULL != LCP) { delete[] LCP; LCP = 0; } if(NULL != SA) { delete[] SA; SA = 0; } if(NULL != nClvy) { delete[] nClvy; nClvy = 0; } if(NULL != m_tMass) { delete[] m_tMass; m_tMass = 0; } if(NULL != beg) { delete[] beg; beg = 0; } } catch(runtime_error &e) { proteomics_sdk::CErrInfo err_info("CCTermOnlineDigestion", "_DeleteAll"); throw runtime_error(err_info.Get(e).c_str()); } catch(...) { proteomics_sdk::CErrInfo err_info("CCTermOnlineDigestion", "_DeleteAll","Unknown Error!"); throw runtime_error(err_info.Get().c_str()); } } bool CCTermOnlineDigestion::GetNextAllPro(size_t tSufType) { size_t clt = clock(); cout << "GetNextAllPro is Begin..." << endl; if(++m_uCurFileID >= m_pMetaHandler.m_uFastaNum) return false; FILE *f = fopen(m_pMetaHandler.GenerFileName((uchar)m_uCurFileID,PRO_SQ_EXT).c_str(), "rb"); if(NULL == f) return false; fseek(f, 0, SEEK_END); m_tLen = ftell(f); switch(tSufType) { case 0: m_chDat = new uchar[m_tLen + 10]; break; case 3: m_chDat = new uchar[(m_tLen + 4) * 6 + 10]; break; default: m_chDat = new uchar[m_tLen + 10]; break; } fseek(f, 0, SEEK_SET); fread(m_chDat, sizeof(char), m_tLen, f); m_chDat[m_tLen] = 0; fclose(f); cout << "GetNextAllPro is end, the time is:" << clock() - clt << endl << endl; return true; } bool CCTermOnlineDigestion::GetNextBeg() { m_tNum = m_pMetaHandler.m_vmItems[m_uCurFileID].tEnd - m_pMetaHandler.m_vmItems[m_uCurFileID].tBeg; size_t tn = 3 * ( m_tNum + 1); FILE *f = fopen(m_pMetaHandler.GenerFileName((uchar)m_uCurFileID,PRO_IDX_EXT).c_str(), "rb"); if(NULL == f) return false; long *tmp = new long[tn]; beg = new size_t[tn]; fread(tmp,sizeof(long), tn , f); for(size_t t =2; t < tn; t += 3) { beg[t/3] = tmp[t]; } delete[] tmp;tmp = 0; fclose(f); return true; } bool CCTermOnlineDigestion::GetNextLCP() { FILE *fl = NULL; switch(m_pIndexItem.nCleaveWay) { case 0: fl = fopen(m_pMetaHandler.GenerFileName((uchar)m_uCurFileID,PRO_SQ_0_LCP).c_str(), "rb"); if(NULL == fl) return false; LCP = new uchar[m_tLen + 2]; fread(LCP, sizeof(uchar), m_tLen, fl); break; case 1: fl = fopen(m_pMetaHandler.GenerFileName((uchar)m_uCurFileID,PRO_SQ_2_LCP).c_str(), "rb"); if(NULL == fl) return false; LCP = new uchar[m_tLen + 2]; fread(LCP, sizeof(uchar), m_tLen, fl); break; case 2: fl = fopen(m_pMetaHandler.GenerFileName((uchar)m_uCurFileID,PRO_SQ_2_LCP).c_str(), "rb"); if(NULL == fl) return false; LCP = new uchar[m_tLen + 2]; fread(LCP, sizeof(uchar), m_tLen, fl); break; default: return false; } fclose(fl); return true; } bool CCTermOnlineDigestion::GetNextSA() { FILE *fl = fopen(m_pMetaHandler.GenerFileName((uchar)m_uCurFileID,PRO_SQ_SA).c_str(), "rb"); if(NULL == fl) return false; SA = new size_t[m_tLen + 2]; if(fread((char*)SA, sizeof(size_t), m_tLen, fl) < m_tLen) return false; fclose(fl); return true; } void CCTermOnlineDigestion::_InitDigest() { size_t clt = clock(); cout << "_InitDigest is begin ..." << endl; m_tMass = new size_t[m_tLen + 3]; nClvy = new size_t[m_tLen/4 + 3]; ncp = 0; m_tMass[0] = 0,nClvy[ncp++] = 0; for(size_t t = 1; t < m_tLen - 1; ++t)//todo { m_tMass[t] = (m_tMass[t - 1] + m_tAAMass[m_chDat[t]]) & m_tMassMod; if(_IsLeft(t) || _IsRight(t)) { nClvy[ncp++] = t; } } m_tMass[m_tLen] = m_tMass[m_tLen - 1] = m_tMass[m_tLen - 2]; m_b = m_e = tbg = 0; tMaxClvy = m_pIndexItem.nMaxMissSite; cout << "_InitDigest is end , The time is:" << clock() - clt << " and ncp is:" << ncp << endl << endl; } void CCTermOnlineDigestion::_Print(size_t s, size_t e, uchar t,PEP_SQ &strPepSQ) { char tmp = m_chDat[e +1]; m_chDat[e + 1] = 0; strPepSQ.strSQ = (char*)&m_chDat[s]; m_chDat[e + 1] = tmp; strPepSQ.dfMass = (((m_tMass[e] + (m_tMassMod + 1 - m_tMass[s - 1])) & m_tMassMod) * 1.0)/ DEFAULT_MULTPLIER; //the miss is wrong, however, in suffix array, we shouold don't care this strPepSQ.cMiss = t; //for protein infer strPepSQ.tInvertedFilesPos = s; strPepSQ.cEnd = 0; if(_IsLeftTerm(s - 1)) strPepSQ.cEnd |=1; if(_IsRightTerm(e)) strPepSQ.cEnd |=2; } size_t CCTermOnlineDigestion::GetProID(size_t tp) { size_t s = 0,e = m_tNum, mid = 0, rp = 0; while(s <= e) { mid =( s + e) >> 1; if(beg[mid] <= tp) { rp=mid,s=mid+1; }else e=mid-1; } if(tp<=beg[rp+1]-2) return rp; return m_tNum; } bool CCTermOnlineDigestion::GetPep2Pro(size_t tp, size_t tLen, vector<size_t> & vtProID) { return false; vtProID.clear(); do { switch(m_pIndexItem.nCleaveWay) { case 0: if(_IsLeft(tp - 1)) { vtProID.push_back(GetProID(tp)); } break; case 1: if(_IsLeft(tp - 1) || _IsRight(tp + tLen -1)) vtProID.push_back(GetProID(tp)); break; case 2: vtProID.push_back(GetProID(tp)); break; } tp = SA[tp]; if(tp >= m_tLen || LCP[tp] < tLen) break; }while(true); return true; } bool CCTermOnlineDigestion::GetSpecificPep(PEP_SQ &strPepSQ) { bool fl = false; for(; m_b < ncp; ++m_b) { while(nClvy[m_b] + 1 >= beg[tbg + 1]) ++tbg; if(true == fl) { tMaxClvy = m_pIndexItem.nMaxMissSite; m_e = 0; } else fl = true; for(; m_e <= tMaxClvy && m_b + m_e + 1 < ncp; ++m_e) { if(nClvy[m_b + m_e + 1] >= beg[tbg + 1] - 1) break;// if not minus one,there will be rudundant of two, because the left of DIVPEP is also the nClvy place if(nClvy[m_b + m_e + 1] - nClvy[m_b] <= LCP[nClvy[m_b] + 1]) { if(!_IsEnzyme(nClvy[m_b + m_e + 1])) ++tMaxClvy; continue; } if(_IsPep(nClvy[m_b] + 1, nClvy[m_b + m_e + 1])) { _Print(nClvy[m_b] + 1, nClvy[m_b + m_e + 1], (uchar)m_e, strPepSQ); ++m_e; return true; } } } return false; } bool CCTermOnlineDigestion::_GetSemiSpecificPep1(PEP_SQ &strPepSQ)//the situation of specific digestion, the right postion must not the digest position { /* * In the suffix system, the first SQ of database begin with '?' */ // if(!m_b) ++m_b; bool fl = false; size_t t = 0; for(; m_b < ncp; ++m_b) { if(!_IsLeft(nClvy[m_b])) continue; while(nClvy[m_b] + 1 >= beg[tbg + 1]) ++tbg; tMaxClvy = m_pIndexItem.nMaxMissSite; for(t = 0; t <= tMaxClvy && m_b + t + 1 < ncp; ++t) { if(nClvy[m_b + t + 1] >= beg[tbg + 1] - 1) break; if(nClvy[m_b + t + 1] - nClvy[m_b] <= LCP[nClvy[m_b] + 1]) { if(!_IsEnzyme(nClvy[m_b + t + 1])) ++tMaxClvy; continue; } } --t; if(true == fl) m_e = 0; else fl = true; for( ; nClvy[m_b] + 1 + m_e < nClvy[m_b + t + 1]&& m_e < m_pIndexItem.tMaxPepLength; ++m_e) { if(nClvy[m_b] + 1 + m_e >= beg[tbg + 1] - 1) break; if(_IsPep(nClvy[m_b] + 1, nClvy[m_b] + 1 +m_e) && !_IsRight(nClvy[m_b] + 1 + m_e)) { _Print(nClvy[m_b] + 1, nClvy[m_b] + 1 + m_e , (uchar)0, strPepSQ); ++m_e; return true; } } } return false; } bool CCTermOnlineDigestion::_GetSemiSpecificPep2(PEP_SQ &strPepSQ)//the situation of non-specific digestion, the right postion must be the digest position { /* * In the suffix system, the first SQ of database begin with '?' */ if(!m_b) ++m_b; bool fl = false; for(; m_b < m_tLen; ++m_b) { while(m_b >= beg[tbg + 1]) ++tbg; if(true == fl) { m_e = LCP[m_b]; tMaxClvy = m_pIndexItem.nMaxMissSite; for(size_t t = 0; t < m_e; ++t) { if(_IsEnzyme(m_b + t)) --tMaxClvy; } } else fl = true; for( ; m_b + m_e < m_tLen && m_e < m_pIndexItem.tMaxPepLength && tMaxClvy>=0; ++m_e) { if(m_b + m_e >= beg[tbg + 1] - 1) break; if(_IsEnzyme(m_b + m_e)) --tMaxClvy; if(_IsPep(m_b, m_b +m_e) && _IsRight(m_b + m_e)) { _Print(m_b, m_b + m_e , (uchar)0, strPepSQ); ++m_e; return true; } } } return false; } bool CCTermOnlineDigestion::GetSemiSpecificPep(PEP_SQ &strPepSQ) { static bool flag = true; if(flag && _GetSemiSpecificPep2(strPepSQ)) return true; if(flag) { FILE *fl = fopen(m_pMetaHandler.GenerFileName((uchar)m_uCurFileID,PRO_SQ_0_LCP).c_str(), "rb"); fread(LCP, sizeof(uchar), m_tLen, fl); fclose(fl); m_b = m_e = tbg = 0; tMaxClvy = m_pIndexItem.nMaxMissSite; flag = false; } return _GetSemiSpecificPep1(strPepSQ); } bool CCTermOnlineDigestion::GetNonSpecificPep(PEP_SQ &strPepSQ) { /* * In the suffix system, the first SQ of database begin with '?' */ if(!m_b) ++m_b; bool fl = false; for(; m_b < m_tLen; ++m_b) { while(m_b >= beg[tbg + 1]) ++tbg; if(true == fl)m_e = LCP[m_b]; else fl = true; for( ; m_b + m_e < m_tLen && m_e < m_pIndexItem.tMaxPepLength; ++m_e) { if(m_b + m_e >= beg[tbg + 1] - 1) break; if(_IsPep(m_b, m_b +m_e)) { _Print(m_b, m_b + m_e , (uchar)0, strPepSQ); ++m_e; return true; } } } return false; } long long CCTermOnlineDigestion::StaticNonSpecificPep() { long long fn = 0; size_t tbg = 0; for(m_b = 0; m_b < m_tLen; ++m_b) { while(m_b >= beg[tbg + 1]) ++tbg; for(m_e = m_pIndexItem.tMinPepLength - 1 ; m_b + m_e < m_tLen && m_e < m_pIndexItem.tMaxPepLength; ++m_e) { if(m_b + m_e >= beg[tbg + 1] - 1) break; if(_IsPep(m_b, m_b +m_e))++fn; } } return fn; } bool CCTermOnlineDigestion::GetNextBlock() { _DeleteAll(); if(false == GetNextAllPro(0)) return false; if(false == GetNextBeg())return false; if(false == GetNextLCP())return false; GetNextSA(); _InitDigest(); return true; } bool CCTermOnlineDigestion::GetNextPep(PEP_SQ &strPepSQ) { switch(m_pIndexItem.nCleaveWay) { case 0: return GetSpecificPep(strPepSQ); case 1: return GetSemiSpecificPep(strPepSQ); case 2: return GetNonSpecificPep(strPepSQ); default: break; } return false; } bool CCTermOnlineDigestion::SuffixSort(size_t tSufType) { size_t clt = 0; FILE *fl = NULL; switch(tSufType) { case 0:return false; case 1:break; case 2:break; case 3: { MSufSort * msufsort = new MSufSort(); while(GetNextAllPro(tSufType)) { // ofstream os("time.txt",ios::app); clt = clock(); m_chDat[--m_tLen] = 0; msufsort->Sort(m_chDat, m_tLen); // os << "The time of Create Suffix Array with Read File is:" << clock() - clt << endl << endl; SA = (size_t *)(m_chDat + ((m_tLen + 3) & ~3)); m_chDat[m_tLen] = DIVPEP;//todo m_tLen = m_tLen + 1; clt = clock(); _GetLCP(); // os << "The time of GetLCP is:" << clock() - clt << endl << endl; clt = clock(); fl = fopen(m_pMetaHandler.GenerFileName((uchar)m_uCurFileID,PRO_SQ_2_LCP).c_str(), "wb"); fwrite((char*)LCP, sizeof(uchar), m_tLen, fl); fclose(fl); // os << "The time of WriteLCP is:" << clock() - clt << endl << endl; clt = clock(); _DealSpecial(); // os << "The time of DealSpecial is:" << clock() - clt << endl << endl; fl = fopen(m_pMetaHandler.GenerFileName((uchar)m_uCurFileID,PRO_SQ_0_LCP).c_str(), "wb"); fwrite((char*)LCP, sizeof(uchar), m_tLen, fl); fclose(fl); // fl = fopen(m_pMetaHandler.GenerFileName((uchar)m_uCurFileID,PRO_SQ_SA).c_str(), "wb"); // fwrite((char*)SA, sizeof(size_t), m_tLen, fl); // fclose(fl); // os.close(); _DeleteAll(); } delete msufsort; return true; } default: return false; } return true; } void CCTermOnlineDigestion::_GetLCP() { size_t clt = clock(); cout << "_GetLCP is Begin...m_tLen is:" << m_tLen << endl; size_t *Rank = new size_t[m_tLen + 5]; size_t t = 0, j = 0, tmp = 0; for(t = 0; t < m_tLen; ++t) { Rank[SA[t]] = t; } LCP = new unsigned char[m_tLen + 5]; for(t = 0;t < m_tLen; ++t) { if(m_tLen - 1 == Rank[t])LCP[t]=0; else { if(t==0||LCP[t-1]<=1) j=0; else j=LCP[t-1]-1; for(tmp=SA[Rank[t]+1];m_chDat[t+j]==m_chDat[tmp+j] && j <= MAX_PEP_LENGTH;++j);//czhou, the max length of peptide LCP[t]=j; } } delete[] Rank;Rank = 0; cout << "_GetLCP is end, the time is:" << clock() - clt << endl << endl; } void CCTermOnlineDigestion::_DealSpecial() { size_t clt = clock(); cout << "DealSpecial is Begin..." << endl; size_t *Rank = new size_t[m_tLen + 2]; size_t t = 0; for(t = 0; t < m_tLen; ++t) { Rank[SA[t]] = t; } for(size_t i =0; i < m_tLen; ++i) { t = Rank[i]; if(MIN_PEP_LENGTH - 1 > LCP[i] ) continue; if(_IsLeft(i - 1))//todo to judge i -1 < 0 is left { size_t p = 1; while(t + p < m_tLen) { int q = SA[t + p]; if(_IsLeft(q - 1)) break; if(LCP[q] < LCP[i]) LCP[i] = LCP[q]; if(LCP[q] == 0) break; ++p; } } if(_IsDiv(i + LCP[i]) && !_IsEnzyme(i + LCP[i] - 1)) --LCP[i];//µ°°×ÖÊ×îºóÒ»¸öëÄ } Rank[SA[0]] = m_tLen;//todo for not use AC algorithm for(t =m_tLen - 1; t >0 ; --t) { Rank[SA[t]] = SA[t - 1]; } memcpy(SA, Rank, sizeof(size_t) * (m_tLen + 1)); delete[] Rank;Rank = 0; cout << "DealSpecial is end, the time is:" << clock() - clt << endl << endl; } }
gpl-3.0
dprevost/photon
src/Nucleus/Tests/List/PeakPrevNullCurrNextOffset.c
1
1767
/* * Copyright (C) 2006-2009 Daniel Prevost <dprevost@photonsoftware.org> * * This file is part of Photon (photonsoftware.org). * * This file may be distributed and/or modified under the terms of the * GNU General Public License version 2 or version 3 as published by the * Free Software Foundation and appearing in the file COPYING.GPL2 and * COPYING.GPL3 included in the packaging of this software. * * Licensees holding a valid Photon Commercial license can use this file * in accordance with the terms of their license. * * This software 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. */ /* --+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-- */ #include "ListTestCommon.h" #include "Nucleus/Tests/EngineTestCommon.h" const bool expectedToPass = false; /* --+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-- */ int main() { #if defined(USE_DBC) psonLinkedList list; psonLinkNode node1, node2, *pNode; psonSessionContext context; bool ok; initTest( expectedToPass, &context ); InitMem(); psonLinkNodeInit( &node1 ); psonLinkNodeInit( &node2 ); psonLinkedListInit( &list ); psonLinkedListPutLast( &list, &node1 ); psonLinkedListPutLast( &list, &node2 ); ok = psonLinkedListPeakLast( &list, &pNode ); if ( ! ok ) { ERROR_EXIT( expectedToPass, NULL, ; ); } pNode->nextOffset = PSON_NULL_OFFSET; ok = psonLinkedListPeakPrevious( &list, pNode, &pNode ); ERROR_EXIT( expectedToPass, NULL, ; ); #else return 1; #endif } /* --+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-- */
gpl-3.0
sjaeckel/libaxolotl-c
src/session_state.c
1
59113
#include "session_state.h" #include <stdlib.h> #include <string.h> #include <assert.h> #include "hkdf.h" #include "curve.h" #include "ratchet.h" #include "axolotl_internal.h" #include "LocalStorageProtocol.pb-c.h" #include "utlist.h" #define MAX_MESSAGE_KEYS 2000 typedef struct message_keys_node { ratchet_message_keys message_key; struct message_keys_node *prev, *next; } message_keys_node; typedef struct session_state_sender_chain { ec_key_pair *sender_ratchet_key_pair; ratchet_chain_key *chain_key; message_keys_node *message_keys_head; } session_state_sender_chain; typedef struct session_state_receiver_chain { ec_public_key *sender_ratchet_key; ratchet_chain_key *chain_key; message_keys_node *message_keys_head; struct session_state_receiver_chain *prev, *next; } session_state_receiver_chain; typedef struct session_pending_key_exchange { uint32_t sequence; ec_key_pair *local_base_key; ec_key_pair *local_ratchet_key; ratchet_identity_key_pair *local_identity_key; } session_pending_key_exchange; typedef struct session_pending_pre_key { int has_pre_key_id; uint32_t pre_key_id; uint32_t signed_pre_key_id; ec_public_key *base_key; } session_pending_pre_key; struct session_state { axolotl_type_base base; uint32_t session_version; ec_public_key *local_identity_public; ec_public_key *remote_identity_public; ratchet_root_key *root_key; uint32_t previous_counter; int has_sender_chain; session_state_sender_chain sender_chain; session_state_receiver_chain *receiver_chain_head; int has_pending_key_exchange; session_pending_key_exchange pending_key_exchange; int has_pending_pre_key; session_pending_pre_key pending_pre_key; uint32_t remote_registration_id; uint32_t local_registration_id; int needs_refresh; ec_public_key *alice_base_key; axolotl_context *global_context; }; static int session_state_serialize_prepare_sender_chain( session_state_sender_chain *chain, Textsecure__SessionStructure__Chain *chain_structure); static int session_state_serialize_prepare_receiver_chain( session_state_receiver_chain *chain, Textsecure__SessionStructure__Chain *chain_structure); static void session_state_serialize_prepare_chain_free( Textsecure__SessionStructure__Chain *chain_structure); static int session_state_serialize_prepare_chain_chain_key( ratchet_chain_key *chain_key, Textsecure__SessionStructure__Chain *chain_structure); static int session_state_serialize_prepare_chain_message_keys_list( message_keys_node *message_keys_head, Textsecure__SessionStructure__Chain *chain_structure); static int session_state_serialize_prepare_message_keys( ratchet_message_keys *message_key, Textsecure__SessionStructure__Chain__MessageKey *message_key_structure); static void session_state_serialize_prepare_message_keys_free( Textsecure__SessionStructure__Chain__MessageKey *message_key_structure); static int session_state_serialize_prepare_pending_key_exchange( session_pending_key_exchange *exchange, Textsecure__SessionStructure__PendingKeyExchange *exchange_structure); static void session_state_serialize_prepare_pending_key_exchange_free( Textsecure__SessionStructure__PendingKeyExchange *exchange_structure); static int session_state_serialize_prepare_pending_pre_key( session_pending_pre_key *pre_key, Textsecure__SessionStructure__PendingPreKey *pre_key_structure); static void session_state_serialize_prepare_pending_pre_key_free( Textsecure__SessionStructure__PendingPreKey *pre_key_structure); static int session_state_deserialize_protobuf_pending_key_exchange( session_pending_key_exchange *result_exchange, Textsecure__SessionStructure__PendingKeyExchange *exchange_structure, axolotl_context *global_context); static int session_state_deserialize_protobuf_pending_pre_key( session_pending_pre_key *result_pre_key, Textsecure__SessionStructure__PendingPreKey *pre_key_structure, axolotl_context *global_context); static int session_state_deserialize_protobuf_sender_chain( uint32_t session_version, session_state_sender_chain *chain, Textsecure__SessionStructure__Chain *chain_structure, axolotl_context *global_context); static int session_state_deserialize_protobuf_receiver_chain( uint32_t session_version, session_state_receiver_chain *chain, Textsecure__SessionStructure__Chain *chain_structure, axolotl_context *global_context); static void session_state_free_sender_chain(session_state *state); static void session_state_free_receiver_chain_node(session_state_receiver_chain *node); static void session_state_free_receiver_chain(session_state *state); static session_state_receiver_chain *session_state_find_receiver_chain(const session_state *state, const ec_public_key *sender_ephemeral); int session_state_create(session_state **state, axolotl_context *global_context) { session_state *result = malloc(sizeof(session_state)); if(!result) { return AX_ERR_NOMEM; } memset(result, 0, sizeof(session_state)); AXOLOTL_INIT(result, session_state_destroy); result->session_version = 2; result->global_context = global_context; *state = result; return 0; } int session_state_serialize(axolotl_buffer **buffer, session_state *state) { int result = 0; size_t result_size = 0; Textsecure__SessionStructure *state_structure = 0; axolotl_buffer *result_buf = 0; size_t len = 0; uint8_t *data = 0; state_structure = malloc(sizeof(Textsecure__SessionStructure)); if(!state_structure) { result = AX_ERR_NOMEM; goto complete; } textsecure__session_structure__init(state_structure); result = session_state_serialize_prepare(state, state_structure); if(result < 0) { goto complete; } len = textsecure__session_structure__get_packed_size(state_structure); result_buf = axolotl_buffer_alloc(len); if(!result_buf) { result = AX_ERR_NOMEM; goto complete; } data = axolotl_buffer_data(result_buf); result_size = textsecure__session_structure__pack(state_structure, data); if(result_size != len) { axolotl_buffer_free(result_buf); result = AX_ERR_INVALID_PROTO_BUF; result_buf = 0; goto complete; } complete: if(state_structure) { session_state_serialize_prepare_free(state_structure); } if(result >= 0) { *buffer = result_buf; } return result; } int session_state_deserialize(session_state **state, const uint8_t *data, size_t len, axolotl_context *global_context) { int result = 0; session_state *result_state = 0; Textsecure__SessionStructure *session_structure = 0; session_structure = textsecure__session_structure__unpack(0, len, data); if(!session_structure) { result = AX_ERR_INVALID_PROTO_BUF; goto complete; } result = session_state_deserialize_protobuf(&result_state, session_structure, global_context); if(result < 0) { goto complete; } complete: if(session_structure) { textsecure__session_structure__free_unpacked(session_structure, 0); } if(result_state) { if(result < 0) { AXOLOTL_UNREF(result_state); } else { *state = result_state; } } return result; } int session_state_serialize_prepare(session_state *state, Textsecure__SessionStructure *session_structure) { int result = 0; assert(state); assert(session_structure); session_structure->has_sessionversion = 1; session_structure->sessionversion = state->session_version; if(state->local_identity_public) { result = ec_public_key_serialize_protobuf( &session_structure->localidentitypublic, state->local_identity_public); if(result < 0) { goto complete; } session_structure->has_localidentitypublic = 1; } if(state->remote_identity_public) { result = ec_public_key_serialize_protobuf( &session_structure->remoteidentitypublic, state->remote_identity_public); if(result < 0) { goto complete; } session_structure->has_remoteidentitypublic = 1; } if(state->root_key) { result = ratchet_root_key_get_key_protobuf( state->root_key, &session_structure->rootkey); if(result < 0) { goto complete; } session_structure->has_rootkey = 1; } session_structure->has_previouscounter = 1; session_structure->previouscounter = state->previous_counter; if(state->has_sender_chain) { session_structure->senderchain = malloc(sizeof(Textsecure__SessionStructure__Chain)); if(!session_structure->senderchain) { result = AX_ERR_NOMEM; goto complete; } textsecure__session_structure__chain__init(session_structure->senderchain); result = session_state_serialize_prepare_sender_chain( &state->sender_chain, session_structure->senderchain); if(result < 0) { goto complete; } } if(state->receiver_chain_head) { size_t i = 0; unsigned int count; session_state_receiver_chain *cur_node; DL_COUNT(state->receiver_chain_head, cur_node, count); if(count > SIZE_MAX / sizeof(Textsecure__SessionStructure__Chain *)) { result = AX_ERR_NOMEM; goto complete; } session_structure->receiverchains = malloc(sizeof(Textsecure__SessionStructure__Chain *) * count); if(!session_structure->receiverchains) { result = AX_ERR_NOMEM; goto complete; } DL_FOREACH(state->receiver_chain_head, cur_node) { session_structure->receiverchains[i] = malloc(sizeof(Textsecure__SessionStructure__Chain)); if(!session_structure->receiverchains[i]) { result = AX_ERR_NOMEM; break; } textsecure__session_structure__chain__init(session_structure->receiverchains[i]); result = session_state_serialize_prepare_receiver_chain(cur_node, session_structure->receiverchains[i]); if(result < 0) { break; } i++; } session_structure->n_receiverchains = i; if(result < 0) { goto complete; } } if(state->has_pending_key_exchange) { session_structure->pendingkeyexchange = malloc(sizeof(Textsecure__SessionStructure__PendingKeyExchange)); if(!session_structure->pendingkeyexchange) { result = AX_ERR_NOMEM; goto complete; } textsecure__session_structure__pending_key_exchange__init(session_structure->pendingkeyexchange); result = session_state_serialize_prepare_pending_key_exchange( &state->pending_key_exchange, session_structure->pendingkeyexchange); if(result < 0) { goto complete; } } if(state->has_pending_pre_key) { session_structure->pendingprekey = malloc(sizeof(Textsecure__SessionStructure__PendingPreKey)); if(!session_structure->pendingprekey) { result = AX_ERR_NOMEM; goto complete; } textsecure__session_structure__pending_pre_key__init(session_structure->pendingprekey); result = session_state_serialize_prepare_pending_pre_key( &state->pending_pre_key, session_structure->pendingprekey); if(result < 0) { goto complete; } } session_structure->has_remoteregistrationid = 1; session_structure->remoteregistrationid = state->remote_registration_id; session_structure->has_localregistrationid = 1; session_structure->localregistrationid = state->local_registration_id; session_structure->has_needsrefresh = 1; session_structure->needsrefresh = state->needs_refresh; if(state->alice_base_key) { result = ec_public_key_serialize_protobuf( &session_structure->alicebasekey, state->alice_base_key); if(result < 0) { goto complete; } session_structure->has_alicebasekey = 1; } complete: return result; } static int session_state_serialize_prepare_sender_chain( session_state_sender_chain *chain, Textsecure__SessionStructure__Chain *chain_structure) { int result = 0; if(chain->sender_ratchet_key_pair) { ec_public_key *public_key = 0; ec_private_key *private_key = 0; public_key = ec_key_pair_get_public(chain->sender_ratchet_key_pair); result = ec_public_key_serialize_protobuf(&chain_structure->senderratchetkey, public_key); if(result < 0) { goto complete; } chain_structure->has_senderratchetkey = 1; private_key = ec_key_pair_get_private(chain->sender_ratchet_key_pair); result = ec_private_key_serialize_protobuf(&chain_structure->senderratchetkeyprivate, private_key); if(result < 0) { goto complete; } chain_structure->has_senderratchetkeyprivate = 1; } if(chain->chain_key) { result = session_state_serialize_prepare_chain_chain_key(chain->chain_key, chain_structure); if(result < 0) { goto complete; } } if(chain->message_keys_head) { result = session_state_serialize_prepare_chain_message_keys_list(chain->message_keys_head, chain_structure); if(result < 0) { goto complete; } } complete: return result; } static int session_state_serialize_prepare_receiver_chain( session_state_receiver_chain *chain, Textsecure__SessionStructure__Chain *chain_structure) { int result = 0; if(chain->sender_ratchet_key) { result = ec_public_key_serialize_protobuf(&chain_structure->senderratchetkey, chain->sender_ratchet_key); if(result < 0) { goto complete; } chain_structure->has_senderratchetkey = 1; } if(chain->chain_key) { result = session_state_serialize_prepare_chain_chain_key(chain->chain_key, chain_structure); if(result < 0) { goto complete; } } if(chain->message_keys_head) { result = session_state_serialize_prepare_chain_message_keys_list(chain->message_keys_head, chain_structure); if(result < 0) { goto complete; } } complete: return result; } static int session_state_serialize_prepare_chain_chain_key( ratchet_chain_key *chain_key, Textsecure__SessionStructure__Chain *chain_structure) { int result = 0; chain_structure->chainkey = malloc(sizeof(Textsecure__SessionStructure__Chain__ChainKey)); if(!chain_structure->chainkey) { result = AX_ERR_NOMEM; goto complete; } textsecure__session_structure__chain__chain_key__init(chain_structure->chainkey); chain_structure->chainkey->has_index = 1; chain_structure->chainkey->index = ratchet_chain_key_get_index(chain_key); result = ratchet_chain_key_get_key_protobuf(chain_key, &chain_structure->chainkey->key); if(result < 0) { goto complete; } chain_structure->chainkey->has_key = 1; complete: return result; } static int session_state_serialize_prepare_chain_message_keys_list( message_keys_node *message_keys_head, Textsecure__SessionStructure__Chain *chain_structure) { int result = 0; size_t i = 0; unsigned int count; message_keys_node *cur_node; DL_COUNT(message_keys_head, cur_node, count); if(count == 0) { goto complete; } if(count > SIZE_MAX / sizeof(Textsecure__SessionStructure__Chain__MessageKey *)) { result = AX_ERR_NOMEM; goto complete; } chain_structure->messagekeys = malloc(sizeof(Textsecure__SessionStructure__Chain__MessageKey *) * count); if(!chain_structure->messagekeys) { result = AX_ERR_NOMEM; goto complete; } DL_FOREACH(message_keys_head, cur_node) { chain_structure->messagekeys[i] = malloc(sizeof(Textsecure__SessionStructure__Chain__MessageKey)); if(!chain_structure->messagekeys[i]) { result = AX_ERR_NOMEM; break; } textsecure__session_structure__chain__message_key__init(chain_structure->messagekeys[i]); result = session_state_serialize_prepare_message_keys(&cur_node->message_key, chain_structure->messagekeys[i]); if(result < 0) { break; } i++; } chain_structure->n_messagekeys = i; if(result < 0) { goto complete; } complete: return result; } static int session_state_serialize_prepare_message_keys( ratchet_message_keys *message_key, Textsecure__SessionStructure__Chain__MessageKey *message_key_structure) { int result = 0; message_key_structure->has_index = 1; message_key_structure->index = message_key->counter; message_key_structure->cipherkey.data = malloc(sizeof(message_key->cipher_key)); if(!message_key_structure->cipherkey.data) { result = AX_ERR_NOMEM; goto complete; } memcpy(message_key_structure->cipherkey.data, message_key->cipher_key, sizeof(message_key->cipher_key)); message_key_structure->cipherkey.len = sizeof(message_key->cipher_key); message_key_structure->has_cipherkey = 1; message_key_structure->mackey.data = malloc(sizeof(message_key->mac_key)); if(!message_key_structure->mackey.data) { result = AX_ERR_NOMEM; goto complete; } memcpy(message_key_structure->mackey.data, message_key->mac_key, sizeof(message_key->mac_key)); message_key_structure->mackey.len = sizeof(message_key->mac_key); message_key_structure->has_mackey = 1; message_key_structure->iv.data = malloc(sizeof(message_key->iv)); if(!message_key_structure->iv.data) { result = AX_ERR_NOMEM; goto complete; } memcpy(message_key_structure->iv.data, message_key->iv, sizeof(message_key->iv)); message_key_structure->iv.len = sizeof(message_key->iv); message_key_structure->has_iv = 1; complete: return result; } static void session_state_serialize_prepare_message_keys_free( Textsecure__SessionStructure__Chain__MessageKey *message_key_structure) { if(message_key_structure->has_cipherkey) { free(message_key_structure->cipherkey.data); } if(message_key_structure->has_mackey) { free(message_key_structure->mackey.data); } if(message_key_structure->has_iv) { free(message_key_structure->iv.data); } free(message_key_structure); } static int session_state_serialize_prepare_pending_key_exchange( session_pending_key_exchange *exchange, Textsecure__SessionStructure__PendingKeyExchange *exchange_structure) { int result = 0; exchange_structure->has_sequence = 1; exchange_structure->sequence = exchange->sequence; if(exchange->local_base_key) { ec_public_key *public_key = 0; ec_private_key *private_key = 0; public_key = ec_key_pair_get_public(exchange->local_base_key); result = ec_public_key_serialize_protobuf(&exchange_structure->localbasekey, public_key); if(result < 0) { goto complete; } exchange_structure->has_localbasekey = 1; private_key = ec_key_pair_get_private(exchange->local_base_key); result = ec_private_key_serialize_protobuf(&exchange_structure->localbasekeyprivate, private_key); if(result < 0) { goto complete; } exchange_structure->has_localbasekeyprivate = 1; } if(exchange->local_ratchet_key) { ec_public_key *public_key; ec_private_key *private_key; public_key = ec_key_pair_get_public(exchange->local_ratchet_key); result = ec_public_key_serialize_protobuf(&exchange_structure->localratchetkey, public_key); if(result < 0) { goto complete; } exchange_structure->has_localratchetkey = 1; private_key = ec_key_pair_get_private(exchange->local_ratchet_key); result = ec_private_key_serialize_protobuf(&exchange_structure->localratchetkeyprivate, private_key); if(result < 0) { goto complete; } exchange_structure->has_localratchetkeyprivate = 1; } if(exchange->local_identity_key) { ec_public_key *public_key; ec_private_key *private_key; public_key = ratchet_identity_key_pair_get_public(exchange->local_identity_key); result = ec_public_key_serialize_protobuf(&exchange_structure->localidentitykey, public_key); if(result < 0) { goto complete; } exchange_structure->has_localidentitykey = 1; private_key = ratchet_identity_key_pair_get_private(exchange->local_identity_key); result = ec_private_key_serialize_protobuf(&exchange_structure->localidentitykeyprivate, private_key); if(result < 0) { goto complete; } exchange_structure->has_localidentitykeyprivate = 1; } complete: return result; } static int session_state_serialize_prepare_pending_pre_key( session_pending_pre_key *pre_key, Textsecure__SessionStructure__PendingPreKey *pre_key_structure) { int result = 0; if(pre_key->has_pre_key_id) { pre_key_structure->has_prekeyid = 1; pre_key_structure->prekeyid = pre_key->pre_key_id; } pre_key_structure->has_signedprekeyid = 1; pre_key_structure->signedprekeyid = (int32_t)pre_key->signed_pre_key_id; if(pre_key->base_key) { result = ec_public_key_serialize_protobuf(&pre_key_structure->basekey, pre_key->base_key); if(result < 0) { goto complete; } pre_key_structure->has_basekey = 1; } complete: return result; } void session_state_serialize_prepare_free(Textsecure__SessionStructure *session_structure) { assert(session_structure); if(session_structure->has_localidentitypublic) { free(session_structure->localidentitypublic.data); } if(session_structure->has_remoteidentitypublic) { free(session_structure->remoteidentitypublic.data); } if(session_structure->has_rootkey) { free(session_structure->rootkey.data); } if(session_structure->senderchain) { session_state_serialize_prepare_chain_free(session_structure->senderchain); } if(session_structure->receiverchains) { unsigned int i; for(i = 0; i < session_structure->n_receiverchains; i++) { if(session_structure->receiverchains[i]) { session_state_serialize_prepare_chain_free(session_structure->receiverchains[i]); } } free(session_structure->receiverchains); } if(session_structure->pendingkeyexchange) { session_state_serialize_prepare_pending_key_exchange_free(session_structure->pendingkeyexchange); } if(session_structure->pendingprekey) { session_state_serialize_prepare_pending_pre_key_free(session_structure->pendingprekey); } if(session_structure->has_alicebasekey) { free(session_structure->alicebasekey.data); } free(session_structure); } static void session_state_serialize_prepare_chain_free( Textsecure__SessionStructure__Chain *chain_structure) { if(chain_structure->has_senderratchetkey) { free(chain_structure->senderratchetkey.data); } if(chain_structure->has_senderratchetkeyprivate) { free(chain_structure->senderratchetkeyprivate.data); } if(chain_structure->chainkey) { if(chain_structure->chainkey->has_key) { free(chain_structure->chainkey->key.data); } free(chain_structure->chainkey); } if(chain_structure->messagekeys) { unsigned int i; for(i = 0; i < chain_structure->n_messagekeys; i++) { if(chain_structure->messagekeys[i]) { session_state_serialize_prepare_message_keys_free(chain_structure->messagekeys[i]); } } free(chain_structure->messagekeys); } free(chain_structure); } static void session_state_serialize_prepare_pending_key_exchange_free( Textsecure__SessionStructure__PendingKeyExchange *exchange_structure) { if(exchange_structure->has_localbasekey) { free(exchange_structure->localbasekey.data); } if(exchange_structure->has_localbasekeyprivate) { free(exchange_structure->localbasekeyprivate.data); } if(exchange_structure->has_localratchetkey) { free(exchange_structure->localratchetkey.data); } if(exchange_structure->has_localratchetkeyprivate) { free(exchange_structure->localratchetkeyprivate.data); } if(exchange_structure->has_localidentitykey) { free(exchange_structure->localidentitykey.data); } if(exchange_structure->has_localidentitykeyprivate) { free(exchange_structure->localidentitykeyprivate.data); } free(exchange_structure); } static void session_state_serialize_prepare_pending_pre_key_free( Textsecure__SessionStructure__PendingPreKey *pre_key_structure) { if(pre_key_structure->has_basekey) { free(pre_key_structure->basekey.data); } free(pre_key_structure); } int session_state_deserialize_protobuf(session_state **state, Textsecure__SessionStructure *session_structure, axolotl_context *global_context) { int result = 0; session_state *result_state = 0; result = session_state_create(&result_state, global_context); if(result < 0) { goto complete; } if(session_structure->has_sessionversion) { result_state->session_version = session_structure->sessionversion; } if(session_structure->has_localidentitypublic) { result = curve_decode_point( &result_state->local_identity_public, session_structure->localidentitypublic.data, session_structure->localidentitypublic.len, global_context); if(result < 0) { goto complete; } } if(session_structure->has_remoteidentitypublic) { result = curve_decode_point( &result_state->remote_identity_public, session_structure->remoteidentitypublic.data, session_structure->remoteidentitypublic.len, global_context); if(result < 0) { goto complete; } } if(session_structure->has_rootkey) { hkdf_context *kdf = 0; result = hkdf_create(&kdf, (int)result_state->session_version, global_context); if(result < 0) { goto complete; } result = ratchet_root_key_create( &result_state->root_key, kdf, session_structure->rootkey.data, session_structure->rootkey.len, global_context); AXOLOTL_UNREF(kdf); if(result < 0) { goto complete; } } if(session_structure->has_previouscounter) { result_state->previous_counter = session_structure->previouscounter; } if(session_structure->senderchain) { session_state_deserialize_protobuf_sender_chain( result_state->session_version, &result_state->sender_chain, session_structure->senderchain, global_context); if(result < 0) { goto complete; } result_state->has_sender_chain = 1; } if(session_structure->n_receiverchains > 0) { unsigned int i; for(i = 0; i < session_structure->n_receiverchains; i++) { session_state_receiver_chain *node = malloc(sizeof(session_state_receiver_chain)); if(!node) { result = AX_ERR_NOMEM; goto complete; } memset(node, 0, sizeof(session_state_receiver_chain)); result = session_state_deserialize_protobuf_receiver_chain( result_state->session_version, node, session_structure->receiverchains[i], global_context); if(result < 0) { free(node); goto complete; } DL_APPEND(result_state->receiver_chain_head, node); } } if(session_structure->pendingkeyexchange) { result = session_state_deserialize_protobuf_pending_key_exchange( &result_state->pending_key_exchange, session_structure->pendingkeyexchange, global_context); if(result < 0) { goto complete; } result_state->has_pending_key_exchange = 1; } if(session_structure->pendingprekey) { result = session_state_deserialize_protobuf_pending_pre_key( &result_state->pending_pre_key, session_structure->pendingprekey, global_context); if(result < 0) { goto complete; } result_state->has_pending_pre_key = 1; } if(session_structure->has_remoteregistrationid) { result_state->remote_registration_id = session_structure->remoteregistrationid; } if(session_structure->has_localregistrationid) { result_state->local_registration_id = session_structure->localregistrationid; } if(session_structure->has_needsrefresh) { result_state->needs_refresh = session_structure->needsrefresh; } if(session_structure->has_alicebasekey) { result = curve_decode_point( &result_state->alice_base_key, session_structure->alicebasekey.data, session_structure->alicebasekey.len, global_context); if(result < 0) { goto complete; } } complete: if(result >= 0) { *state = result_state; } else { if(result_state) { AXOLOTL_UNREF(result_state); } } return result; } static int session_state_deserialize_protobuf_pending_key_exchange( session_pending_key_exchange *result_exchange, Textsecure__SessionStructure__PendingKeyExchange *exchange_structure, axolotl_context *global_context) { int result = 0; ec_key_pair *local_base_key = 0; ec_public_key *local_base_key_public = 0; ec_private_key *local_base_key_private = 0; ec_key_pair *local_ratchet_key = 0; ec_public_key *local_ratchet_key_public = 0; ec_private_key *local_ratchet_key_private = 0; ratchet_identity_key_pair *local_identity_key = 0; ec_public_key *local_identity_key_public = 0; ec_private_key *local_identity_key_private = 0; if(exchange_structure->has_localbasekey && exchange_structure->has_localbasekeyprivate) { result = curve_decode_point(&local_base_key_public, exchange_structure->localbasekey.data, exchange_structure->localbasekey.len, global_context); if(result < 0) { goto complete; } result = curve_decode_private_point(&local_base_key_private, exchange_structure->localbasekeyprivate.data, exchange_structure->localbasekeyprivate.len, global_context); if(result < 0) { goto complete; } result = ec_key_pair_create(&local_base_key, local_base_key_public, local_base_key_private); if(result < 0) { goto complete; } } if(exchange_structure->has_localratchetkey && exchange_structure->has_localratchetkeyprivate) { result = curve_decode_point(&local_ratchet_key_public, exchange_structure->localratchetkey.data, exchange_structure->localratchetkey.len, global_context); if(result < 0) { goto complete; } result = curve_decode_private_point(&local_ratchet_key_private, exchange_structure->localratchetkeyprivate.data, exchange_structure->localratchetkeyprivate.len, global_context); if(result < 0) { goto complete; } result = ec_key_pair_create(&local_ratchet_key, local_ratchet_key_public, local_ratchet_key_private); if(result < 0) { goto complete; } } if(exchange_structure->has_localidentitykey && exchange_structure->has_localidentitykeyprivate) { result = curve_decode_point(&local_identity_key_public, exchange_structure->localidentitykey.data, exchange_structure->localidentitykey.len, global_context); if(result < 0) { goto complete; } result = curve_decode_private_point(&local_identity_key_private, exchange_structure->localidentitykeyprivate.data, exchange_structure->localidentitykeyprivate.len, global_context); if(result < 0) { goto complete; } result = ratchet_identity_key_pair_create(&local_identity_key, local_identity_key_public, local_identity_key_private); if(result < 0) { goto complete; } } result_exchange->sequence = exchange_structure->sequence; result_exchange->local_base_key = local_base_key; result_exchange->local_ratchet_key = local_ratchet_key; result_exchange->local_identity_key = local_identity_key; complete: AXOLOTL_UNREF(local_base_key_public); AXOLOTL_UNREF(local_base_key_private); AXOLOTL_UNREF(local_ratchet_key_public); AXOLOTL_UNREF(local_ratchet_key_private); AXOLOTL_UNREF(local_identity_key_public); AXOLOTL_UNREF(local_identity_key_private); if(result < 0) { AXOLOTL_UNREF(local_base_key); AXOLOTL_UNREF(local_ratchet_key); AXOLOTL_UNREF(local_identity_key); } return result; } static int session_state_deserialize_protobuf_pending_pre_key( session_pending_pre_key *result_pre_key, Textsecure__SessionStructure__PendingPreKey *pre_key_structure, axolotl_context *global_context) { int result = 0; if(pre_key_structure->has_basekey) { ec_public_key *base_key = 0; result = curve_decode_point(&base_key, pre_key_structure->basekey.data, pre_key_structure->basekey.len, global_context); if(result < 0) { goto complete; } result_pre_key->base_key = base_key; } if(pre_key_structure->has_prekeyid) { result_pre_key->has_pre_key_id = 1; result_pre_key->pre_key_id = pre_key_structure->prekeyid; } if(pre_key_structure->has_signedprekeyid) { result_pre_key->signed_pre_key_id = (uint32_t)pre_key_structure->signedprekeyid; } complete: return result; } static int session_state_deserialize_protobuf_sender_chain( uint32_t session_version, session_state_sender_chain *chain, Textsecure__SessionStructure__Chain *chain_structure, axolotl_context *global_context) { int result = 0; hkdf_context *kdf = 0; ec_key_pair *sender_ratchet_key_pair = 0; ec_public_key *sender_ratchet_key_public = 0; ec_private_key *sender_ratchet_key_private = 0; ratchet_chain_key *sender_chain_key = 0; if(chain_structure->has_senderratchetkey && chain_structure->has_senderratchetkeyprivate) { result = curve_decode_point(&sender_ratchet_key_public, chain_structure->senderratchetkey.data, chain_structure->senderratchetkey.len, global_context); if(result < 0) { goto complete; } result = curve_decode_private_point(&sender_ratchet_key_private, chain_structure->senderratchetkeyprivate.data, chain_structure->senderratchetkeyprivate.len, global_context); if(result < 0) { goto complete; } result = ec_key_pair_create(&sender_ratchet_key_pair, sender_ratchet_key_public, sender_ratchet_key_private); if(result < 0) { goto complete; } } if(chain_structure->chainkey && chain_structure->chainkey->has_key && chain_structure->chainkey->has_index) { result = hkdf_create(&kdf, (int)session_version, global_context); if(result < 0) { goto complete; } result = ratchet_chain_key_create( &sender_chain_key, kdf, chain_structure->chainkey->key.data, chain_structure->chainkey->key.len, chain_structure->chainkey->index, global_context); if(result < 0) { goto complete; } } chain->sender_ratchet_key_pair = sender_ratchet_key_pair; chain->chain_key = sender_chain_key; complete: AXOLOTL_UNREF(kdf); AXOLOTL_UNREF(sender_ratchet_key_public); AXOLOTL_UNREF(sender_ratchet_key_private); if(result < 0) { AXOLOTL_UNREF(sender_ratchet_key_pair); AXOLOTL_UNREF(sender_chain_key); } return result; } static int session_state_deserialize_protobuf_receiver_chain( uint32_t session_version, session_state_receiver_chain *chain, Textsecure__SessionStructure__Chain *chain_structure, axolotl_context *global_context) { int result = 0; hkdf_context *kdf = 0; ec_public_key *sender_ratchet_key = 0; ratchet_chain_key *chain_key = 0; message_keys_node *message_keys_head = 0; if(chain_structure->has_senderratchetkey) { result = curve_decode_point(&sender_ratchet_key, chain_structure->senderratchetkey.data, chain_structure->senderratchetkey.len, global_context); if(result < 0) { goto complete; } } if(chain_structure->chainkey && chain_structure->chainkey->has_key && chain_structure->chainkey->has_index) { result = hkdf_create(&kdf, (int)session_version, global_context); if(result < 0) { goto complete; } result = ratchet_chain_key_create( &chain_key, kdf, chain_structure->chainkey->key.data, chain_structure->chainkey->key.len, chain_structure->chainkey->index, global_context); if(result < 0) { goto complete; } } if(chain_structure->n_messagekeys > 0) { unsigned int i; for(i = 0; i < chain_structure->n_messagekeys; i++) { Textsecure__SessionStructure__Chain__MessageKey *key_structure = chain_structure->messagekeys[i]; message_keys_node *node = malloc(sizeof(message_keys_node)); if(!node) { result = AX_ERR_NOMEM; goto complete; } memset(node, 0, sizeof(message_keys_node)); if(key_structure->has_index) { node->message_key.counter = key_structure->index; } if(key_structure->has_cipherkey && key_structure->cipherkey.len == sizeof(node->message_key.cipher_key)) { memcpy(node->message_key.cipher_key, key_structure->cipherkey.data, key_structure->cipherkey.len); } if(key_structure->has_mackey && key_structure->mackey.len == sizeof(node->message_key.mac_key)) { memcpy(node->message_key.mac_key, key_structure->mackey.data, key_structure->mackey.len); } if(key_structure->has_iv && key_structure->iv.len == sizeof(node->message_key.iv)) { memcpy(node->message_key.iv, key_structure->iv.data, key_structure->iv.len); } DL_APPEND(message_keys_head, node); } } chain->sender_ratchet_key = sender_ratchet_key; chain->chain_key = chain_key; chain->message_keys_head = message_keys_head; complete: AXOLOTL_UNREF(kdf); if(result < 0) { AXOLOTL_UNREF(sender_ratchet_key); AXOLOTL_UNREF(chain_key); if(message_keys_head) { message_keys_node *cur_node; message_keys_node *tmp_node; DL_FOREACH_SAFE(message_keys_head, cur_node, tmp_node) { DL_DELETE(message_keys_head, cur_node); axolotl_explicit_bzero(&cur_node->message_key, sizeof(ratchet_message_keys)); free(cur_node); } } } return result; } int session_state_copy(session_state **state, session_state *other_state, axolotl_context *global_context) { int result = 0; axolotl_buffer *buffer = 0; size_t len = 0; uint8_t *data = 0; assert(other_state); assert(global_context); result = session_state_serialize(&buffer, other_state); if(result < 0) { goto complete; } data = axolotl_buffer_data(buffer); len = axolotl_buffer_len(buffer); result = session_state_deserialize(state, data, len, global_context); if(result < 0) { goto complete; } complete: if(buffer) { axolotl_buffer_free(buffer); } return result; } void session_state_set_session_version(session_state *state, uint32_t version) { assert(state); state->session_version = version; } uint32_t session_state_get_session_version(const session_state *state) { assert(state); return state->session_version; } void session_state_set_local_identity_key(session_state *state, ec_public_key *identity_key) { assert(state); assert(identity_key); if(state->local_identity_public) { AXOLOTL_UNREF(state->local_identity_public); } AXOLOTL_REF(identity_key); state->local_identity_public = identity_key; } ec_public_key *session_state_get_local_identity_key(const session_state *state) { assert(state); return state->local_identity_public; } void session_state_set_remote_identity_key(session_state *state, ec_public_key *identity_key) { assert(state); assert(identity_key); if(state->remote_identity_public) { AXOLOTL_UNREF(state->remote_identity_public); } AXOLOTL_REF(identity_key); state->remote_identity_public = identity_key; } ec_public_key *session_state_get_remote_identity_key(const session_state *state) { assert(state); return state->remote_identity_public; } void session_state_set_root_key(session_state *state, ratchet_root_key *root_key) { assert(state); assert(root_key); if(state->root_key) { AXOLOTL_UNREF(state->root_key); } AXOLOTL_REF(root_key); state->root_key = root_key; } ratchet_root_key *session_state_get_root_key(const session_state *state) { assert(state); return state->root_key; } void session_state_set_previous_counter(session_state *state, uint32_t counter) { assert(state); state->previous_counter = counter; } uint32_t session_state_get_previous_counter(const session_state *state) { assert(state); return state->previous_counter; } void session_state_set_sender_chain(session_state *state, ec_key_pair *sender_ratchet_key_pair, ratchet_chain_key *chain_key) { assert(state); assert(sender_ratchet_key_pair); assert(chain_key); state->has_sender_chain = 1; if(state->sender_chain.sender_ratchet_key_pair) { AXOLOTL_UNREF(state->sender_chain.sender_ratchet_key_pair); } AXOLOTL_REF(sender_ratchet_key_pair); state->sender_chain.sender_ratchet_key_pair = sender_ratchet_key_pair; if(state->sender_chain.chain_key) { AXOLOTL_UNREF(state->sender_chain.chain_key); } AXOLOTL_REF(chain_key); state->sender_chain.chain_key = chain_key; } ec_public_key *session_state_get_sender_ratchet_key(const session_state *state) { assert(state); if(state->sender_chain.sender_ratchet_key_pair) { return ec_key_pair_get_public(state->sender_chain.sender_ratchet_key_pair); } else { return 0; } } ec_key_pair *session_state_get_sender_ratchet_key_pair(const session_state *state) { assert(state); return state->sender_chain.sender_ratchet_key_pair; } ratchet_chain_key *session_state_get_sender_chain_key(const session_state *state) { assert(state); return state->sender_chain.chain_key; } int session_state_set_sender_chain_key(session_state *state, ratchet_chain_key *chain_key) { assert(state); if(state->has_sender_chain) { if(state->sender_chain.chain_key) { AXOLOTL_UNREF(state->sender_chain.chain_key); } AXOLOTL_REF(chain_key); state->sender_chain.chain_key = chain_key; return 0; } else { return AX_ERR_UNKNOWN; } } int session_state_has_sender_chain(const session_state *state) { assert(state); return state->has_sender_chain; } int session_state_has_message_keys(session_state *state, ec_public_key *sender_ephemeral, uint32_t counter) { session_state_receiver_chain *chain = 0; message_keys_node *cur_node = 0; assert(state); assert(sender_ephemeral); chain = session_state_find_receiver_chain(state, sender_ephemeral); if(!chain) { return 0; } DL_FOREACH(chain->message_keys_head, cur_node) { if(cur_node->message_key.counter == counter) { return 1; } } return 0; } int session_state_remove_message_keys(session_state *state, ratchet_message_keys *message_keys_result, ec_public_key *sender_ephemeral, uint32_t counter) { session_state_receiver_chain *chain = 0; message_keys_node *cur_node = 0; message_keys_node *tmp_node = 0; assert(state); assert(message_keys_result); assert(sender_ephemeral); chain = session_state_find_receiver_chain(state, sender_ephemeral); if(!chain) { return 0; } DL_FOREACH_SAFE(chain->message_keys_head, cur_node, tmp_node) { if(cur_node->message_key.counter == counter) { memcpy(message_keys_result, &(cur_node->message_key), sizeof(ratchet_message_keys)); DL_DELETE(chain->message_keys_head, cur_node); axolotl_explicit_bzero(&cur_node->message_key, sizeof(ratchet_message_keys)); free(cur_node); return 1; } } return 0; } int session_state_set_message_keys(session_state *state, ec_public_key *sender_ephemeral, ratchet_message_keys *message_keys) { session_state_receiver_chain *chain = 0; message_keys_node *node = 0; int count; assert(state); assert(sender_ephemeral); assert(message_keys); chain = session_state_find_receiver_chain(state, sender_ephemeral); if(!chain) { return 0; } node = malloc(sizeof(message_keys_node)); if(!node) { return AX_ERR_NOMEM; } memcpy(&(node->message_key), message_keys, sizeof(ratchet_message_keys)); node->prev = 0; node->next = 0; DL_APPEND(chain->message_keys_head, node); DL_COUNT(chain->message_keys_head, node, count); while(count > MAX_MESSAGE_KEYS) { node = chain->message_keys_head; DL_DELETE(chain->message_keys_head, node); axolotl_explicit_bzero(&node->message_key, sizeof(ratchet_message_keys)); free(node); --count; } return 0; } int session_state_add_receiver_chain(session_state *state, ec_public_key *sender_ratchet_key, ratchet_chain_key *chain_key) { session_state_receiver_chain *node; int count; assert(state); assert(sender_ratchet_key); assert(chain_key); node = malloc(sizeof(session_state_receiver_chain)); if(!node) { return AX_ERR_NOMEM; } memset(node, 0, sizeof(session_state_receiver_chain)); AXOLOTL_REF(sender_ratchet_key); node->sender_ratchet_key = sender_ratchet_key; AXOLOTL_REF(chain_key); node->chain_key = chain_key; DL_APPEND(state->receiver_chain_head, node); DL_COUNT(state->receiver_chain_head, node, count); while(count > 5) { node = state->receiver_chain_head; DL_DELETE(state->receiver_chain_head, node); session_state_free_receiver_chain_node(node); --count; } return 0; } int session_state_set_receiver_chain_key(session_state *state, ec_public_key *sender_ephemeral, ratchet_chain_key *chain_key) { int result = 0; session_state_receiver_chain *node; assert(state); assert(sender_ephemeral); assert(chain_key); node = session_state_find_receiver_chain(state, sender_ephemeral); if(!node) { axolotl_log(state->global_context, AX_LOG_WARNING, "Couldn't find receiver chain to set chain key on"); result = AX_ERR_UNKNOWN; goto complete; } AXOLOTL_UNREF(node->chain_key); AXOLOTL_REF(chain_key); node->chain_key = chain_key; complete: return result; } static session_state_receiver_chain *session_state_find_receiver_chain(const session_state *state, const ec_public_key *sender_ephemeral) { session_state_receiver_chain *result = 0; session_state_receiver_chain *cur_node; DL_FOREACH(state->receiver_chain_head, cur_node) { if(ec_public_key_compare(cur_node->sender_ratchet_key, sender_ephemeral) == 0) { result = cur_node; break; } } return result; } ratchet_chain_key *session_state_get_receiver_chain_key(session_state *state, ec_public_key *sender_ephemeral) { ratchet_chain_key *result = 0; session_state_receiver_chain *node = session_state_find_receiver_chain(state, sender_ephemeral); if(node) { result = node->chain_key; } return result; } void session_state_set_pending_key_exchange(session_state *state, uint32_t sequence, ec_key_pair *our_base_key, ec_key_pair *our_ratchet_key, ratchet_identity_key_pair *our_identity_key) { assert(state); assert(our_base_key); assert(our_ratchet_key); assert(our_identity_key); if(state->pending_key_exchange.local_base_key) { AXOLOTL_UNREF(state->pending_key_exchange.local_base_key); state->pending_key_exchange.local_base_key = 0; } if(state->pending_key_exchange.local_ratchet_key) { AXOLOTL_UNREF(state->pending_key_exchange.local_ratchet_key); state->pending_key_exchange.local_ratchet_key = 0; } if(state->pending_key_exchange.local_identity_key) { AXOLOTL_UNREF(state->pending_key_exchange.local_identity_key); state->pending_key_exchange.local_identity_key = 0; } AXOLOTL_REF(our_base_key); AXOLOTL_REF(our_ratchet_key); AXOLOTL_REF(our_identity_key); state->has_pending_key_exchange = 1; state->pending_key_exchange.sequence = sequence; state->pending_key_exchange.local_base_key = our_base_key; state->pending_key_exchange.local_ratchet_key = our_ratchet_key; state->pending_key_exchange.local_identity_key = our_identity_key; } uint32_t session_state_get_pending_key_exchange_sequence(session_state *state) { assert(state); if(state->has_pending_key_exchange) { return state->pending_key_exchange.sequence; } else { return 0; } } ec_key_pair *session_state_get_pending_key_exchange_base_key(const session_state *state) { assert(state); if(state->has_pending_key_exchange) { return state->pending_key_exchange.local_base_key; } else { return 0; } } ec_key_pair *session_state_get_pending_key_exchange_ratchet_key(const session_state *state) { assert(state); if(state->has_pending_key_exchange) { return state->pending_key_exchange.local_ratchet_key; } else { return 0; } } ratchet_identity_key_pair *session_state_get_pending_key_exchange_identity_key(const session_state *state) { assert(state); if(state->has_pending_key_exchange) { return state->pending_key_exchange.local_identity_key; } else { return 0; } } int session_state_has_pending_key_exchange(const session_state *state) { assert(state); return state->has_pending_key_exchange; } void session_state_set_unacknowledged_pre_key_message(session_state *state, const uint32_t *pre_key_id, uint32_t signed_pre_key_id, ec_public_key *base_key) { assert(state); assert(base_key); if(state->pending_pre_key.base_key) { AXOLOTL_UNREF(state->pending_pre_key.base_key); state->pending_pre_key.base_key = 0; } AXOLOTL_REF(base_key); state->has_pending_pre_key = 1; if(pre_key_id) { state->pending_pre_key.has_pre_key_id = 1; state->pending_pre_key.pre_key_id = *pre_key_id; } else { state->pending_pre_key.has_pre_key_id = 0; state->pending_pre_key.pre_key_id = 0; } state->pending_pre_key.signed_pre_key_id = signed_pre_key_id; state->pending_pre_key.base_key = base_key; } int session_state_unacknowledged_pre_key_message_has_pre_key_id(const session_state *state) { assert(state); return state->pending_pre_key.has_pre_key_id; } uint32_t session_state_unacknowledged_pre_key_message_get_pre_key_id(const session_state *state) { assert(state); assert(state->pending_pre_key.has_pre_key_id); return state->pending_pre_key.pre_key_id; } uint32_t session_state_unacknowledged_pre_key_message_get_signed_pre_key_id(const session_state *state) { assert(state); return state->pending_pre_key.signed_pre_key_id; } ec_public_key *session_state_unacknowledged_pre_key_message_get_base_key(const session_state *state) { assert(state); return state->pending_pre_key.base_key; } int session_state_has_unacknowledged_pre_key_message(const session_state *state) { assert(state); return state->has_pending_pre_key; } void session_state_clear_unacknowledged_pre_key_message(session_state *state) { assert(state); if(state->pending_pre_key.base_key) { AXOLOTL_UNREF(state->pending_pre_key.base_key); } memset(&state->pending_pre_key, 0, sizeof(state->pending_pre_key)); state->has_pending_pre_key = 0; } void session_state_set_remote_registration_id(session_state *state, uint32_t id) { assert(state); state->remote_registration_id = id; } uint32_t session_state_get_remote_registration_id(const session_state *state) { assert(state); return state->remote_registration_id; } void session_state_set_local_registration_id(session_state *state, uint32_t id) { assert(state); state->local_registration_id = id; } uint32_t session_state_get_local_registration_id(const session_state *state) { assert(state); return state->local_registration_id; } void session_state_set_needs_refresh(session_state *state, int value) { assert(state); assert(value == 0 || value == 1); state->needs_refresh = value; } int session_state_get_needs_refresh(const session_state *state) { assert(state); return state->needs_refresh; } void session_state_set_alice_base_key(session_state *state, ec_public_key *key) { assert(state); assert(key); if(state->alice_base_key) { AXOLOTL_UNREF(state->alice_base_key); } AXOLOTL_REF(key); state->alice_base_key = key; } ec_public_key *session_state_get_alice_base_key(const session_state *state) { assert(state); return state->alice_base_key; } static void session_state_free_sender_chain(session_state *state) { if(state->sender_chain.sender_ratchet_key_pair) { AXOLOTL_UNREF(state->sender_chain.sender_ratchet_key_pair); state->sender_chain.sender_ratchet_key_pair = 0; } if(state->sender_chain.chain_key) { AXOLOTL_UNREF(state->sender_chain.chain_key); state->sender_chain.chain_key = 0; } if(state->sender_chain.message_keys_head) { message_keys_node *cur_node; message_keys_node *tmp_node; DL_FOREACH_SAFE(state->sender_chain.message_keys_head, cur_node, tmp_node) { DL_DELETE(state->sender_chain.message_keys_head, cur_node); axolotl_explicit_bzero(&cur_node->message_key, sizeof(ratchet_message_keys)); free(cur_node); } state->sender_chain.message_keys_head = 0; } } static void session_state_free_receiver_chain_node(session_state_receiver_chain *node) { if(node->sender_ratchet_key) { AXOLOTL_UNREF(node->sender_ratchet_key); } if(node->chain_key) { AXOLOTL_UNREF(node->chain_key); } if(node->message_keys_head) { message_keys_node *cur_node; message_keys_node *tmp_node; DL_FOREACH_SAFE(node->message_keys_head, cur_node, tmp_node) { DL_DELETE(node->message_keys_head, cur_node); axolotl_explicit_bzero(&cur_node->message_key, sizeof(ratchet_message_keys)); free(cur_node); } node->message_keys_head = 0; } free(node); } static void session_state_free_receiver_chain(session_state *state) { session_state_receiver_chain *cur_node; session_state_receiver_chain *tmp_node; DL_FOREACH_SAFE(state->receiver_chain_head, cur_node, tmp_node) { DL_DELETE(state->receiver_chain_head, cur_node); session_state_free_receiver_chain_node(cur_node); } state->receiver_chain_head = 0; } void session_state_destroy(axolotl_type_base *type) { session_state *state = (session_state *)type; if(state->local_identity_public) { AXOLOTL_UNREF(state->local_identity_public); } if(state->remote_identity_public) { AXOLOTL_UNREF(state->remote_identity_public); } if(state->root_key) { AXOLOTL_UNREF(state->root_key); } session_state_free_sender_chain(state); session_state_free_receiver_chain(state); if(state->has_pending_key_exchange) { if(state->pending_key_exchange.local_base_key) { AXOLOTL_UNREF(state->pending_key_exchange.local_base_key); } if(state->pending_key_exchange.local_ratchet_key) { AXOLOTL_UNREF(state->pending_key_exchange.local_ratchet_key); } if(state->pending_key_exchange.local_identity_key) { AXOLOTL_UNREF(state->pending_key_exchange.local_identity_key); } } if(state->has_pending_pre_key) { if(state->pending_pre_key.base_key) { AXOLOTL_UNREF(state->pending_pre_key.base_key); } } if(state->alice_base_key) { AXOLOTL_UNREF(state->alice_base_key); } free(state); }
gpl-3.0
ProgDan/maratona
SPOJ/INCSEQ.cpp
1
1341
#include<iostream> #include<stdio.h> #include<string.h> #include<vector> #include<queue> #include<algorithm> #include<set> #include<math.h> #include<map> using namespace std; #define mp make_pair #define pb push_back int inf=5000000,MAX=0; int t,n,k; int store[10001],inp[10001]; map <int,int> map1; int tree[60][10001]; //Query int read(int a[],int idx) { int sum=0; while(idx>0) { if( (sum+=a[idx]) >= inf) sum=sum-inf; idx -= (idx & -idx); } return sum; } //Update void update(int a[],int idx,int val) { while(idx<MAX) { if( (a[idx]+=val) >= inf ) a[idx]-=inf; idx += (idx & -idx); } } int main() { //freopen("input.txt","r",stdin); scanf("%d%d",&n,&k); for(int i=0;i<n;i++) { scanf("%d",&inp[i]); store[i]=inp[i]; } sort(inp,inp+n); map1[inp[0]]=++MAX; for(int i=1;i<n;i++) { if(inp[i]==inp[i-1]) map1[inp[i]]=MAX; else map1[inp[i]]=++MAX; } ++MAX; for(int i=0;i<n;i++) { int temp=map1[store[i]]; update(tree[1],temp,1); for(int j=1;j<k;j++) { int x=read(tree[j],temp-1); if(x) update(tree[j+1],temp,x); } } printf("%d\n",read(tree[k],MAX-1)); }
gpl-3.0
dparks1134/NetworkDiversity
source/SplitSystem.cpp
1
4691
//======================================================================= // Author: Donovan Parks // // Copyright 2009 Donovan Parks // // This file is part of Chameleon. // // Chameleon 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. // // Chameleon 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 Chameleon. If not, see <http://www.gnu.org/licenses/>. //======================================================================= #include "Precompiled.hpp" #include "SplitSystem.hpp" #include "NexusIO.hpp" #include "NewickIO.hpp" #include "SampleIO.hpp" bool SplitSystem::LoadData(const std::string& nexusFile, const std::string& newickFile, const std::string& sampleFile, bool bVerbose) { // read sample file if(!m_sampleIO.Read(sampleFile)) { std::cerr << "Failed to read sample file: " << sampleFile; return false; } // read nexus file if(!nexusFile.empty()) { NexusIO nexusIO; if(!nexusIO.Read(this, nexusFile)) { std::cerr << "Failed to read Nexus file: " << nexusFile; return false; } } else if(!newickFile.empty()) { NewickIO newickIO; if(!newickIO.Read(this, newickFile)) { std::cerr << "Failed to read Newick file: " << nexusFile; return false; } } if(bVerbose) { std::cout << " Number of samples: " << m_sampleIO.GetNumSamples() << std::endl; std::cout << " Number of splits: " << GetNumSplits() << std::endl; std::cout << " Total number of sequences: " << m_sampleIO.GetNumSeqs() << std::endl; std::cout << " Total number of ingroup sequences: " << m_sampleIO.GetNumIngroupSeqs() << std::endl; std::cout << std::endl; } return true; } std::vector<double> SplitSystem::GetSampleData(uint sampleId, DATA_TYPE dataType) { std::vector<double> data; data.resize(m_splits.size()); std::vector<double> seqCount; double totalNumSeq; m_sampleIO.GetData(sampleId, seqCount, totalNumSeq); for(uint splitId = 0; splitId < m_splits.size(); ++splitId) { std::vector<uint> leftSeqIds = m_splits.at(splitId).GetLeftSequenceIds(); for(uint i = 0; i < leftSeqIds.size(); ++i) { uint seqId = leftSeqIds.at(i); if(dataType == WEIGHTED_DATA) data.at(splitId) += seqCount.at(seqId) / totalNumSeq; else if(dataType == COUNT_DATA) data.at(splitId) += seqCount.at(seqId); else if(dataType == UNWEIGHTED_DATA) { if(seqCount.at(seqId) > 0) data.at(splitId) = 1; } } } return data; } void SplitSystem::CreateFromTree(Tree<Node>& tree) { std::set<std::string> seqsToRemove = m_sampleIO.GetOutgroupSeqs(); std::vector<std::string> seqsMissingInSampleFile; std::vector<Node*> leaves = tree.GetLeaves(tree.GetRootNode()); for(uint i = 0; i < leaves.size(); ++i) { uint seqId; std::string name = leaves.at(i)->GetName(); if(!m_sampleIO.GetSeqId(name, seqId)) { seqsToRemove.insert(name); if(m_sampleIO.GetOutgroupSeqs().count(name) == 0) seqsMissingInSampleFile.push_back(name); } } // report missing sequences if(seqsMissingInSampleFile.size() > 0) { std::cout << "(Warning) The following sequences are in your tree file, but not your sample file:" << std::endl; std::vector<std::string>::iterator iter; for(iter = seqsMissingInSampleFile.begin(); iter != seqsMissingInSampleFile.end(); ++iter) std::cout << *iter << std::endl; } // project tree to ingroup sequences if(seqsToRemove.size() > 0) tree.Project(seqsToRemove); std::vector<Node*> nodes = tree.PostOrder(tree.GetRootNode()); uint totalTaxa = m_sampleIO.GetNumIngroupSeqs(); for(uint i = 0; i < nodes.size(); ++i) { Node* curNode = nodes.at(i); if(curNode->IsRoot()) continue; // bit array indicates the id of sequences on the left (1) and right (0) of the split std::vector<bool> split(totalTaxa, false); std::vector<Node*> leaves = curNode->GetLeaves(); for(uint j = 0; j < leaves.size(); ++j) { std::string name = leaves.at(j)->GetName(); uint id; if(m_sampleIO.GetSeqId(name, id)) split[id] = true; else { assert(false); std::cerr << "(Bug) Unknown sequence name. Please report this bug." << std::endl; } } double weight = curNode->GetDistanceToParent(); AddSplit(Split(i, weight, split, false, true, leaves.size(), totalTaxa-leaves.size())); } }
gpl-3.0
teemuatlut/Marlin
Marlin/src/HAL/HAL_STM32F1/u8g_com_stm32duino_fsmc.cpp
1
8273
/** * Marlin 3D Printer Firmware * Copyright (C) 2019 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ /** * u8g_com_stm32duino_fsmc.cpp * * Communication interface for FSMC */ #include "../../inc/MarlinConfig.h" #if defined(ARDUINO_ARCH_STM32F1) && PIN_EXISTS(FSMC_CS) // FSMC on 100/144 pins SoCs #if HAS_GRAPHICAL_LCD #include "U8glib.h" #include "libmaple/fsmc.h" #include "libmaple/gpio.h" #include "boards.h" #define LCD_READ_ID 0x04 /* Read display identification information */ /* Timing configuration */ #define FSMC_ADDRESS_SETUP_TIME 15 // AddressSetupTime #define FSMC_DATA_SETUP_TIME 15 // DataSetupTime void LCD_IO_Init(uint8_t cs, uint8_t rs); void LCD_IO_WriteData(uint16_t RegValue); void LCD_IO_WriteReg(uint8_t Reg); uint32_t LCD_IO_ReadData(uint16_t RegValue, uint8_t ReadSize); static uint8_t msgInitCount = 2; // Ignore all messages until 2nd U8G_COM_MSG_INIT uint8_t u8g_com_stm32duino_fsmc_fn(u8g_t *u8g, uint8_t msg, uint8_t arg_val, void *arg_ptr) { if (msgInitCount) { if (msg == U8G_COM_MSG_INIT) msgInitCount--; if (msgInitCount) return -1; } static uint8_t isCommand; switch (msg) { case U8G_COM_MSG_STOP: break; case U8G_COM_MSG_INIT: u8g_SetPIOutput(u8g, U8G_PI_RESET); LCD_IO_Init(u8g->pin_list[U8G_PI_CS], u8g->pin_list[U8G_PI_A0]); u8g_Delay(100); if (arg_ptr != nullptr) *((uint32_t *)arg_ptr) = LCD_IO_ReadData(LCD_READ_ID, 3); isCommand = 0; break; case U8G_COM_MSG_ADDRESS: // define cmd (arg_val = 0) or data mode (arg_val = 1) isCommand = arg_val == 0 ? 1 : 0; break; case U8G_COM_MSG_RESET: u8g_SetPILevel(u8g, U8G_PI_RESET, arg_val); break; case U8G_COM_MSG_WRITE_BYTE: if (isCommand) LCD_IO_WriteReg(arg_val); else LCD_IO_WriteData((uint16_t)arg_val); break; case U8G_COM_MSG_WRITE_SEQ: for (uint8_t i = 0; i < arg_val; i += 2) LCD_IO_WriteData(*(uint16_t *)(((uint32_t)arg_ptr) + i)); break; } return 1; } /** * FSMC LCD IO */ #define __ASM __asm #define __STATIC_INLINE static inline __attribute__((always_inline)) __STATIC_INLINE void __DSB(void) { __ASM volatile ("dsb 0xF":::"memory"); } #define FSMC_CS_NE1 PD7 #ifdef STM32_XL_DENSITY #define FSMC_CS_NE2 PG9 #define FSMC_CS_NE3 PG10 #define FSMC_CS_NE4 PG12 #define FSMC_RS_A0 PF0 #define FSMC_RS_A1 PF1 #define FSMC_RS_A2 PF2 #define FSMC_RS_A3 PF3 #define FSMC_RS_A4 PF4 #define FSMC_RS_A5 PF5 #define FSMC_RS_A6 PF12 #define FSMC_RS_A7 PF13 #define FSMC_RS_A8 PF14 #define FSMC_RS_A9 PF15 #define FSMC_RS_A10 PG0 #define FSMC_RS_A11 PG1 #define FSMC_RS_A12 PG2 #define FSMC_RS_A13 PG3 #define FSMC_RS_A14 PG4 #define FSMC_RS_A15 PG5 #endif #define FSMC_RS_A16 PD11 #define FSMC_RS_A17 PD12 #define FSMC_RS_A18 PD13 #define FSMC_RS_A19 PE3 #define FSMC_RS_A20 PE4 #define FSMC_RS_A21 PE5 #define FSMC_RS_A22 PE6 #define FSMC_RS_A23 PE2 #ifdef STM32_XL_DENSITY #define FSMC_RS_A24 PG13 #define FSMC_RS_A25 PG14 #endif static uint8_t fsmcInit = 0; typedef struct { __IO uint16_t REG; __IO uint16_t RAM; } LCD_CONTROLLER_TypeDef; LCD_CONTROLLER_TypeDef *LCD; void LCD_IO_Init(uint8_t cs, uint8_t rs) { uint32_t controllerAddress; if (fsmcInit) return; fsmcInit = 1; switch (cs) { case FSMC_CS_NE1: controllerAddress = (uint32_t)FSMC_NOR_PSRAM_REGION1; break; #ifdef STM32_XL_DENSITY case FSMC_CS_NE2: controllerAddress = (uint32_t)FSMC_NOR_PSRAM_REGION2; break; case FSMC_CS_NE3: controllerAddress = (uint32_t)FSMC_NOR_PSRAM_REGION3; break; case FSMC_CS_NE4: controllerAddress = (uint32_t)FSMC_NOR_PSRAM_REGION4; break; #endif default: return; } #define _ORADDR(N) controllerAddress |= (_BV32(N) - 2) switch (rs) { #ifdef STM32_XL_DENSITY case FSMC_RS_A0: _ORADDR( 1); break; case FSMC_RS_A1: _ORADDR( 2); break; case FSMC_RS_A2: _ORADDR( 3); break; case FSMC_RS_A3: _ORADDR( 4); break; case FSMC_RS_A4: _ORADDR( 5); break; case FSMC_RS_A5: _ORADDR( 6); break; case FSMC_RS_A6: _ORADDR( 7); break; case FSMC_RS_A7: _ORADDR( 8); break; case FSMC_RS_A8: _ORADDR( 9); break; case FSMC_RS_A9: _ORADDR(10); break; case FSMC_RS_A10: _ORADDR(11); break; case FSMC_RS_A11: _ORADDR(12); break; case FSMC_RS_A12: _ORADDR(13); break; case FSMC_RS_A13: _ORADDR(14); break; case FSMC_RS_A14: _ORADDR(15); break; case FSMC_RS_A15: _ORADDR(16); break; #endif case FSMC_RS_A16: _ORADDR(17); break; case FSMC_RS_A17: _ORADDR(18); break; case FSMC_RS_A18: _ORADDR(19); break; case FSMC_RS_A19: _ORADDR(20); break; case FSMC_RS_A20: _ORADDR(21); break; case FSMC_RS_A21: _ORADDR(22); break; case FSMC_RS_A22: _ORADDR(23); break; case FSMC_RS_A23: _ORADDR(24); break; #ifdef STM32_XL_DENSITY case FSMC_RS_A24: _ORADDR(25); break; case FSMC_RS_A25: _ORADDR(26); break; #endif default: return; } rcc_clk_enable(RCC_FSMC); gpio_set_mode(GPIOD, 14, GPIO_AF_OUTPUT_PP); // FSMC_D00 gpio_set_mode(GPIOD, 15, GPIO_AF_OUTPUT_PP); // FSMC_D01 gpio_set_mode(GPIOD, 0, GPIO_AF_OUTPUT_PP); // FSMC_D02 gpio_set_mode(GPIOD, 1, GPIO_AF_OUTPUT_PP); // FSMC_D03 gpio_set_mode(GPIOE, 7, GPIO_AF_OUTPUT_PP); // FSMC_D04 gpio_set_mode(GPIOE, 8, GPIO_AF_OUTPUT_PP); // FSMC_D05 gpio_set_mode(GPIOE, 9, GPIO_AF_OUTPUT_PP); // FSMC_D06 gpio_set_mode(GPIOE, 10, GPIO_AF_OUTPUT_PP); // FSMC_D07 gpio_set_mode(GPIOE, 11, GPIO_AF_OUTPUT_PP); // FSMC_D08 gpio_set_mode(GPIOE, 12, GPIO_AF_OUTPUT_PP); // FSMC_D09 gpio_set_mode(GPIOE, 13, GPIO_AF_OUTPUT_PP); // FSMC_D10 gpio_set_mode(GPIOE, 14, GPIO_AF_OUTPUT_PP); // FSMC_D11 gpio_set_mode(GPIOE, 15, GPIO_AF_OUTPUT_PP); // FSMC_D12 gpio_set_mode(GPIOD, 8, GPIO_AF_OUTPUT_PP); // FSMC_D13 gpio_set_mode(GPIOD, 9, GPIO_AF_OUTPUT_PP); // FSMC_D14 gpio_set_mode(GPIOD, 10, GPIO_AF_OUTPUT_PP); // FSMC_D15 gpio_set_mode(GPIOD, 4, GPIO_AF_OUTPUT_PP); // FSMC_NOE gpio_set_mode(GPIOD, 5, GPIO_AF_OUTPUT_PP); // FSMC_NWE gpio_set_mode(PIN_MAP[cs].gpio_device, PIN_MAP[cs].gpio_bit, GPIO_AF_OUTPUT_PP); //FSMC_CS_NEx gpio_set_mode(PIN_MAP[rs].gpio_device, PIN_MAP[rs].gpio_bit, GPIO_AF_OUTPUT_PP); //FSMC_RS_Ax #ifdef STM32_XL_DENSITY FSMC_NOR_PSRAM4_BASE->BCR = FSMC_BCR_WREN | FSMC_BCR_MTYP_SRAM | FSMC_BCR_MWID_16BITS | FSMC_BCR_MBKEN; FSMC_NOR_PSRAM4_BASE->BTR = (FSMC_DATA_SETUP_TIME << 8) | FSMC_ADDRESS_SETUP_TIME; #else // PSRAM1 for STM32F103V (high density) FSMC_NOR_PSRAM1_BASE->BCR = FSMC_BCR_WREN | FSMC_BCR_MTYP_SRAM | FSMC_BCR_MWID_16BITS | FSMC_BCR_MBKEN; FSMC_NOR_PSRAM1_BASE->BTR = (FSMC_DATA_SETUP_TIME << 8) | FSMC_ADDRESS_SETUP_TIME; #endif afio_remap(AFIO_REMAP_FSMC_NADV); LCD = (LCD_CONTROLLER_TypeDef*)controllerAddress; } void LCD_IO_WriteData(uint16_t RegValue) { LCD->RAM = RegValue; __DSB(); } void LCD_IO_WriteReg(uint8_t Reg) { LCD->REG = (uint16_t)Reg; __DSB(); } uint32_t LCD_IO_ReadData(uint16_t RegValue, uint8_t ReadSize) { volatile uint32_t data; LCD->REG = (uint16_t)RegValue; __DSB(); data = LCD->RAM; // dummy read data = LCD->RAM & 0x00FF; while (--ReadSize) { data <<= 8; data |= (LCD->RAM & 0x00FF); } return (uint32_t)data; } #endif // HAS_GRAPHICAL_LCD #endif // ARDUINO_ARCH_STM32F1 && FSMC_CS_PIN
gpl-3.0
dfm/batman
c_src/_quadratic_ld.c
1
10548
/* The batman package: fast computation of exoplanet transit light curves * Copyright (C) 2015 Laura Kreidberg * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION #include <Python.h> #include "numpy/arrayobject.h" #include <math.h> #if defined (_OPENMP) # include <omp.h> #endif #define MIN(x, y) (((x) < (y)) ? (x) : (y)) #define MAX(x, y) (((x) > (y)) ? (x) : (y)) double ellpic_bulirsch(double n, double k); double ellec(double k); double ellk(double k); static PyObject *_quadratic_ld(PyObject *self, PyObject *args); static PyObject *_quadratic_ld(PyObject *self, PyObject *args) { /* Input: ************************************* ds array of impact parameters in units of rs c1 linear limb-darkening coefficient (gamma_1 in Mandel & Agol 2002) c2 quadratic limb-darkening coefficient (gamma_2) p occulting star size in units of rs Output: *********************************** flux fraction of flux at each ds for a limb-darkened source Limb darkening has the form: I(r) = [1 - c1 * (1 - sqrt(1 - (r/rs)^2)) - c2*(1 - sqrt(1 - (r/rs)^2))^2]/(1 - c1/3 - c2/6)/pi */ int nd, nthreads; double c1, c2, p, *mu, *lambdad, *etad, \ *lambdae, lam, x1, x2, x3, d, omega, kap0 = 0.0, kap1 = 0.0, \ q, Kk, Ek, Pk, n; PyArrayObject *ds, *flux; npy_intp i, dims[1]; if(!PyArg_ParseTuple(args,"Odddi", &ds, &p, &c1, &c2, &nthreads)) return NULL; dims[0] = PyArray_DIMS(ds)[0]; flux = (PyArrayObject *) PyArray_SimpleNew(1, dims, PyArray_TYPE(ds)); //creates numpy array to store return flux values nd = (int)dims[0]; double *f_array = PyArray_DATA(flux); double *d_array = PyArray_DATA(ds); /* NOTE: the safest way to access numpy arrays is to use the PyArray_GETITEM and PyArray_SETITEM functions. Here we use a trick for faster access and more convenient access, where we set a pointer to the beginning of the array with the PyArray_DATA (e.g., f_array) and access elements with e.g., f_array[i]. Success of this operation depends on the numpy array storing data in blocks equal in size to a C double. If you run into trouble along these lines, I recommend changing the array access to something like: d = PyFloat_AsDouble(PyArray_GETITEM(ds, PyArray_GetPtr(ds, &i))); where ds is a numpy array object. Laura Kreidberg 07/2015 */ lambdad = (double *)malloc(nd*sizeof(double)); lambdae = (double *)malloc(nd*sizeof(double)); etad = (double *)malloc(nd*sizeof(double)); mu = (double *)malloc(nd*sizeof(double)); if(fabs(p - 0.5) < 1.0e-3) p = 0.5; omega = 1.0 - c1/3.0 - c2/6.0; #if defined (_OPENMP) omp_set_num_threads(nthreads); #endif #if defined (_OPENMP) #pragma omp parallel for private(d, x1, x2, x3, n, q, Kk, Ek, Pk, kap0, kap1) #endif for(i = 0; i < dims[0]; i++) { d = d_array[i]; // separation of centers x1 = pow((p - d), 2.0); x2 = pow((p + d), 2.0); x3 = p*p - d*d; //source is unocculted: if(d >= 1.0 + p) { //printf("zone 1\n"); lambdad[i] = 0.0; etad[i] = 0.0; lambdae[i] = 0.0; f_array[i] = 1.0 - ((1.0 - c1 - 2.0*c2)*lambdae[i] + (c1 + 2.0*c2)*lambdad[i] + c2*etad[i])/omega; continue; } //source is completely occulted: if(p >= 1.0 && d <= p - 1.0) { //printf("zone 2\n"); lambdad[i] = 0.0; etad[i] = 0.5; //error in Fortran code corrected here, following Jason Eastman's python code lambdae[i] = 1.0; f_array[i] = 1.0 - ((1.0 - c1 - 2.0*c2)*lambdae[i] + (c1 + 2.0*c2)*(lambdad[i] + 2.0/3.0) + c2*etad[i])/omega; continue; } //source is partly occulted and occulting object crosses the limb: if(d >= fabs(1.0 - p) && d <= 1.0 + p) { //printf("zone 3\n"); kap1 = acos(MIN((1.0 - p*p + d*d)/2.0/d, 1.0)); kap0 = acos(MIN((p*p + d*d - 1.0)/2.0/p/d, 1.0)); lambdae[i] = p*p*kap0 + kap1; lambdae[i] = (lambdae[i] - 0.50*sqrt(MAX(4.0*d*d - pow((1.0 + d*d - p*p), 2.0), 0.0)))/M_PI; } //occulting object transits the source but doesn't completely cover it: if(d <= 1.0 - p) { //printf("zone 4\n"); lambdae[i] = p*p; } //edge of the occulting star lies at the origin if(fabs(d - p) < 1.0e-4*(d + p)) { d = p; //printf("zone 5\n"); if(p == 0.5) { //printf("zone 6\n"); lambdad[i] = 1.0/3.0 - 4.0/M_PI/9.0; etad[i] = 3.0/32.0; f_array[i] = 1.0 - ((1.0 - c1 - 2.0*c2)*lambdae[i] + (c1 + 2.0*c2)*lambdad[i] + c2*etad[i])/omega; continue; } else if(d >= 0.5) { //printf("zone 5.1\n"); lam = 0.5*M_PI; q = 0.5/p; Kk = ellk(q); Ek = ellec(q); lambdad[i] = 1.0/3.0 + 16.0*p/9.0/M_PI*(2.0*p*p - 1.0)*Ek - \ (32.0*pow(p, 4.0) - 20.0*p*p + 3.0)/9.0/M_PI/p*Kk; etad[i] = 1.0/2.0/M_PI*(kap1 + p*p*(p*p + 2.0*d*d)*kap0 - \ (1.0 + 5.0*p*p + d*d)/4.0*sqrt((1.0 - x1)*(x2 - 1.0))); // continue; } else if(d<0.5) { //printf("zone 5.2\n"); lam = 0.50*M_PI; q = 2.0*p; Kk = ellk(q); Ek = ellec(q); lambdad[i] = 1.0/3.0 + 2.0/9.0/M_PI*(4.0*(2.0*p*p - 1.0)*Ek + (1.0 - 4.0*p*p)*Kk); etad[i] = p*p/2.0*(p*p + 2.0*d*d); f_array[i] = 1.0 - ((1.0 - c1 - 2.0*c2)*lambdae[i] + (c1 + 2.0*c2)*lambdad[i] + c2*etad[i])/omega; continue; } f_array[i] = 1.0 - ((1.0 - c1 - 2.0*c2)*lambdae[i] + (c1 + 2.0*c2)*lambdad[i] + c2*etad[i])/omega; continue; } //occulting star partly occults the source and crosses the limb: if((d > 0.5 + fabs(p - 0.5) && d < 1.0 + p) || (p > 0.5 && d > fabs(1.0 - p)*1.0001 \ && d < p)) { //printf("zone 3.1\n"); lam = 0.50*M_PI; q = sqrt((1.0 - pow((p - d), 2.0))/4.0/d/p); Kk = ellk(q); Ek = ellec(q); n = 1.0/x1 - 1.0; Pk = ellpic_bulirsch(n, q); lambdad[i] = 1.0/9.0/M_PI/sqrt(p*d)*(((1.0 - x2)*(2.0*x2 + \ x1 - 3.0) - 3.0*x3*(x2 - 2.0))*Kk + 4.0*p*d*(d*d + \ 7.0*p*p - 4.0)*Ek - 3.0*x3/x1*Pk); if(d < p) lambdad[i] += 2.0/3.0; etad[i] = 1.0/2.0/M_PI*(kap1 + p*p*(p*p + 2.0*d*d)*kap0 - \ (1.0 + 5.0*p*p + d*d)/4.0*sqrt((1.0 - x1)*(x2 - 1.0))); f_array[i] = 1.0 - ((1.0 - c1 - 2.0*c2)*lambdae[i] + (c1 + 2.0*c2)*lambdad[i] + c2*etad[i])/omega; continue; } //occulting star transits the source: if(p <= 1.0 && d <= (1.0 - p)*1.0001) { //printf("zone 4.1\n"); lam = 0.50*M_PI; q = sqrt((x2 - x1)/(1.0 - x1)); Kk = ellk(q); Ek = ellec(q); n = x2/x1 - 1.0; Pk = ellpic_bulirsch(n, q); lambdad[i] = 2.0/9.0/M_PI/sqrt(1.0 - x1)*((1.0 - 5.0*d*d + p*p + \ x3*x3)*Kk + (1.0 - x1)*(d*d + 7.0*p*p - 4.0)*Ek - 3.0*x3/x1*Pk); if(d < p) lambdad[i] += 2.0/3.0; if(fabs(p + d - 1.0) <= 1.0e-4) { lambdad[i] = 2.0/3.0/M_PI*acos(1.0 - 2.0*p) - 4.0/9.0/M_PI* \ sqrt(p*(1.0 - p))*(3.0 + 2.0*p - 8.0*p*p); } etad[i] = p*p/2.0*(p*p + 2.0*d*d); } f_array[i] = 1.0 - ((1.0 - c1 - 2.0*c2)*lambdae[i] + (c1 + 2.0*c2)*lambdad[i] + c2*etad[i])/omega; } free(lambdae); free(lambdad); free(etad); free(mu); return PyArray_Return((PyArrayObject *)flux); } /* Computes the complete elliptical integral of the third kind using the algorithm of Bulirsch (1965): Bulirsch 1965, Numerische Mathematik, 7, 78 Bulirsch 1965, Numerische Mathematik, 7, 353 INPUTS: n,k - int(dtheta/((1-n*sin(theta)^2)*sqrt(1-k^2*sin(theta)^2)),0, pi/2) RESULT: The complete elliptical integral of the third kind -- translated from the ellpic_bulirsch.pro routine from EXOFAST (Eastman et al. 2013, PASP 125, 83) by Laura Kreidberg (7/22/15) */ double ellpic_bulirsch(double n, double k) { double kc = sqrt(1.-k*k); double p = sqrt(n + 1.); double m0 = 1.; double c = 1.; double d = 1./p; double e = kc; double f, g; int nit = 0; while(nit < 10000) { f = c; c = d/p + c; g = e/p; d = 2.*(f*g + d); p = g + p; g = m0; m0 = kc + m0; if(fabs(1.-kc/g) > 1.0e-8) { kc = 2.*sqrt(e); e = kc*m0; } else { return 0.5*M_PI*(c*m0+d)/(m0*(m0+p)); } nit++; } printf("Convergence failure in ellpic_bulirsch\n"); return 0; } double ellec(double k) { double m1, a1, a2, a3, a4, b1, b2, b3, b4, ee1, ee2, ellec; // Computes polynomial approximation for the complete elliptic // integral of the second kind (Hasting's approximation): m1 = 1.0 - k*k; a1 = 0.44325141463; a2 = 0.06260601220; a3 = 0.04757383546; a4 = 0.01736506451; b1 = 0.24998368310; b2 = 0.09200180037; b3 = 0.04069697526; b4 = 0.00526449639; ee1 = 1.0 + m1*(a1 + m1*(a2 + m1*(a3 + m1*a4))); ee2 = m1*(b1 + m1*(b2 + m1*(b3 + m1*b4)))*log(1.0/m1); ellec = ee1 + ee2; return ellec; } double ellk(double k) { double a0, a1, a2, a3, a4, b0, b1, b2, b3, b4, ellk, ek1, ek2, m1; // Computes polynomial approximation for the complete elliptic // integral of the first kind (Hasting's approximation): m1 = 1.0 - k*k; a0 = 1.38629436112; a1 = 0.09666344259; a2 = 0.03590092383; a3 = 0.03742563713; a4 = 0.01451196212; b0 = 0.5; b1 = 0.12498593597; b2 = 0.06880248576; b3 = 0.03328355346; b4 = 0.00441787012; ek1 = a0 + m1*(a1 + m1*(a2 + m1*(a3 + m1*a4))); ek2 = (b0 + m1*(b1 + m1*(b2 + m1*(b3 + m1*b4))))*log(m1); ellk = ek1 - ek2; return ellk; } static char _quadratic_ld_doc[] = "This extension module returns a limb darkened light curve for a quadratic stellar intensity profile."; static PyMethodDef _quadratic_ld_methods[] = { {"_quadratic_ld", _quadratic_ld, METH_VARARGS, _quadratic_ld_doc},{NULL}}; #if PY_MAJOR_VERSION >= 3 static struct PyModuleDef _quadratic_ld_module = { PyModuleDef_HEAD_INIT, "_quadratic_ld", _quadratic_ld_doc, -1, _quadratic_ld_methods }; PyMODINIT_FUNC PyInit__quadratic_ld(void) { PyObject* module = PyModule_Create(&_quadratic_ld_module); if(!module) { return NULL; } import_array(); return module; } #else void init_quadratic_ld(void) { Py_InitModule("_quadratic_ld", _quadratic_ld_methods); import_array(); } #endif
gpl-3.0
Fizzixnerd/fizzixmacs
elpa/irony-20170404.1127/server/src/Irony.cpp
1
13256
/** * \file * \author Guillaume Papin <guillaume.papin@epitech.eu> * * \brief irony-server "API" definitions. * * \sa Irony.h for more information. * * This file is distributed under the GNU General Public License. See * COPYING for details. */ #include "Irony.h" #include "support/iomanip_quoted.h" #include <algorithm> #include <cassert> #include <iostream> static std::string cxStringToStd(CXString cxString) { std::string stdStr; if (const char *cstr = clang_getCString(cxString)) { stdStr = cstr; } clang_disposeString(cxString); return stdStr; } Irony::Irony() : activeTu_(nullptr), debug_(false) { } static const char *diagnosticSeverity(CXDiagnostic diagnostic) { switch (clang_getDiagnosticSeverity(diagnostic)) { case CXDiagnostic_Ignored: return "ignored"; case CXDiagnostic_Note: return "note"; case CXDiagnostic_Warning: return "warning"; case CXDiagnostic_Error: return "error"; case CXDiagnostic_Fatal: return "fatal"; } return "unknown"; } static void dumpDiagnostics(const CXTranslationUnit &tu) { std::cout << "(\n"; std::string file; for (unsigned i = 0, diagnosticCount = clang_getNumDiagnostics(tu); i < diagnosticCount; ++i) { CXDiagnostic diagnostic = clang_getDiagnostic(tu, i); CXSourceLocation location = clang_getDiagnosticLocation(diagnostic); unsigned line, column, offset; if (clang_equalLocations(location, clang_getNullLocation())) { file.clear(); line = 0; column = 0; offset = 0; } else { CXFile cxFile; // clang_getInstantiationLocation() has been marked deprecated and // is aimed to be replaced by clang_getExpansionLocation(). #if CINDEX_VERSION >= 6 clang_getExpansionLocation(location, &cxFile, &line, &column, &offset); #else clang_getInstantiationLocation(location, &cxFile, &line, &column, &offset); #endif file = cxStringToStd(clang_getFileName(cxFile)); } const char *severity = diagnosticSeverity(diagnostic); std::string message = cxStringToStd(clang_getDiagnosticSpelling(diagnostic)); std::cout << '(' << support::quoted(file) // << ' ' << line // << ' ' << column // << ' ' << offset // << ' ' << severity // << ' ' << support::quoted(message) // << ")\n"; clang_disposeDiagnostic(diagnostic); } std::cout << ")\n"; } void Irony::parse(const std::string &file, const std::vector<std::string> &flags, const std::vector<CXUnsavedFile> &unsavedFiles) { activeTu_ = tuManager_.parse(file, flags, unsavedFiles); file_ = file; std::cout << (activeTu_ ? "t" : "nil") << "\n"; } void Irony::diagnostics() const { if (activeTu_ == nullptr) { std::clog << "W: diagnostics - parse wasn't called\n"; std::cout << "nil\n"; return; } dumpDiagnostics(activeTu_); } void Irony::getType(unsigned line, unsigned col) const { if (activeTu_ == nullptr) { std::clog << "W: get-type - parse wasn't called\n"; std::cout << "nil\n"; return; } CXFile cxFile = clang_getFile(activeTu_, file_.c_str()); CXSourceLocation sourceLoc = clang_getLocation(activeTu_, cxFile, line, col); CXCursor cursor = clang_getCursor(activeTu_, sourceLoc); if (clang_Cursor_isNull(cursor)) { // TODO: "error: no type at point"? std::cout << "nil"; return; } CXType cxTypes[2]; cxTypes[0] = clang_getCursorType(cursor); cxTypes[1] = clang_getCanonicalType(cxTypes[0]); std::cout << "("; for (const CXType &cxType : cxTypes) { CXString typeDescr = clang_getTypeSpelling(cxType); std::string typeStr = clang_getCString(typeDescr); clang_disposeString(typeDescr); if (typeStr.empty()) break; std::cout << support::quoted(typeStr) << " "; } std::cout << ")\n"; } namespace { class CompletionChunk { public: explicit CompletionChunk(CXCompletionString completionString) : completionString_(completionString) , numChunks_(clang_getNumCompletionChunks(completionString_)) , chunkIdx_(0) { } bool hasNext() const { return chunkIdx_ < numChunks_; } void next() { if (!hasNext()) { assert(0 && "out of range completion chunk"); abort(); } ++chunkIdx_; } CXCompletionChunkKind kind() const { return clang_getCompletionChunkKind(completionString_, chunkIdx_); } std::string text() const { return cxStringToStd( clang_getCompletionChunkText(completionString_, chunkIdx_)); } private: CXCompletionString completionString_; unsigned int numChunks_; unsigned chunkIdx_; }; } // unnamed namespace void Irony::complete(const std::string &file, unsigned line, unsigned col, const std::vector<std::string> &flags, const std::vector<CXUnsavedFile> &unsavedFiles) { CXTranslationUnit tu = tuManager_.getOrCreateTU(file, flags, unsavedFiles); if (tu == nullptr) { std::cout << "nil\n"; return; } if (CXCodeCompleteResults *completions = clang_codeCompleteAt(tu, file.c_str(), line, col, const_cast<CXUnsavedFile *>(unsavedFiles.data()), unsavedFiles.size(), (clang_defaultCodeCompleteOptions() & ~CXCodeComplete_IncludeCodePatterns) #if HAS_BRIEF_COMMENTS_IN_COMPLETION | CXCodeComplete_IncludeBriefComments #endif )) { if (debug_) { unsigned numDiags = clang_codeCompleteGetNumDiagnostics(completions); std::clog << "debug: complete: " << numDiags << " diagnostic(s)\n"; for (unsigned i = 0; i < numDiags; ++i) { CXDiagnostic diagnostic = clang_codeCompleteGetDiagnostic(completions, i); CXString s = clang_formatDiagnostic( diagnostic, clang_defaultDiagnosticDisplayOptions()); std::clog << clang_getCString(s) << std::endl; clang_disposeString(s); clang_disposeDiagnostic(diagnostic); } } clang_sortCodeCompletionResults(completions->Results, completions->NumResults); std::cout << "(\n"; // re-use the same buffers to avoid unnecessary allocations std::string typedtext, brief, resultType, prototype, postCompCar, available; std::vector<unsigned> postCompCdr; for (unsigned i = 0; i < completions->NumResults; ++i) { CXCompletionResult candidate = completions->Results[i]; CXAvailabilityKind availability = clang_getCompletionAvailability(candidate.CompletionString); unsigned priority = clang_getCompletionPriority(candidate.CompletionString); unsigned annotationStart = 0; bool typedTextSet = false; typedtext.clear(); brief.clear(); resultType.clear(); prototype.clear(); postCompCar.clear(); postCompCdr.clear(); available.clear(); switch (availability) { case CXAvailability_NotAvailable: // No benefits to expose this to elisp for now continue; case CXAvailability_Available: available = "available"; break; case CXAvailability_Deprecated: available = "deprecated"; break; case CXAvailability_NotAccessible: available = "not-accessible"; break; } for (CompletionChunk chunk(candidate.CompletionString); chunk.hasNext(); chunk.next()) { char ch = 0; auto chunkKind = chunk.kind(); switch (chunkKind) { case CXCompletionChunk_ResultType: resultType = chunk.text(); break; case CXCompletionChunk_TypedText: case CXCompletionChunk_Text: case CXCompletionChunk_Placeholder: case CXCompletionChunk_Informative: case CXCompletionChunk_CurrentParameter: prototype += chunk.text(); break; case CXCompletionChunk_LeftParen: ch = '('; break; case CXCompletionChunk_RightParen: ch = ')'; break; case CXCompletionChunk_LeftBracket: ch = '['; break; case CXCompletionChunk_RightBracket: ch = ']'; break; case CXCompletionChunk_LeftBrace: ch = '{'; break; case CXCompletionChunk_RightBrace: ch = '}'; break; case CXCompletionChunk_LeftAngle: ch = '<'; break; case CXCompletionChunk_RightAngle: ch = '>'; break; case CXCompletionChunk_Comma: ch = ','; break; case CXCompletionChunk_Colon: ch = ':'; break; case CXCompletionChunk_SemiColon: ch = ';'; break; case CXCompletionChunk_Equal: ch = '='; break; case CXCompletionChunk_HorizontalSpace: ch = ' '; break; case CXCompletionChunk_VerticalSpace: ch = '\n'; break; case CXCompletionChunk_Optional: // ignored for now break; } if (ch != 0) { prototype += ch; // commas look better followed by a space if (ch == ',') { prototype += ' '; } } if (typedTextSet) { if (ch != 0) { postCompCar += ch; if (ch == ',') { postCompCar += ' '; } } else if (chunkKind == CXCompletionChunk_Text || chunkKind == CXCompletionChunk_TypedText) { postCompCar += chunk.text(); } else if (chunkKind == CXCompletionChunk_Placeholder || chunkKind == CXCompletionChunk_CurrentParameter) { postCompCdr.push_back(postCompCar.size()); postCompCar += chunk.text(); postCompCdr.push_back(postCompCar.size()); } } // Consider only the first typed text. The CXCompletionChunk_TypedText // doc suggests that exactly one typed text will be given but at least // in Objective-C it seems that more than one can appear, see: // https://github.com/Sarcasm/irony-mode/pull/78#issuecomment-37115538 if (chunkKind == CXCompletionChunk_TypedText && !typedTextSet) { typedtext = chunk.text(); // annotation is what comes after the typedtext annotationStart = prototype.size(); typedTextSet = true; } } #if HAS_BRIEF_COMMENTS_IN_COMPLETION brief = cxStringToStd( clang_getCompletionBriefComment(candidate.CompletionString)); #endif // see irony-completion.el#irony-completion-candidates std::cout << '(' << support::quoted(typedtext) << ' ' << priority << ' ' << support::quoted(resultType) << ' ' << support::quoted(brief) << ' ' << support::quoted(prototype) << ' ' << annotationStart << " (" << support::quoted(postCompCar); for (unsigned index : postCompCdr) std::cout << ' ' << index; std::cout << ")" << ' ' << available << ")\n"; } clang_disposeCodeCompleteResults(completions); std::cout << ")\n"; } } void Irony::getCompileOptions(const std::string &buildDir, const std::string &file) const { #if !(HAS_COMPILATION_DATABASE) (void)buildDir; (void)file; std::cout << "nil\n"; return; #else CXCompilationDatabase_Error error; CXCompilationDatabase db = clang_CompilationDatabase_fromDirectory(buildDir.c_str(), &error); switch (error) { case CXCompilationDatabase_CanNotLoadDatabase: std::clog << "I: could not load compilation database in '" << buildDir << "'\n"; std::cout << "nil\n"; return; case CXCompilationDatabase_NoError: break; } CXCompileCommands compileCommands = clang_CompilationDatabase_getCompileCommands(db, file.c_str()); std::cout << "(\n"; for (unsigned i = 0, numCompileCommands = clang_CompileCommands_getSize(compileCommands); i < numCompileCommands; ++i) { CXCompileCommand compileCommand = clang_CompileCommands_getCommand(compileCommands, i); std::cout << "(" << "("; for (unsigned j = 0, numArgs = clang_CompileCommand_getNumArgs(compileCommand); j < numArgs; ++j) { CXString arg = clang_CompileCommand_getArg(compileCommand, j); std::cout << support::quoted(clang_getCString(arg)) << " "; clang_disposeString(arg); } std::cout << ")" << " . "; CXString directory = clang_CompileCommand_getDirectory(compileCommand); std::cout << support::quoted(clang_getCString(directory)); clang_disposeString(directory); std::cout << ")\n"; } std::cout << ")\n"; clang_CompileCommands_dispose(compileCommands); clang_CompilationDatabase_dispose(db); #endif }
gpl-3.0
CertifiedBlyndGuy/ewok-onyx
arch/arm/mach-mxs/devices/platform-rtc-stmp3xxx.c
5121
1263
/* * Copyright (C) 2011 Pengutronix, Wolfram Sang <w.sang@pengutronix.de> * * 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. */ #include <asm/sizes.h> #include <mach/mx23.h> #include <mach/mx28.h> #include <mach/devices-common.h> #ifdef CONFIG_SOC_IMX23 struct platform_device *__init mx23_add_rtc_stmp3xxx(void) { struct resource res[] = { { .start = MX23_RTC_BASE_ADDR, .end = MX23_RTC_BASE_ADDR + SZ_8K - 1, .flags = IORESOURCE_MEM, }, { .start = MX23_INT_RTC_ALARM, .end = MX23_INT_RTC_ALARM, .flags = IORESOURCE_IRQ, }, }; return mxs_add_platform_device("stmp3xxx-rtc", 0, res, ARRAY_SIZE(res), NULL, 0); } #endif /* CONFIG_SOC_IMX23 */ #ifdef CONFIG_SOC_IMX28 struct platform_device *__init mx28_add_rtc_stmp3xxx(void) { struct resource res[] = { { .start = MX28_RTC_BASE_ADDR, .end = MX28_RTC_BASE_ADDR + SZ_8K - 1, .flags = IORESOURCE_MEM, }, { .start = MX28_INT_RTC_ALARM, .end = MX28_INT_RTC_ALARM, .flags = IORESOURCE_IRQ, }, }; return mxs_add_platform_device("stmp3xxx-rtc", 0, res, ARRAY_SIZE(res), NULL, 0); } #endif /* CONFIG_SOC_IMX28 */
gpl-3.0
AndKe/ardupilot
ArduSub/GCS_Mavlink.cpp
2
28085
#include "Sub.h" #include "GCS_Mavlink.h" /* * !!NOTE!! * * the use of NOINLINE separate functions for each message type avoids * a compiler bug in gcc that would cause it to use far more stack * space than is needed. Without the NOINLINE we use the sum of the * stack needed for each message type. Please be careful to follow the * pattern below when adding any new messages */ MAV_TYPE GCS_Sub::frame_type() const { return MAV_TYPE_SUBMARINE; } MAV_MODE GCS_MAVLINK_Sub::base_mode() const { uint8_t _base_mode = MAV_MODE_FLAG_STABILIZE_ENABLED; // work out the base_mode. This value is not very useful // for APM, but we calculate it as best we can so a generic // MAVLink enabled ground station can work out something about // what the MAV is up to. The actual bit values are highly // ambiguous for most of the APM flight modes. In practice, you // only get useful information from the custom_mode, which maps to // the APM flight mode and has a well defined meaning in the // ArduPlane documentation switch (sub.control_mode) { case AUTO: case GUIDED: case CIRCLE: case POSHOLD: _base_mode |= MAV_MODE_FLAG_GUIDED_ENABLED; // note that MAV_MODE_FLAG_AUTO_ENABLED does not match what // APM does in any mode, as that is defined as "system finds its own goal // positions", which APM does not currently do break; default: break; } // all modes except INITIALISING have some form of manual // override if stick mixing is enabled _base_mode |= MAV_MODE_FLAG_MANUAL_INPUT_ENABLED; if (sub.motors.armed()) { _base_mode |= MAV_MODE_FLAG_SAFETY_ARMED; } // indicate we have set a custom mode _base_mode |= MAV_MODE_FLAG_CUSTOM_MODE_ENABLED; return (MAV_MODE)_base_mode; } uint32_t GCS_Sub::custom_mode() const { return sub.control_mode; } MAV_STATE GCS_MAVLINK_Sub::vehicle_system_status() const { // set system as critical if any failsafe have triggered if (sub.any_failsafe_triggered()) { return MAV_STATE_CRITICAL; } if (sub.motors.armed()) { return MAV_STATE_ACTIVE; } return MAV_STATE_STANDBY; } void GCS_MAVLINK_Sub::send_nav_controller_output() const { const Vector3f &targets = sub.attitude_control.get_att_target_euler_cd(); mavlink_msg_nav_controller_output_send( chan, targets.x * 1.0e-2f, targets.y * 1.0e-2f, targets.z * 1.0e-2f, sub.wp_nav.get_wp_bearing_to_destination() * 1.0e-2f, MIN(sub.wp_nav.get_wp_distance_to_destination() * 1.0e-2f, UINT16_MAX), sub.pos_control.get_alt_error() * 1.0e-2f, 0, 0); } int16_t GCS_MAVLINK_Sub::vfr_hud_throttle() const { return (int16_t)(sub.motors.get_throttle() * 100); } // Work around to get temperature sensor data out void GCS_MAVLINK_Sub::send_scaled_pressure3() { if (!sub.celsius.healthy()) { return; } mavlink_msg_scaled_pressure3_send( chan, AP_HAL::millis(), 0, 0, sub.celsius.temperature() * 100, 0); // TODO: use differential pressure temperature } bool GCS_MAVLINK_Sub::send_info() { // Just do this all at once, hopefully the hard-wire telemetry requirement means this is ok // Name is char[10] CHECK_PAYLOAD_SIZE(NAMED_VALUE_FLOAT); send_named_float("CamTilt", 1 - (SRV_Channels::get_output_norm(SRV_Channel::k_mount_tilt) / 2.0f + 0.5f)); CHECK_PAYLOAD_SIZE(NAMED_VALUE_FLOAT); send_named_float("CamPan", 1 - (SRV_Channels::get_output_norm(SRV_Channel::k_mount_pan) / 2.0f + 0.5f)); CHECK_PAYLOAD_SIZE(NAMED_VALUE_FLOAT); send_named_float("TetherTrn", sub.quarter_turn_count/4); CHECK_PAYLOAD_SIZE(NAMED_VALUE_FLOAT); send_named_float("Lights1", SRV_Channels::get_output_norm(SRV_Channel::k_rcin9) / 2.0f + 0.5f); CHECK_PAYLOAD_SIZE(NAMED_VALUE_FLOAT); send_named_float("Lights2", SRV_Channels::get_output_norm(SRV_Channel::k_rcin10) / 2.0f + 0.5f); CHECK_PAYLOAD_SIZE(NAMED_VALUE_FLOAT); send_named_float("PilotGain", sub.gain); CHECK_PAYLOAD_SIZE(NAMED_VALUE_FLOAT); send_named_float("InputHold", sub.input_hold_engaged); CHECK_PAYLOAD_SIZE(NAMED_VALUE_FLOAT); send_named_float("RollPitch", sub.roll_pitch_flag); return true; } /* send PID tuning message */ void GCS_MAVLINK_Sub::send_pid_tuning() { const Parameters &g = sub.g; AP_AHRS &ahrs = AP::ahrs(); AC_AttitudeControl_Sub &attitude_control = sub.attitude_control; const Vector3f &gyro = ahrs.get_gyro(); if (g.gcs_pid_mask & 1) { const AP_Logger::PID_Info &pid_info = attitude_control.get_rate_roll_pid().get_pid_info(); mavlink_msg_pid_tuning_send(chan, PID_TUNING_ROLL, pid_info.target*0.01f, degrees(gyro.x), pid_info.FF*0.01f, pid_info.P*0.01f, pid_info.I*0.01f, pid_info.D*0.01f); if (!HAVE_PAYLOAD_SPACE(chan, PID_TUNING)) { return; } } if (g.gcs_pid_mask & 2) { const AP_Logger::PID_Info &pid_info = attitude_control.get_rate_pitch_pid().get_pid_info(); mavlink_msg_pid_tuning_send(chan, PID_TUNING_PITCH, pid_info.target*0.01f, degrees(gyro.y), pid_info.FF*0.01f, pid_info.P*0.01f, pid_info.I*0.01f, pid_info.D*0.01f); if (!HAVE_PAYLOAD_SPACE(chan, PID_TUNING)) { return; } } if (g.gcs_pid_mask & 4) { const AP_Logger::PID_Info &pid_info = attitude_control.get_rate_yaw_pid().get_pid_info(); mavlink_msg_pid_tuning_send(chan, PID_TUNING_YAW, pid_info.target*0.01f, degrees(gyro.z), pid_info.FF*0.01f, pid_info.P*0.01f, pid_info.I*0.01f, pid_info.D*0.01f); if (!HAVE_PAYLOAD_SPACE(chan, PID_TUNING)) { return; } } if (g.gcs_pid_mask & 8) { const AP_Logger::PID_Info &pid_info = sub.pos_control.get_accel_z_pid().get_pid_info(); mavlink_msg_pid_tuning_send(chan, PID_TUNING_ACCZ, pid_info.target*0.01f, -(ahrs.get_accel_ef_blended().z + GRAVITY_MSS), pid_info.FF*0.01f, pid_info.P*0.01f, pid_info.I*0.01f, pid_info.D*0.01f); if (!HAVE_PAYLOAD_SPACE(chan, PID_TUNING)) { return; } } } uint8_t GCS_MAVLINK_Sub::sysid_my_gcs() const { return sub.g.sysid_my_gcs; } bool GCS_Sub::vehicle_initialised() const { return sub.ap.initialised; } // try to send a message, return false if it won't fit in the serial tx buffer bool GCS_MAVLINK_Sub::try_send_message(enum ap_message id) { switch (id) { case MSG_NAMED_FLOAT: send_info(); break; case MSG_TERRAIN: #if AP_TERRAIN_AVAILABLE && AC_TERRAIN CHECK_PAYLOAD_SIZE(TERRAIN_REQUEST); sub.terrain.send_request(chan); #endif break; default: return GCS_MAVLINK::try_send_message(id); } return true; } const AP_Param::GroupInfo GCS_MAVLINK_Parameters::var_info[] = { // @Param: RAW_SENS // @DisplayName: Raw sensor stream rate // @Description: Stream rate of RAW_IMU, SCALED_IMU2, SCALED_PRESSURE, and SENSOR_OFFSETS to ground station // @Units: Hz // @Range: 0 10 // @Increment: 1 // @User: Advanced AP_GROUPINFO("RAW_SENS", 0, GCS_MAVLINK_Parameters, streamRates[GCS_MAVLINK::STREAM_RAW_SENSORS], 0), // @Param: EXT_STAT // @DisplayName: Extended status stream rate to ground station // @Description: Stream rate of SYS_STATUS, MEMINFO, MISSION_CURRENT, GPS_RAW_INT, NAV_CONTROLLER_OUTPUT, and LIMITS_STATUS to ground station // @Units: Hz // @Range: 0 10 // @Increment: 1 // @User: Advanced AP_GROUPINFO("EXT_STAT", 1, GCS_MAVLINK_Parameters, streamRates[GCS_MAVLINK::STREAM_EXTENDED_STATUS], 0), // @Param: RC_CHAN // @DisplayName: RC Channel stream rate to ground station // @Description: Stream rate of SERVO_OUTPUT_RAW and RC_CHANNELS_RAW to ground station // @Units: Hz // @Range: 0 10 // @Increment: 1 // @User: Advanced AP_GROUPINFO("RC_CHAN", 2, GCS_MAVLINK_Parameters, streamRates[GCS_MAVLINK::STREAM_RC_CHANNELS], 0), // @Param: POSITION // @DisplayName: Position stream rate to ground station // @Description: Stream rate of GLOBAL_POSITION_INT to ground station // @Units: Hz // @Range: 0 10 // @Increment: 1 // @User: Advanced AP_GROUPINFO("POSITION", 4, GCS_MAVLINK_Parameters, streamRates[GCS_MAVLINK::STREAM_POSITION], 0), // @Param: EXTRA1 // @DisplayName: Extra data type 1 stream rate to ground station // @Description: Stream rate of ATTITUDE and SIMSTATE (SITL only) to ground station // @Units: Hz // @Range: 0 10 // @Increment: 1 // @User: Advanced AP_GROUPINFO("EXTRA1", 5, GCS_MAVLINK_Parameters, streamRates[GCS_MAVLINK::STREAM_EXTRA1], 0), // @Param: EXTRA2 // @DisplayName: Extra data type 2 stream rate to ground station // @Description: Stream rate of VFR_HUD to ground station // @Units: Hz // @Range: 0 10 // @Increment: 1 // @User: Advanced AP_GROUPINFO("EXTRA2", 6, GCS_MAVLINK_Parameters, streamRates[GCS_MAVLINK::STREAM_EXTRA2], 0), // @Param: EXTRA3 // @DisplayName: Extra data type 3 stream rate to ground station // @Description: Stream rate of AHRS, HWSTATUS, and SYSTEM_TIME to ground station // @Units: Hz // @Range: 0 10 // @Increment: 1 // @User: Advanced AP_GROUPINFO("EXTRA3", 7, GCS_MAVLINK_Parameters, streamRates[GCS_MAVLINK::STREAM_EXTRA3], 0), // @Param: PARAMS // @DisplayName: Parameter stream rate to ground station // @Description: Stream rate of PARAM_VALUE to ground station // @Units: Hz // @Range: 0 10 // @Increment: 1 // @User: Advanced AP_GROUPINFO("PARAMS", 8, GCS_MAVLINK_Parameters, streamRates[GCS_MAVLINK::STREAM_PARAMS], 0), AP_GROUPEND }; static const ap_message STREAM_RAW_SENSORS_msgs[] = { MSG_RAW_IMU, MSG_SCALED_IMU2, MSG_SCALED_IMU3, MSG_SCALED_PRESSURE, MSG_SCALED_PRESSURE2, MSG_SCALED_PRESSURE3, MSG_SENSOR_OFFSETS }; static const ap_message STREAM_EXTENDED_STATUS_msgs[] = { MSG_SYS_STATUS, MSG_POWER_STATUS, MSG_MEMINFO, MSG_CURRENT_WAYPOINT, MSG_GPS_RAW, MSG_GPS_RTK, MSG_GPS2_RAW, MSG_GPS2_RTK, MSG_NAV_CONTROLLER_OUTPUT, MSG_FENCE_STATUS, MSG_NAMED_FLOAT }; static const ap_message STREAM_POSITION_msgs[] = { MSG_LOCATION, MSG_LOCAL_POSITION }; static const ap_message STREAM_RC_CHANNELS_msgs[] = { MSG_SERVO_OUTPUT_RAW, MSG_RC_CHANNELS, MSG_RC_CHANNELS_RAW, // only sent on a mavlink1 connection }; static const ap_message STREAM_EXTRA1_msgs[] = { MSG_ATTITUDE, MSG_SIMSTATE, MSG_AHRS2, MSG_PID_TUNING }; static const ap_message STREAM_EXTRA2_msgs[] = { MSG_VFR_HUD }; static const ap_message STREAM_EXTRA3_msgs[] = { MSG_AHRS, MSG_HWSTATUS, MSG_SYSTEM_TIME, MSG_RANGEFINDER, MSG_DISTANCE_SENSOR, #if AP_TERRAIN_AVAILABLE && AC_TERRAIN MSG_TERRAIN, #endif MSG_BATTERY2, MSG_BATTERY_STATUS, MSG_MOUNT_STATUS, MSG_OPTICAL_FLOW, MSG_GIMBAL_REPORT, MSG_MAG_CAL_REPORT, MSG_MAG_CAL_PROGRESS, MSG_EKF_STATUS_REPORT, MSG_VIBRATION, #if RPM_ENABLED == ENABLED MSG_RPM, #endif MSG_ESC_TELEMETRY, }; static const ap_message STREAM_PARAMS_msgs[] = { MSG_NEXT_PARAM }; const struct GCS_MAVLINK::stream_entries GCS_MAVLINK::all_stream_entries[] = { MAV_STREAM_ENTRY(STREAM_RAW_SENSORS), MAV_STREAM_ENTRY(STREAM_EXTENDED_STATUS), MAV_STREAM_ENTRY(STREAM_POSITION), MAV_STREAM_ENTRY(STREAM_RC_CHANNELS), MAV_STREAM_ENTRY(STREAM_EXTRA1), MAV_STREAM_ENTRY(STREAM_EXTRA2), MAV_STREAM_ENTRY(STREAM_EXTRA3), MAV_STREAM_ENTRY(STREAM_PARAMS), MAV_STREAM_TERMINATOR // must have this at end of stream_entries }; bool GCS_MAVLINK_Sub::handle_guided_request(AP_Mission::Mission_Command &cmd) { return sub.do_guided(cmd); } void GCS_MAVLINK_Sub::handle_change_alt_request(AP_Mission::Mission_Command &cmd) { // add home alt if needed if (cmd.content.location.relative_alt) { cmd.content.location.alt += sub.ahrs.get_home().alt; } // To-Do: update target altitude for loiter or waypoint controller depending upon nav mode } MAV_RESULT GCS_MAVLINK_Sub::_handle_command_preflight_calibration_baro() { if (sub.motors.armed()) { gcs().send_text(MAV_SEVERITY_INFO, "Disarm before calibration."); return MAV_RESULT_FAILED; } if (!sub.control_check_barometer()) { return MAV_RESULT_FAILED; } AP::baro().calibrate(true); return MAV_RESULT_ACCEPTED; } MAV_RESULT GCS_MAVLINK_Sub::_handle_command_preflight_calibration(const mavlink_command_long_t &packet) { if (is_equal(packet.param6,1.0f)) { // compassmot calibration //result = sub.mavlink_compassmot(chan); gcs().send_text(MAV_SEVERITY_INFO, "#CompassMot calibration not supported"); return MAV_RESULT_UNSUPPORTED; } return GCS_MAVLINK::_handle_command_preflight_calibration(packet); } MAV_RESULT GCS_MAVLINK_Sub::handle_command_do_set_roi(const Location &roi_loc) { if (!roi_loc.check_latlng()) { return MAV_RESULT_FAILED; } sub.set_auto_yaw_roi(roi_loc); return MAV_RESULT_ACCEPTED; } bool GCS_MAVLINK_Sub::set_home_to_current_location(bool _lock) { return sub.set_home_to_current_location(_lock); } bool GCS_MAVLINK_Sub::set_home(const Location& loc, bool _lock) { return sub.set_home(loc, _lock); } MAV_RESULT GCS_MAVLINK_Sub::handle_command_long_packet(const mavlink_command_long_t &packet) { switch (packet.command) { case MAV_CMD_NAV_LOITER_UNLIM: if (!sub.set_mode(POSHOLD, ModeReason::GCS_COMMAND)) { return MAV_RESULT_FAILED; } return MAV_RESULT_ACCEPTED; case MAV_CMD_NAV_LAND: if (!sub.set_mode(SURFACE, ModeReason::GCS_COMMAND)) { return MAV_RESULT_FAILED; } return MAV_RESULT_ACCEPTED; case MAV_CMD_CONDITION_YAW: // param1 : target angle [0-360] // param2 : speed during change [deg per second] // param3 : direction (-1:ccw, +1:cw) // param4 : relative offset (1) or absolute angle (0) if ((packet.param1 >= 0.0f) && (packet.param1 <= 360.0f) && (is_zero(packet.param4) || is_equal(packet.param4,1.0f))) { sub.set_auto_yaw_look_at_heading(packet.param1, packet.param2, (int8_t)packet.param3, (uint8_t)packet.param4); return MAV_RESULT_ACCEPTED; } return MAV_RESULT_FAILED; case MAV_CMD_DO_CHANGE_SPEED: // param1 : unused // param2 : new speed in m/s // param3 : unused // param4 : unused if (packet.param2 > 0.0f) { sub.wp_nav.set_speed_xy(packet.param2 * 100.0f); return MAV_RESULT_ACCEPTED; } return MAV_RESULT_FAILED; case MAV_CMD_MISSION_START: if (sub.motors.armed() && sub.set_mode(AUTO, ModeReason::GCS_COMMAND)) { return MAV_RESULT_ACCEPTED; } return MAV_RESULT_FAILED; case MAV_CMD_DO_MOTOR_TEST: // param1 : motor sequence number (a number from 1 to max number of motors on the vehicle) // param2 : throttle type (0=throttle percentage, 1=PWM, 2=pilot throttle channel pass-through. See MOTOR_TEST_THROTTLE_TYPE enum) // param3 : throttle (range depends upon param2) // param4 : timeout (in seconds) if (!sub.handle_do_motor_test(packet)) { return MAV_RESULT_FAILED; } return MAV_RESULT_ACCEPTED; default: return GCS_MAVLINK::handle_command_long_packet(packet); } } void GCS_MAVLINK_Sub::handleMessage(const mavlink_message_t &msg) { switch (msg.msgid) { case MAVLINK_MSG_ID_HEARTBEAT: { // MAV ID: 0 // We keep track of the last time we received a heartbeat from our GCS for failsafe purposes if (msg.sysid != sub.g.sysid_my_gcs) { break; } sub.failsafe.last_heartbeat_ms = AP_HAL::millis(); break; } case MAVLINK_MSG_ID_MANUAL_CONTROL: { // MAV ID: 69 if (msg.sysid != sub.g.sysid_my_gcs) { break; // Only accept control from our gcs } mavlink_manual_control_t packet; mavlink_msg_manual_control_decode(&msg, &packet); if (packet.target != sub.g.sysid_this_mav) { break; // only accept control aimed at us } sub.transform_manual_control_to_rc_override(packet.x,packet.y,packet.z,packet.r,packet.buttons); sub.failsafe.last_pilot_input_ms = AP_HAL::millis(); // a RC override message is considered to be a 'heartbeat' from the ground station for failsafe purposes sub.failsafe.last_heartbeat_ms = AP_HAL::millis(); break; } case MAVLINK_MSG_ID_SET_ATTITUDE_TARGET: { // MAV ID: 82 // decode packet mavlink_set_attitude_target_t packet; mavlink_msg_set_attitude_target_decode(&msg, &packet); // ensure type_mask specifies to use attitude // the thrust can be used from the altitude hold if (packet.type_mask & (1<<6)) { sub.set_attitude_target_no_gps = {AP_HAL::millis(), packet}; } // ensure type_mask specifies to use attitude and thrust if ((packet.type_mask & ((1<<7)|(1<<6))) != 0) { break; } // convert thrust to climb rate packet.thrust = constrain_float(packet.thrust, 0.0f, 1.0f); float climb_rate_cms = 0.0f; if (is_equal(packet.thrust, 0.5f)) { climb_rate_cms = 0.0f; } else if (packet.thrust > 0.5f) { // climb at up to WPNAV_SPEED_UP climb_rate_cms = (packet.thrust - 0.5f) * 2.0f * sub.wp_nav.get_default_speed_up(); } else { // descend at up to WPNAV_SPEED_DN climb_rate_cms = (packet.thrust - 0.5f) * 2.0f * fabsf(sub.wp_nav.get_default_speed_down()); } sub.guided_set_angle(Quaternion(packet.q[0],packet.q[1],packet.q[2],packet.q[3]), climb_rate_cms); break; } case MAVLINK_MSG_ID_SET_POSITION_TARGET_LOCAL_NED: { // MAV ID: 84 // decode packet mavlink_set_position_target_local_ned_t packet; mavlink_msg_set_position_target_local_ned_decode(&msg, &packet); // exit if vehicle is not in Guided mode or Auto-Guided mode if ((sub.control_mode != GUIDED) && !(sub.control_mode == AUTO && sub.auto_mode == Auto_NavGuided)) { break; } // check for supported coordinate frames if (packet.coordinate_frame != MAV_FRAME_LOCAL_NED && packet.coordinate_frame != MAV_FRAME_LOCAL_OFFSET_NED && packet.coordinate_frame != MAV_FRAME_BODY_NED && packet.coordinate_frame != MAV_FRAME_BODY_OFFSET_NED) { break; } bool pos_ignore = packet.type_mask & MAVLINK_SET_POS_TYPE_MASK_POS_IGNORE; bool vel_ignore = packet.type_mask & MAVLINK_SET_POS_TYPE_MASK_VEL_IGNORE; bool acc_ignore = packet.type_mask & MAVLINK_SET_POS_TYPE_MASK_ACC_IGNORE; /* * for future use: * bool force = packet.type_mask & MAVLINK_SET_POS_TYPE_MASK_FORCE; * bool yaw_ignore = packet.type_mask & MAVLINK_SET_POS_TYPE_MASK_YAW_IGNORE; * bool yaw_rate_ignore = packet.type_mask & MAVLINK_SET_POS_TYPE_MASK_YAW_RATE_IGNORE; */ // prepare position Vector3f pos_vector; if (!pos_ignore) { // convert to cm pos_vector = Vector3f(packet.x * 100.0f, packet.y * 100.0f, -packet.z * 100.0f); // rotate to body-frame if necessary if (packet.coordinate_frame == MAV_FRAME_BODY_NED || packet.coordinate_frame == MAV_FRAME_BODY_OFFSET_NED) { sub.rotate_body_frame_to_NE(pos_vector.x, pos_vector.y); } // add body offset if necessary if (packet.coordinate_frame == MAV_FRAME_LOCAL_OFFSET_NED || packet.coordinate_frame == MAV_FRAME_BODY_NED || packet.coordinate_frame == MAV_FRAME_BODY_OFFSET_NED) { pos_vector += sub.inertial_nav.get_position(); } else { // convert from alt-above-home to alt-above-ekf-origin pos_vector.z = sub.pv_alt_above_origin(pos_vector.z); } } // prepare velocity Vector3f vel_vector; if (!vel_ignore) { // convert to cm vel_vector = Vector3f(packet.vx * 100.0f, packet.vy * 100.0f, -packet.vz * 100.0f); // rotate to body-frame if necessary if (packet.coordinate_frame == MAV_FRAME_BODY_NED || packet.coordinate_frame == MAV_FRAME_BODY_OFFSET_NED) { sub.rotate_body_frame_to_NE(vel_vector.x, vel_vector.y); } } // send request if (!pos_ignore && !vel_ignore && acc_ignore) { sub.guided_set_destination_posvel(pos_vector, vel_vector); } else if (pos_ignore && !vel_ignore && acc_ignore) { sub.guided_set_velocity(vel_vector); } else if (!pos_ignore && vel_ignore && acc_ignore) { sub.guided_set_destination(pos_vector); } break; } case MAVLINK_MSG_ID_SET_POSITION_TARGET_GLOBAL_INT: { // MAV ID: 86 // decode packet mavlink_set_position_target_global_int_t packet; mavlink_msg_set_position_target_global_int_decode(&msg, &packet); // exit if vehicle is not in Guided, Auto-Guided, or Depth Hold modes if ((sub.control_mode != GUIDED) && !(sub.control_mode == AUTO && sub.auto_mode == Auto_NavGuided) && !(sub.control_mode == ALT_HOLD)) { break; } bool pos_ignore = packet.type_mask & MAVLINK_SET_POS_TYPE_MASK_POS_IGNORE; bool vel_ignore = packet.type_mask & MAVLINK_SET_POS_TYPE_MASK_VEL_IGNORE; bool acc_ignore = packet.type_mask & MAVLINK_SET_POS_TYPE_MASK_ACC_IGNORE; /* * for future use: * bool force = packet.type_mask & MAVLINK_SET_POS_TYPE_MASK_FORCE; * bool yaw_ignore = packet.type_mask & MAVLINK_SET_POS_TYPE_MASK_YAW_IGNORE; * bool yaw_rate_ignore = packet.type_mask & MAVLINK_SET_POS_TYPE_MASK_YAW_RATE_IGNORE; */ if (!pos_ignore && sub.control_mode == ALT_HOLD) { // Control only target depth when in ALT_HOLD sub.pos_control.set_alt_target(packet.alt*100); break; } Vector3f pos_neu_cm; // position (North, East, Up coordinates) in centimeters if (!pos_ignore) { // sanity check location if (!check_latlng(packet.lat_int, packet.lon_int)) { break; } Location::AltFrame frame; if (!mavlink_coordinate_frame_to_location_alt_frame((MAV_FRAME)packet.coordinate_frame, frame)) { // unknown coordinate frame break; } const Location loc{ packet.lat_int, packet.lon_int, int32_t(packet.alt*100), frame, }; if (!loc.get_vector_from_origin_NEU(pos_neu_cm)) { break; } } if (!pos_ignore && !vel_ignore && acc_ignore) { sub.guided_set_destination_posvel(pos_neu_cm, Vector3f(packet.vx * 100.0f, packet.vy * 100.0f, -packet.vz * 100.0f)); } else if (pos_ignore && !vel_ignore && acc_ignore) { sub.guided_set_velocity(Vector3f(packet.vx * 100.0f, packet.vy * 100.0f, -packet.vz * 100.0f)); } else if (!pos_ignore && vel_ignore && acc_ignore) { sub.guided_set_destination(pos_neu_cm); } break; } case MAVLINK_MSG_ID_TERRAIN_DATA: case MAVLINK_MSG_ID_TERRAIN_CHECK: #if AP_TERRAIN_AVAILABLE && AC_TERRAIN sub.terrain.handle_data(chan, msg); #endif break; case MAVLINK_MSG_ID_SET_HOME_POSITION: { mavlink_set_home_position_t packet; mavlink_msg_set_home_position_decode(&msg, &packet); if ((packet.latitude == 0) && (packet.longitude == 0) && (packet.altitude == 0)) { if (!sub.set_home_to_current_location(true)) { // ignore this failure } } else { Location new_home_loc; new_home_loc.lat = packet.latitude; new_home_loc.lng = packet.longitude; new_home_loc.alt = packet.altitude / 10; if (sub.far_from_EKF_origin(new_home_loc)) { break; } if (!sub.set_home(new_home_loc, true)) { // silently ignored } } break; } // This adds support for leak detectors in a separate enclosure // connected to a mavlink enabled subsystem case MAVLINK_MSG_ID_SYS_STATUS: { uint32_t MAV_SENSOR_WATER = 0x20000000; mavlink_sys_status_t packet; mavlink_msg_sys_status_decode(&msg, &packet); if ((packet.onboard_control_sensors_enabled & MAV_SENSOR_WATER) && !(packet.onboard_control_sensors_health & MAV_SENSOR_WATER)) { sub.leak_detector.set_detect(); } } break; default: handle_common_message(msg); break; } // end switch } // end handle mavlink uint64_t GCS_MAVLINK_Sub::capabilities() const { return (MAV_PROTOCOL_CAPABILITY_MISSION_FLOAT | MAV_PROTOCOL_CAPABILITY_MISSION_INT | MAV_PROTOCOL_CAPABILITY_SET_POSITION_TARGET_LOCAL_NED | MAV_PROTOCOL_CAPABILITY_SET_POSITION_TARGET_GLOBAL_INT | MAV_PROTOCOL_CAPABILITY_FLIGHT_TERMINATION | #if AP_TERRAIN_AVAILABLE && AC_TERRAIN (sub.terrain.enabled() ? MAV_PROTOCOL_CAPABILITY_TERRAIN : 0) | #endif MAV_PROTOCOL_CAPABILITY_SET_ATTITUDE_TARGET | GCS_MAVLINK::capabilities() ); } // a RC override message is considered to be a 'heartbeat' from the ground station for failsafe purposes void GCS_MAVLINK_Sub::handle_rc_channels_override(const mavlink_message_t &msg) { sub.failsafe.last_heartbeat_ms = AP_HAL::millis(); GCS_MAVLINK::handle_rc_channels_override(msg); } MAV_RESULT GCS_MAVLINK_Sub::handle_flight_termination(const mavlink_command_long_t &packet) { if (packet.param1 > 0.5f) { sub.arming.disarm(AP_Arming::Method::TERMINATION); return MAV_RESULT_ACCEPTED; } return MAV_RESULT_FAILED; } int32_t GCS_MAVLINK_Sub::global_position_int_alt() const { if (!sub.ap.depth_sensor_present) { return 0; } return GCS_MAVLINK::global_position_int_alt(); } int32_t GCS_MAVLINK_Sub::global_position_int_relative_alt() const { if (!sub.ap.depth_sensor_present) { return 0; } return GCS_MAVLINK::global_position_int_relative_alt(); }
gpl-3.0
AlexsJones/jnxlibc
test/unit/test_jnxexceptions.c
2
1364
/* * ===================================================================================== * * Filename: test_jnxexceptions.c * * Description: * * Version: 1.0 * Created: 02/19/2015 08:24:41 PM * Revision: none * Compiler: gcc * * Author: YOUR NAME (), * Organization: * * ===================================================================================== */ #include <stdlib.h> #include "jnx_log.h" #include "jnx_check.h" #define FOO_EXCEPTION (-2) #define BAR_EXCEPTION (-3) int test_jnxexceptions() { JNXLOG(LDEBUG,"Running test_jnxexception tests"); int ar[3] = { -1,-2,-3}; int c; for(c=0;c<3;++c) { int current_exception = ar[c]; jnx_try { jnx_throw( ar[c] ); } jnx_catch( JNX_EXCEPTION ) { JNXLOG(LDEBUG,"Default system exception fired correctly"); JNXCHECK(current_exception == JNX_EXCEPTION); break; } jnx_catch( FOO_EXCEPTION ) { JNXLOG(LDEBUG,"First exception fired correctly"); JNXCHECK(current_exception == FOO_EXCEPTION); break; } jnx_catch( BAR_EXCEPTION ) { JNXLOG(LDEBUG,"Second exception fired correctly"); JNXCHECK(current_exception == BAR_EXCEPTION); break; } jnx_finally { JNXLOG(LDEBUG,"Hit finally clause"); } jnx_try_end } return 0; }
gpl-3.0
pmverma/winscp
libs/mfc/source/array_w.cpp
2
7481
// This is a part of the Microsoft Foundation Classes C++ library. // Copyright (C) 1992-1998 Microsoft Corporation // All rights reserved. // // This source code is only intended as a supplement to the // Microsoft Foundation Classes Reference and related // electronic documentation provided with the library. // See these sources for detailed information regarding the // Microsoft Foundation Classes product. ///////////////////////////////////////////////////////////////////////////// // // Implementation of parameterized Array // ///////////////////////////////////////////////////////////////////////////// // NOTE: we allocate an array of 'm_nMaxSize' elements, but only // the current size 'm_nSize' contains properly constructed // objects. #include "stdafx.h" #ifdef AFX_COLL_SEG #pragma code_seg(AFX_COLL_SEG) #endif #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #define new DEBUG_NEW ///////////////////////////////////////////////////////////////////////////// CWordArray::CWordArray() { m_pData = NULL; m_nSize = m_nMaxSize = m_nGrowBy = 0; } CWordArray::~CWordArray() { ASSERT_VALID(this); delete[] (BYTE*)m_pData; } void CWordArray::SetSize(int nNewSize, int nGrowBy) { ASSERT_VALID(this); ASSERT(nNewSize >= 0); if (nGrowBy != -1) m_nGrowBy = nGrowBy; // set new size if (nNewSize == 0) { // shrink to nothing delete[] (BYTE*)m_pData; m_pData = NULL; m_nSize = m_nMaxSize = 0; } else if (m_pData == NULL) { // create one with exact size #ifdef SIZE_T_MAX ASSERT(nNewSize <= SIZE_T_MAX/sizeof(WORD)); // no overflow #endif m_pData = (WORD*) new BYTE[nNewSize * sizeof(WORD)]; memset(m_pData, 0, nNewSize * sizeof(WORD)); // zero fill m_nSize = m_nMaxSize = nNewSize; } else if (nNewSize <= m_nMaxSize) { // it fits if (nNewSize > m_nSize) { // initialize the new elements memset(&m_pData[m_nSize], 0, (nNewSize-m_nSize) * sizeof(WORD)); } m_nSize = nNewSize; } else { // otherwise, grow array int nGrowBy = m_nGrowBy; if (nGrowBy == 0) { // heuristically determine growth when nGrowBy == 0 // (this avoids heap fragmentation in many situations) nGrowBy = min(1024, max(4, m_nSize / 8)); } int nNewMax; if (nNewSize < m_nMaxSize + nGrowBy) nNewMax = m_nMaxSize + nGrowBy; // granularity else nNewMax = nNewSize; // no slush ASSERT(nNewMax >= m_nMaxSize); // no wrap around #ifdef SIZE_T_MAX ASSERT(nNewMax <= SIZE_T_MAX/sizeof(WORD)); // no overflow #endif WORD* pNewData = (WORD*) new BYTE[nNewMax * sizeof(WORD)]; // copy new data from old memcpy(pNewData, m_pData, m_nSize * sizeof(WORD)); // construct remaining elements ASSERT(nNewSize > m_nSize); memset(&pNewData[m_nSize], 0, (nNewSize-m_nSize) * sizeof(WORD)); // get rid of old stuff (note: no destructors called) delete[] (BYTE*)m_pData; m_pData = pNewData; m_nSize = nNewSize; m_nMaxSize = nNewMax; } } int CWordArray::Append(const CWordArray& src) { ASSERT_VALID(this); ASSERT(this != &src); // cannot append to itself int nOldSize = m_nSize; SetSize(m_nSize + src.m_nSize); memcpy(m_pData + nOldSize, src.m_pData, src.m_nSize * sizeof(WORD)); return nOldSize; } void CWordArray::Copy(const CWordArray& src) { ASSERT_VALID(this); ASSERT(this != &src); // cannot append to itself SetSize(src.m_nSize); memcpy(m_pData, src.m_pData, src.m_nSize * sizeof(WORD)); } void CWordArray::FreeExtra() { ASSERT_VALID(this); if (m_nSize != m_nMaxSize) { // shrink to desired size #ifdef SIZE_T_MAX ASSERT(m_nSize <= SIZE_T_MAX/sizeof(WORD)); // no overflow #endif WORD* pNewData = NULL; if (m_nSize != 0) { pNewData = (WORD*) new BYTE[m_nSize * sizeof(WORD)]; // copy new data from old memcpy(pNewData, m_pData, m_nSize * sizeof(WORD)); } // get rid of old stuff (note: no destructors called) delete[] (BYTE*)m_pData; m_pData = pNewData; m_nMaxSize = m_nSize; } } ///////////////////////////////////////////////////////////////////////////// void CWordArray::SetAtGrow(int nIndex, WORD newElement) { ASSERT_VALID(this); ASSERT(nIndex >= 0); if (nIndex >= m_nSize) SetSize(nIndex+1); m_pData[nIndex] = newElement; } void CWordArray::InsertAt(int nIndex, WORD newElement, int nCount) { ASSERT_VALID(this); ASSERT(nIndex >= 0); // will expand to meet need ASSERT(nCount > 0); // zero or negative size not allowed if (nIndex >= m_nSize) { // adding after the end of the array SetSize(nIndex + nCount); // grow so nIndex is valid } else { // inserting in the middle of the array int nOldSize = m_nSize; SetSize(m_nSize + nCount); // grow it to new size // shift old data up to fill gap memmove(&m_pData[nIndex+nCount], &m_pData[nIndex], (nOldSize-nIndex) * sizeof(WORD)); // re-init slots we copied from memset(&m_pData[nIndex], 0, nCount * sizeof(WORD)); } // insert new value in the gap ASSERT(nIndex + nCount <= m_nSize); // copy elements into the empty space while (nCount--) m_pData[nIndex++] = newElement; } void CWordArray::RemoveAt(int nIndex, int nCount) { ASSERT_VALID(this); ASSERT(nIndex >= 0); ASSERT(nCount >= 0); ASSERT(nIndex + nCount <= m_nSize); // just remove a range int nMoveCount = m_nSize - (nIndex + nCount); if (nMoveCount) memmove(&m_pData[nIndex], &m_pData[nIndex + nCount], nMoveCount * sizeof(WORD)); m_nSize -= nCount; } void CWordArray::InsertAt(int nStartIndex, CWordArray* pNewArray) { ASSERT_VALID(this); ASSERT(pNewArray != NULL); ASSERT_KINDOF(CWordArray, pNewArray); ASSERT_VALID(pNewArray); ASSERT(nStartIndex >= 0); if (pNewArray->GetSize() > 0) { InsertAt(nStartIndex, pNewArray->GetAt(0), pNewArray->GetSize()); for (int i = 0; i < pNewArray->GetSize(); i++) SetAt(nStartIndex + i, pNewArray->GetAt(i)); } } ///////////////////////////////////////////////////////////////////////////// // Serialization void CWordArray::Serialize(CArchive& ar) { ASSERT_VALID(this); CObject::Serialize(ar); if (ar.IsStoring()) { ar.WriteCount(m_nSize); #ifdef _AFX_BYTESWAP if (!ar.IsByteSwapping()) #endif ar.Write(m_pData, m_nSize * sizeof(WORD)); #ifdef _AFX_BYTESWAP else { // write each item individually so that it will be byte-swapped for (int i = 0; i < m_nSize; i++) ar << m_pData[i]; } #endif } else { DWORD nOldSize = ar.ReadCount(); SetSize(nOldSize); ar.Read(m_pData, m_nSize * sizeof(WORD)); #ifdef _AFX_BYTESWAP if (ar.IsByteSwapping()) { for (int i = 0; i < m_nSize; i++) _AfxByteSwap(m_pData[i], (BYTE*)&m_pData[i]); } #endif } } ///////////////////////////////////////////////////////////////////////////// // Diagnostics #ifdef _DEBUG void CWordArray::Dump(CDumpContext& dc) const { CObject::Dump(dc); dc << "with " << m_nSize << " elements"; if (dc.GetDepth() > 0) { for (int i = 0; i < m_nSize; i++) dc << "\n\t[" << i << "] = " << m_pData[i]; } dc << "\n"; } void CWordArray::AssertValid() const { CObject::AssertValid(); if (m_pData == NULL) { ASSERT(m_nSize == 0); ASSERT(m_nMaxSize == 0); } else { ASSERT(m_nSize >= 0); ASSERT(m_nMaxSize >= 0); ASSERT(m_nSize <= m_nMaxSize); ASSERT(AfxIsValidAddress(m_pData, m_nMaxSize * sizeof(WORD))); } } #endif //_DEBUG #ifdef AFX_INIT_SEG #pragma code_seg(AFX_INIT_SEG) #endif IMPLEMENT_SERIAL(CWordArray, CObject, 0) /////////////////////////////////////////////////////////////////////////////
gpl-3.0
TheMarex/simox
MotionPlanning/CSpace/CSpaceTree.cpp
2
9536
#include "VirtualRobot/CollisionDetection/CDManager.h" #include "CSpaceTree.h" #include "CSpaceNode.h" #include "CSpacePath.h" #include "CSpace.h" #include "VirtualRobot/Robot.h" #include "VirtualRobot/RobotNodeSet.h" #include "float.h" #include <cmath> #include <fstream> #include <iomanip> #include <time.h> using namespace std; //#define DO_THE_TESTS namespace Saba { CSpaceTree::CSpaceTree(CSpacePtr cspace) { if (!cspace) { THROW_SABA_EXCEPTION ("NULL data, aborting..."); } this->cspace = cspace; randMult = (float)(1.0/(double)(RAND_MAX)); updateChildren = false; dimension = cspace->getDimension(); if (dimension < 1) { std::cout << "CSpaceTree: Initialization fails: INVALID DIMENSION" << std::endl; return; } tmpConfig.setZero(dimension); } CSpaceTree::~CSpaceTree() { } void CSpaceTree::lock() { mutex.lock(); } void CSpaceTree::unlock() { mutex.unlock(); } void CSpaceTree::reset() { idNodeMapping.clear(); nodes.clear(); } CSpaceNodePtr CSpaceTree::getNode(unsigned int id) { if (idNodeMapping.find(id)==idNodeMapping.end()) { SABA_WARNING << " wrong ID: " << id << std::endl; return CSpaceNodePtr(); } return idNodeMapping[id]; } bool CSpaceTree::hasNode(CSpaceNodePtr n) { if (!n) return false; if (idNodeMapping.find(n->ID)==idNodeMapping.end()) return false; return true; } float CSpaceTree::getPathDist(unsigned int idStart, unsigned int idEnd, bool useMetricWeights) { float result = 0.0f; if (!getNode(idStart) || !getNode(idStart)) { SABA_ERROR << "CSpaceTree::getPathDist: start or goal id not correct..." << endl; return -1.0f; } unsigned int actID = idEnd; unsigned int actID2 = getNode(idEnd)->parentID; CSpaceNodePtr actNode; CSpaceNodePtr actNode2; while (actID2 != idStart) { actNode = getNode(actID); actNode2 = getNode(actID2); if (actID2<0 || actNode->parentID<0 || !actNode || !actNode2) { std::cout << "CSpaceTree::getPathDist: error, no path from start to end ?!" << std::endl; return result; } result += cspace->calcDist(actNode->configuration, actNode2->configuration); actID = actID2; actID2 = actNode2->parentID; } // add last part result += cspace->calcDist(getNode(actID)->configuration, getNode(actID2)->configuration); return result; } // creates a copy of configuration CSpaceNodePtr CSpaceTree::appendNode(const Eigen::VectorXf &config, int parentID, bool calcDistance) { SABA_ASSERT (config.rows()==dimension) // create a new node with config, store it in nodeList and set parentID CSpaceNodePtr newNode = cspace->createNewNode(); if (!newNode) return newNode; nodes.push_back(newNode); idNodeMapping[newNode->ID] = newNode; // parent of new CSpaceNode newNode->parentID = parentID; if (updateChildren && parentID>=0) { CSpaceNodePtr n = getNode(parentID); if (!n) { SABA_ERROR << "CSpaceTree::appendNode: No parent node with id : " << parentID << std::endl; } else { n->children.push_back(newNode); } } // copy values newNode->configuration = config; // no distance information newNode->obstacleDistance = -1.0f; // calculate distances if (calcDistance) { float d = cspace->calculateObstacleDistance(newNode->configuration); newNode->obstacleDistance = d; } #ifdef DO_THE_TESTS if (!cspace->IsConfigValid(config)) { std::cout << "Appending not valid node!" << std::endl; } #endif return newNode; } // returns true if full path was added bool CSpaceTree::appendPathUntilCollision(CSpaceNodePtr startNode, const Eigen::VectorXf &config, int *storeLastAddedID) { SABA_ASSERT (hasNode(startNode)) SABA_ASSERT (config.rows()==dimension) float dist; CSpacePathPtr res = cspace->createPathUntilInvalid(startNode->configuration, config, dist); if (res->getNrOfPoints()<=1) return false; res->erasePosition(0); bool appOK = appendPath(startNode, res, storeLastAddedID); if (!appOK) return false; return (dist==1.0f); } bool CSpaceTree::appendPath(CSpaceNodePtr startNode, CSpacePathPtr path, int *storeLastAddedID) { SABA_ASSERT (hasNode(startNode)) SABA_ASSERT (path) CSpaceNodePtr n = startNode; const std::vector<Eigen::VectorXf > data = path->getData(); std::vector<Eigen::VectorXf >::const_iterator it; for (it=data.begin(); it!=data.end(); it++) { n = appendNode(*it, n->ID); } if (storeLastAddedID) *storeLastAddedID = n->ID; return true; } // appends path from startNode to config, creates in-between nodes according to cspace if needed // no checks (for valid configs) // creates a copy of configuration bool CSpaceTree::appendPath(CSpaceNodePtr startNode, const Eigen::VectorXf &config, int *storeLastAddedID) { SABA_ASSERT (hasNode(startNode)) SABA_ASSERT (config.rows()==dimension) CSpacePathPtr res = cspace->createPath(startNode->configuration, config); if (res->getNrOfPoints()<=1) return false; res->erasePosition(0); return appendPath(startNode, res, storeLastAddedID); } void CSpaceTree::removeNode(CSpaceNodePtr n) { if (!n) { SABA_ERROR << ": NULL node" << std::endl; return; } if (n->ID<0) { SABA_ERROR << ": wrong ID" << std::endl; return; } if (nodes.size()==0) { SABA_ERROR << ": no nodes in tree" << std::endl; return; } vector<CSpaceNodePtr>::iterator it = nodes.begin(); while (*it!=n) { it++; if (it==nodes.end()) { cout << "CSpaceTree::removeNode: node not in node vector ??? " << endl; return; } } nodes.erase(it); idNodeMapping.erase(n->ID); cspace->removeNode(n); } CSpaceNodePtr CSpaceTree::getNearestNeighbor(const Eigen::VectorXf &config, float *storeDist) { return getNode(getNearestNeighborID(config,storeDist)); } unsigned int CSpaceTree::getNearestNeighborID(const Eigen::VectorXf &config, float *storeDist) { // goes through complete list of nodes, toDO: everything is better than this: eg octrees,something hierarchical... // update: only if we have more than 1000 nodes in the tree! if (nodes.size()==0 || !cspace) { SABA_WARNING << "no nodes in tree..." << endl; return 0; } unsigned int bestID = nodes[0]->ID; float dist2 = cspace->calcDist2(config,nodes[0]->configuration,true); float test; for (unsigned int i = 1; i<nodes.size();i++) { test = cspace->calcDist2(config,nodes[i]->configuration,true); if (test<dist2) { dist2 = test; bestID = nodes[i]->ID; } } if (storeDist!=NULL) *storeDist = sqrtf(dist2); return bestID; } bool CSpaceTree::saveAllNodes(char const* filename) { std::ofstream file(filename, std::ios::out); if (!file.is_open()) { std::cout << "ERROR: rrtCSpace::saveAllNodes: Could not open file to write." << std::endl; return false; } file << "# DO NOT EDIT LIST OF NODES #" << std::endl; file << "# FIRST ROW: KINEMATIC CHAIN NAME" << std::endl; file << "# SECOND ROW: DIMENSION" << std::endl; file << "# THIRD ROW: NUMBER OF ALL NODES" << std::endl; file << "# THEN ACTUAL DATA IN FOLLOWING FORMAT: ID CONFIG PARENTID" << std::endl; // save kinematic chain name used file << cspace->getRobotNodeSet()->getName() << std::endl; // save rrt dimension used for planning file << dimension << std::endl; // save number of nodes file << nodes.size() << std::endl; CSpaceNodePtr actualNode; for (unsigned int i = 0; i < nodes.size(); i++) { // save ID, configuration and parentID of each node in one row actualNode = nodes[i]; file << actualNode->ID << " "; for (unsigned int j = 0; j < dimension; j++) { file << actualNode->configuration[j] << " "; } file << actualNode->parentID << std::endl; } file.close(); return true; } CSpaceNodePtr CSpaceTree::getLastAddedNode() { if (nodes.size()==0) return CSpaceNodePtr(); return nodes[nodes.size()-1]; } bool CSpaceTree::createPath (CSpaceNodePtr startNode, CSpaceNodePtr goalNode, CSpacePathPtr fillPath) { // creates a path from goal to startNode if (!goalNode || !startNode || !fillPath) return false; std::vector<int> tmpSol; fillPath->reset(); int actID = goalNode->ID; CSpaceNodePtr actNode = goalNode; bool found = false; while (actID>=0 && actNode && !found) { actNode = getNode(actID); if (actNode) { tmpSol.push_back(actID); //fillPath->addPoint(actNode->configuration); if (actID == startNode->ID) { found = true; } else { actID = actNode->parentID; } } } if (!found) { std::cout << "CSpaceTree::createPath: Start node not a parent of goalNode... goalID:" << goalNode->ID << ", startID:" << startNode->ID << std::endl; } else { // revert path for ( int i=( int)tmpSol.size()-1;i>=0;i--) { fillPath->addPoint(getNode(tmpSol[i])->configuration); } } return found; } /* void CSpaceTree::printNode(CSpaceNodePtr n) { if (!n) return; cspace->printConfig(n->configuration); }*/ /* void CSpaceTree::printNode(unsigned int id) { CSpaceNodePtr n = getNode(id); cspace->printConfig(n->configuration); } */ float CSpaceTree::getTreeLength(bool useMetricWeights) { unsigned int nMaxNodes = (int)nodes.size(); float res = 0; for (unsigned int i=0; i<nMaxNodes;i++) { if (nodes[i] && nodes[i]->parentID>=0 && nodes[i]->parentID<(int)nMaxNodes) res += cspace->calcDist(nodes[i]->configuration,nodes[nodes[i]->parentID]->configuration, !useMetricWeights); } return res; } unsigned int CSpaceTree::getNrOfNodes() const { return nodes.size(); } std::vector<CSpaceNodePtr> CSpaceTree::getNodes() { return nodes; } unsigned int CSpaceTree::getDimension() const { return dimension; } Saba::CSpacePtr CSpaceTree::getCSpace() { return cspace; } } // namespace Saba
gpl-3.0
lis-epfl/robogen
src/render/callback/PositionObservableCallback.cpp
2
1567
/* * @(#) PositionObservableCallback.cpp 1.0 Mar 20, 2013 * * Andrea Maesani (andrea.maesani@epfl.ch) * * The ROBOGEN Framework * Copyright © 2012-2013 Andrea Maesani * * Laboratory of Intelligent Systems, EPFL * * This file is part of the ROBOGEN Framework. * * The ROBOGEN Framework is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License (GPL) * as published by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * @(#) $Id$ */ #include <osg/PositionAttitudeTransform> #include "model/Model.h" #include "render/callback/PositionObservableCallback.h" namespace robogen { PositionObservableCallback::PositionObservableCallback(boost::shared_ptr<PositionObservable> model) : model_(model) { } void PositionObservableCallback::operator()(osg::Node* node, osg::NodeVisitor* nv) { osg::ref_ptr<osg::PositionAttitudeTransform> pat = node->asTransform()->asPositionAttitudeTransform(); pat->setAttitude(model_->getAttitude()); pat->setPosition(fromOde(model_->getPosition())); traverse(node, nv); } }
gpl-3.0
houmaster/gpupad
libs/KTX/lib/hashtable.c
2
2762
/* -*- tab-width: 4; -*- */ /* vi: set sw=2 ts=4 expandtab: */ /** * @internal * @file hashtable.c * @~English * * @brief Functions for backward compatibility with libktx v1 * hashtable API. * * @author Mark Callow, www.edgewise-consulting.com */ /* * ©2018 Mark Callow. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "ktx.h" /** * @memberof KTX_hash_table * @~English * @deprecated Use ktxHashList_Create(). */ KTX_hash_table ktxHashTable_Create(void) { ktxHashList* hl; (void)ktxHashList_Create(&hl); return hl; } /** * @memberof KTX_hash_table * @~English * @deprecated Use ktxHashList_Serialize(). * @brief Serializes the hash table to a block of memory suitable for * writing to a KTX file. */ KTX_error_code ktxHashTable_Serialize(KTX_hash_table This, unsigned int* kvdLen, unsigned char** kvd) { return ktxHashList_Serialize(This, kvdLen, kvd); } /** * @memberof KTX_hash_table * @deprecated Use ktxHashList_Deserialize(). * @~English * @brief Create a new hash table from a block of serialized key-value * data read from a file. * * The caller is responsible for freeing the returned hash table. * * @note The bytes of the 32-bit key-value lengths within the serialized data * are expected to be in native endianness. * * @param[in] kvdLen the length of the serialized key-value data. * @param[in] pKvd pointer to the serialized key-value data. * @param[in,out] pHt @p *pHt is set to point to the created hash * table. * * @return KTX_SUCCESS or one of the following error codes. * * @exception KTX_INVALID_VALUE if @p pKvd or @p pHt is NULL or kvdLen == 0. * @exception KTX_OUT_OF_MEMORY there was not enough memory to create the hash * table. */ KTX_error_code ktxHashTable_Deserialize(unsigned int kvdLen, void* pKvd, KTX_hash_table* pHt) { ktxHashList* pHl; KTX_error_code result; result = ktxHashList_Create(&pHl); if (result != KTX_SUCCESS) return result; result = ktxHashList_Deserialize(pHl, kvdLen, pKvd); if (result == KTX_SUCCESS) *pHt = pHl; return result; }
gpl-3.0
KingDuckZ/kamokan
src/kamokan_impl/response.cpp
2
9177
/* Copyright 2017, Michele Santullo * This file is part of "kamokan". * * "kamokan" 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. * * "kamokan" 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 "kamokan". If not, see <http://www.gnu.org/licenses/>. */ #include "response.hpp" #include "settings_bag.hpp" #include "duckhandy/stringize.h" #include "pathname/pathname.hpp" #include "highlight_functions.hpp" #include "cgi_env.hpp" #include "num_conv.hpp" #include "kamokan_config.h" #include "version.hpp" #include <utility> #include <cassert> #include <fstream> #include <sstream> #include <functional> #include <boost/optional.hpp> #include <cstdint> #include <spdlog/spdlog.h> namespace kamokan { namespace { //boost::string_ref fetch_page_basename (const cgi::Env& parEnv) { // const boost::string_ref& path = parEnv.path_info(); // const std::size_t last_slash = path.rfind('/'); // const std::size_t last_dot = path.rfind('.'); // const std::size_t start_index = (path.npos == last_slash ? 0 : last_slash + 1); // const std::size_t substr_len = (path.size() - start_index - (last_dot == path.npos ? 0 : path.size() - last_dot)); // assert(start_index <= path.size()); // assert(substr_len < path.size() and substr_len - path.size() - start_index); // return path.substr(start_index, substr_len); //} std::string make_root_path (const SettingsBag& parSettings) { auto retval = parSettings["website_root"]; if (retval.empty()) { return ""; } else { return mchlib::PathName(retval).path() + '/'; } } boost::optional<std::string> load_whole_file (const std::string& parWebsiteRoot, const char* parSuffix, const boost::string_view& parName, bool parThrow) { std::ostringstream oss; oss << parWebsiteRoot << parName << parSuffix; spdlog::get("statuslog")->info("Trying to load \"{}\"", oss.str()); std::ifstream if_mstch(oss.str(), std::ios::binary | std::ios::in); if (not if_mstch) { spdlog::get("statuslog")->warn("Couldn't open file \"{}\"", oss.str()); if (parThrow) throw std::runtime_error(std::string("File \"") + oss.str() + "\" not found"); else return boost::optional<std::string>(); } std::ostringstream buffer; buffer << if_mstch.rdbuf(); return boost::make_optional(buffer.str()); } mstch::array make_mstch_langmap (const SettingsBag& parSettings, const std::string& parSelected) { mstch::array retval; for (auto&& lang : list_highlight_langs(parSettings)) { const bool selected = (parSelected == lang); retval.push_back(mstch::map{ {"language_name", std::move(lang)}, {"language_selected", selected} }); } return retval; } std::string disable_mstch_escaping (const std::string& parStr) { return parStr; }; boost::string_view make_host_path (const SettingsBag& parSettings) { boost::string_view host_path = parSettings.at("host_path"); if (not host_path.empty() and host_path[host_path.size() - 1] == '/') host_path = host_path.substr(0, host_path.size() - 1); return host_path; } std::string make_base_uri (const Kakoune::SafePtr<SettingsBag>& parSettings, const Kakoune::SafePtr<cgi::Env>& parCgiEnv) { assert(parSettings); assert(parCgiEnv); std::ostringstream oss; if (parCgiEnv->https()) oss << "https://"; else oss << "http://"; oss << parSettings->at("host_name"); boost::string_view host_port = parSettings->at("host_port"); if (not host_port.empty()) { if (host_port == "from_downstream") { const uint16_t port = parCgiEnv->server_port(); if ((80 != port and not parCgiEnv->https()) or (443 != port and parCgiEnv->https())) { oss << ':' << port; } } else if (not host_port.empty() and tawashi::seems_valid_number<uint16_t>(host_port)) { oss << ':' << host_port; } } oss << make_host_path(*parSettings); return oss.str(); } } //unnamed namespace Response::Response ( const Kakoune::SafePtr<SettingsBag>& parSettings, std::ostream* parStreamOut, const Kakoune::SafePtr<cgi::Env>& parCgiEnv, bool parWantRedis ) : m_storage(parSettings), //m_page_basename(fetch_page_basename(m_cgi_env)), m_cgi_env(parCgiEnv), m_settings(parSettings), m_time0(std::chrono::steady_clock::now()), m_website_root(make_root_path(*parSettings)), m_base_uri(make_base_uri(m_settings, m_cgi_env)), m_stream_out(parStreamOut) { assert(m_cgi_env); assert(m_stream_out); if (parWantRedis) { m_storage.connect_async(); } mstch::config::escape = &disable_mstch_escaping; auto statuslog = spdlog::get("statuslog"); assert(statuslog); statuslog->info("Preparing response for {} request; query_string=\"{}\"; size={}", cgi_env().request_method()._to_string(), cgi_env().query_string(), cgi_env().content_length() ); } Response::~Response() noexcept = default; tawashi::HttpHeader Response::on_process() { return tawashi::HttpHeader(); } void Response::on_mustache_prepare (mstch::map&) { } void Response::send() { auto statuslog = spdlog::get("statuslog"); assert(statuslog); statuslog->info("Sending response"); SPDLOG_TRACE(statuslog, "Preparing mustache dictionary"); const bool is_submit_page = this->is_submit_page(); const bool is_pastie_page = this->is_pastie_page(); mstch::map mustache_context { {"submit_page", is_submit_page}, {"version", boost::string_view{STRINGIZE(VERSION_MAJOR) "." STRINGIZE(VERSION_MINOR) "." STRINGIZE(VERSION_PATCH)}}, {"tawashi_version", tawashi::version()}, {"base_uri", base_uri()}, {"host_path", make_host_path(this->settings())}, {"pastie_page", is_pastie_page} }; m_storage.finalize_connection(); SPDLOG_TRACE(statuslog, "Raising event on_process"); tawashi::HttpHeader http_header = this->on_process(); *m_stream_out << http_header; if (is_submit_page) { SPDLOG_TRACE(statuslog, "Adding language list to mustache context"); mustache_context["languages"] = make_mstch_langmap(*m_settings, this->default_pastie_lang()); } if (http_header.body_required()) { using std::chrono::steady_clock; using std::chrono::milliseconds; using std::chrono::duration_cast; SPDLOG_TRACE(statuslog, "Raising event on_mustache_prepare"); this->on_mustache_prepare(mustache_context); const auto time1 = steady_clock::now(); const int page_time = duration_cast<milliseconds>(time1 - m_time0).count(); mustache_context["page_time"] = page_time; SPDLOG_TRACE(statuslog, "Rendering in mustache"); *m_stream_out << mstch::render( on_mustache_retrieve(), mustache_context, std::bind( &load_whole_file, std::cref(m_website_root), ".mustache", std::placeholders::_1, false ) ); } SPDLOG_TRACE(statuslog, "Flushing output"); m_stream_out->flush(); } std::string Response::on_mustache_retrieve() { return load_mustache(); } const cgi::Env& Response::cgi_env() const { return *m_cgi_env; } const cgi::PostMapType& Response::cgi_post() const { return cgi::read_post(std::cin, cgi_env(), settings().as<uint32_t>("max_post_size")); } const std::string& Response::base_uri() const { return m_base_uri; } std::string Response::load_mustache() const { boost::optional<std::string> content = load_whole_file(m_website_root, ".html.mstch", page_basename(), true); return *content; } const Storage& Response::storage() const { assert(m_storage.is_connected()); return m_storage; } const SettingsBag& Response::settings() const { assert(m_settings); return *m_settings; } tawashi::HttpHeader Response::make_redirect (tawashi::HttpStatusCodes parCode, const std::string& parLocation) { std::ostringstream oss; oss << base_uri() << '/' << parLocation; auto statuslog = spdlog::get("statuslog"); assert(statuslog); statuslog->info("Redirecting to page \"{}\"", oss.str()); return tawashi::HttpHeader(parCode, oss.str()); } tawashi::HttpHeader Response::make_error_redirect (tawashi::ErrorReasons parReason) { using tawashi::HttpStatusCodes; auto statuslog = spdlog::get("statuslog"); assert(statuslog); const HttpStatusCodes redir_code = HttpStatusCodes::Code302_Found; statuslog->info("Redirecting to error page, code={} reason={}", redir_code, parReason); std::ostringstream oss; oss << "error.cgi?reason=" << parReason._to_integral(); return make_redirect(redir_code, oss.str()); } void Response::set_app_start_time (const std::chrono::time_point<std::chrono::steady_clock>& parTime) { assert(parTime <= m_time0); m_time0 = parTime; } std::string Response::default_pastie_lang() { return std::string(); } void Response::join() { } } //namespace kamokan
gpl-3.0
chu11/freeipmi-mirror
libfreeipmi/api/ipmi-event-cmds-api.c
2
7914
/* * Copyright (C) 2003-2015 FreeIPMI Core 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 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #ifdef HAVE_CONFIG_H #include <config.h> #endif /* HAVE_CONFIG_H */ #include <stdio.h> #include <stdlib.h> #ifdef STDC_HEADERS #include <string.h> #endif /* STDC_HEADERS */ #include <errno.h> #include "freeipmi/api/ipmi-event-cmds-api.h" #include "freeipmi/cmds/ipmi-event-cmds.h" #include "freeipmi/fiid/fiid.h" #include "freeipmi/spec/ipmi-ipmb-lun-spec.h" #include "freeipmi/spec/ipmi-netfn-spec.h" #include "ipmi-api-defs.h" #include "ipmi-api-trace.h" #include "ipmi-api-util.h" #include "libcommon/ipmi-fiid-util.h" #include "freeipmi-portability.h" int ipmi_cmd_set_event_receiver (ipmi_ctx_t ctx, uint8_t event_receiver_slave_address, uint8_t event_receiver_lun, fiid_obj_t obj_cmd_rs) { fiid_obj_t obj_cmd_rq = NULL; int rv = -1; if (!ctx || ctx->magic != IPMI_CTX_MAGIC) { ERR_TRACE (ipmi_ctx_errormsg (ctx), ipmi_ctx_errnum (ctx)); return (-1); } /* remaining parameter checks in fill function */ if (!fiid_obj_valid (obj_cmd_rs)) { API_SET_ERRNUM (ctx, IPMI_ERR_PARAMETERS); return (-1); } if (FIID_OBJ_TEMPLATE_COMPARE (obj_cmd_rs, tmpl_cmd_set_event_receiver_rs) < 0) { API_FIID_OBJECT_ERROR_TO_API_ERRNUM (ctx, obj_cmd_rs); return (-1); } if (!(obj_cmd_rq = fiid_obj_create (tmpl_cmd_set_event_receiver_rq))) { API_ERRNO_TO_API_ERRNUM (ctx, errno); goto cleanup; } if (fill_cmd_set_event_receiver (event_receiver_slave_address, event_receiver_lun, obj_cmd_rq) < 0) { API_ERRNO_TO_API_ERRNUM (ctx, errno); goto cleanup; } if (api_ipmi_cmd (ctx, IPMI_BMC_IPMB_LUN_BMC, IPMI_NET_FN_SENSOR_EVENT_RQ, obj_cmd_rq, obj_cmd_rs) < 0) { ERR_TRACE (ipmi_ctx_errormsg (ctx), ipmi_ctx_errnum (ctx)); goto cleanup; } rv = 0; cleanup: fiid_obj_destroy (obj_cmd_rq); return (rv); } int ipmi_cmd_set_event_receiver_ipmb (ipmi_ctx_t ctx, uint8_t channel_number, uint8_t slave_address, uint8_t event_receiver_slave_address, uint8_t event_receiver_lun, fiid_obj_t obj_cmd_rs) { fiid_obj_t obj_cmd_rq = NULL; int rv = -1; if (!ctx || ctx->magic != IPMI_CTX_MAGIC) { ERR_TRACE (ipmi_ctx_errormsg (ctx), ipmi_ctx_errnum (ctx)); return (-1); } if (!fiid_obj_valid (obj_cmd_rs)) { API_SET_ERRNUM (ctx, IPMI_ERR_PARAMETERS); return (-1); } if (FIID_OBJ_TEMPLATE_COMPARE (obj_cmd_rs, tmpl_cmd_set_event_receiver_rs) < 0) { API_FIID_OBJECT_ERROR_TO_API_ERRNUM (ctx, obj_cmd_rs); return (-1); } if (!(obj_cmd_rq = fiid_obj_create (tmpl_cmd_set_event_receiver_rq))) { API_ERRNO_TO_API_ERRNUM (ctx, errno); goto cleanup; } if (fill_cmd_set_event_receiver (event_receiver_slave_address, event_receiver_lun, obj_cmd_rq) < 0) { API_ERRNO_TO_API_ERRNUM (ctx, errno); goto cleanup; } if (api_ipmi_cmd_ipmb (ctx, channel_number, slave_address, IPMI_BMC_IPMB_LUN_BMC, IPMI_NET_FN_SENSOR_EVENT_RQ, obj_cmd_rq, obj_cmd_rs) < 0) { ERR_TRACE (ipmi_ctx_errormsg (ctx), ipmi_ctx_errnum (ctx)); goto cleanup; } rv = 0; cleanup: fiid_obj_destroy (obj_cmd_rq); return (rv); } int ipmi_cmd_get_event_receiver (ipmi_ctx_t ctx, fiid_obj_t obj_cmd_rs) { fiid_obj_t obj_cmd_rq = NULL; int rv = -1; if (!ctx || ctx->magic != IPMI_CTX_MAGIC) { ERR_TRACE (ipmi_ctx_errormsg (ctx), ipmi_ctx_errnum (ctx)); return (-1); } if (!fiid_obj_valid (obj_cmd_rs)) { API_SET_ERRNUM (ctx, IPMI_ERR_PARAMETERS); return (-1); } if (FIID_OBJ_TEMPLATE_COMPARE (obj_cmd_rs, tmpl_cmd_get_event_receiver_rs) < 0) { API_FIID_OBJECT_ERROR_TO_API_ERRNUM (ctx, obj_cmd_rs); return (-1); } if (!(obj_cmd_rq = fiid_obj_create (tmpl_cmd_get_event_receiver_rq))) { API_ERRNO_TO_API_ERRNUM (ctx, errno); goto cleanup; } if (fill_cmd_get_event_receiver (obj_cmd_rq) < 0) { API_ERRNO_TO_API_ERRNUM (ctx, errno); goto cleanup; } if (api_ipmi_cmd (ctx, IPMI_BMC_IPMB_LUN_BMC, IPMI_NET_FN_SENSOR_EVENT_RQ, obj_cmd_rq, obj_cmd_rs) < 0) { ERR_TRACE (ipmi_ctx_errormsg (ctx), ipmi_ctx_errnum (ctx)); goto cleanup; } rv = 0; cleanup: fiid_obj_destroy (obj_cmd_rq); return (rv); } int ipmi_cmd_platform_event (ipmi_ctx_t ctx, uint8_t *generator_id, uint8_t event_message_format_version, uint8_t sensor_type, uint8_t sensor_number, uint8_t event_type_code, uint8_t event_dir, uint8_t event_data1, uint8_t event_data2, uint8_t event_data3, fiid_obj_t obj_cmd_rs) { fiid_obj_t obj_cmd_rq = NULL; int rv = -1; if (!ctx || ctx->magic != IPMI_CTX_MAGIC) { ERR_TRACE (ipmi_ctx_errormsg (ctx), ipmi_ctx_errnum (ctx)); return (-1); } /* remaining parameter checks in fill function */ if (!fiid_obj_valid (obj_cmd_rs)) { API_SET_ERRNUM (ctx, IPMI_ERR_PARAMETERS); return (-1); } if (FIID_OBJ_TEMPLATE_COMPARE (obj_cmd_rs, tmpl_cmd_platform_event_rs) < 0) { API_FIID_OBJECT_ERROR_TO_API_ERRNUM (ctx, obj_cmd_rs); return (-1); } if (!(obj_cmd_rq = fiid_obj_create (tmpl_cmd_platform_event_rq))) { API_ERRNO_TO_API_ERRNUM (ctx, errno); goto cleanup; } if (fill_cmd_platform_event (generator_id, event_message_format_version, sensor_type, sensor_number, event_type_code, event_dir, event_data1, event_data2, event_data3, obj_cmd_rq) < 0) { API_ERRNO_TO_API_ERRNUM (ctx, errno); goto cleanup; } if (api_ipmi_cmd (ctx, IPMI_BMC_IPMB_LUN_BMC, IPMI_NET_FN_SENSOR_EVENT_RQ, obj_cmd_rq, obj_cmd_rs) < 0) { ERR_TRACE (ipmi_ctx_errormsg (ctx), ipmi_ctx_errnum (ctx)); goto cleanup; } rv = 0; cleanup: fiid_obj_destroy (obj_cmd_rq); return (rv); }
gpl-3.0
geodynamics/specfem3d_geotech
src/plastic_library.f90
2
5977
! this module contains the routine for Mohr-Coulomb plasticity, Viscoplastic ! algorithm, and strength reduction techniques ! AUTHOR ! Hom Nath Gharti ! REVISION ! HNG, Jul 07,2011; HNG, Apr 09,2010 module plastic_library use set_precision use math_constants use conversion_constants,only:DEG2RAD,RAD2DEG contains !------------------------------------------------------------------------------- ! this function computes the stable pseudo-time step ! for viscoplastic algorithm (Cormeau 1975, Smith and Griffiths 2003) function dt_viscoplas(nmat,nuf,phif,ymf,ismat) result(dt_min) implicit none integer,intent(in) :: nmat ! friction angle,Poisson's ratio, strength reduction factor real(kind=kreal),intent(in) :: ymf(nmat),phif(nmat),nuf(nmat) ! phif in degrees logical,optional,intent(in) :: ismat(nmat) real(kind=kreal) :: dt_min real(kind=kreal) :: dt,snphi real(kind=kreal),parameter :: r4=4.0_kreal integer :: i_mat logical :: ismat_on(nmat) ismat_on=.true. if(present(ismat))ismat_on=ismat ! compute minimum pseudo-time step for viscoplasticity dt_min=inftol do i_mat=1,nmat if(.not.ismat_on(i_mat))cycle snphi=sin(phif(i_mat)*deg2rad) dt=r4*(one+nuf(i_mat))*(one-two*nuf(i_mat))/(ymf(i_mat)*(one-two*nuf(i_mat)+ & snphi**2)) if(dt<dt_min)dt_min=dt end do end function dt_viscoplas !=============================================================================== subroutine strength_reduction(srf,phinu,nmat,coh,nu,phi,psi,cohf,nuf,phif,psif,& istat) implicit none real(kind=kreal),intent(in) :: srf logical :: phinu integer,intent(in) :: nmat real(kind=kreal),intent(in) :: coh(nmat),nu(nmat),phi(nmat),psi(nmat) ! phi,psi in degrees real(kind=kreal),intent(out) :: cohf(nmat),nuf(nmat),phif(nmat),psif(nmat) ! phif,psif in degrees ! status whether the material properties has changed integer,intent(out) :: istat integer :: i_mat real(kind=kreal) :: beta_nuphi,omtnu,snphi,snphif,tnphi,tnpsi cohf=coh; nuf=nu; phif=phi; psif=psi istat=0 ! strength reduction if(srf/=one)then do i_mat=1,nmat tnphi=tan(phi(i_mat)*deg2rad) phif(i_mat)=atan(tnphi/srf)*rad2deg tnpsi=tan(psi(i_mat)*deg2rad) psif(i_mat)=atan(tnpsi/srf)*rad2deg cohf(i_mat)=coh(i_mat)/srf enddo endif if(.not.phinu)return ! correction for phi-nu inequality sin(phi)>=1-2*nu ! Reference: Zheng et al 2005, IJNME ! currently only the Poisson's ratio is corrected do i_mat=1,nmat omtnu=one-two*nu(i_mat) snphif=sin(phif(i_mat)*deg2rad) if(snphif<omtnu)then snphi=sin(phi(i_mat)*deg2rad) beta_nuphi=snphi/omtnu if(beta_nuphi<one)beta_nuphi=one+zerotol nuf(i_mat)=half*(one-snphif/beta_nuphi) istat=1 ! material properties has changed endif enddo return end subroutine strength_reduction !=============================================================================== ! this subroutine calculates the value of the yield function ! for a mohr-coulomb material (phi in degrees, theta in radians). ! this routine was copied and modified from ! Smith and Griffiths (2004): Programming the finite element method subroutine mohcouf(phi,c,sigm,dsbar,theta,f) implicit none real(kind=kreal),intent(in)::phi,c,sigm,dsbar,theta real(kind=kreal),intent(out)::f real(kind=kreal)::phir,snph,csph,csth,snth,r3=3.0_kreal phir=phi*deg2rad snph=sin(phir) csph=cos(phir) csth=cos(theta) snth=sin(theta) f=snph*sigm+dsbar*(csth/sqrt(r3)-snth*snph/r3)-c*csph return end subroutine mohcouf !=============================================================================== ! this subroutine forms the derivatives of a mohr-coulomb potential ! function with respect to the three stress invariants ! (psi in degrees, theta in radians). ! this routine was copied and modified from ! Smith and Griffiths (2004): Programming the finite element method subroutine mohcouq(psi,dsbar,theta,dq1,dq2,dq3) implicit none real(kind=kreal),intent(in)::psi,dsbar,theta real(kind=kreal),intent(out)::dq1,dq2,dq3 real(kind=kreal)::psir,snth,snps,sq3,c1,csth,cs3th,tn3th,tnth,pt49=0.49_kreal,& pt5=0.5_kreal,r3=3.0_kreal psir=psi*deg2rad snth=sin(theta) snps=sin(psir) sq3=sqrt(r3) dq1=snps if(abs(snth).gt.pt49)then c1=one if(snth.lt.zero)c1=-one dq2=(sq3*pt5-c1*snps*pt5/sq3)*sq3*pt5/dsbar dq3=zero else csth=cos(theta) cs3th=cos(r3*theta) tn3th=tan(r3*theta) tnth=snth/csth dq2=sq3*csth/dsbar*((one+tnth*tn3th)+snps*(tn3th-tnth)/sq3)*pt5 dq3=pt5*r3*(sq3*snth+snps*csth)/(cs3th*dsbar*dsbar) end if return end subroutine mohcouq !=============================================================================== ! this subroutine forms the derivatives of the invariants with respect to ! stress in 3d. ! this routine was copied and modified from ! Smith and Griffiths (2004): Programming the finite element method subroutine formm(stress,m1,m2,m3) implicit none real(kind=kreal),intent(in)::stress(:) real(kind=kreal),intent(out)::m1(:,:),m2(:,:),m3(:,:) real(kind=kreal)::sx,sy,txy,tyz,tzx,sz,dx,dy,dz,sigm, & r3=3.0_kreal,r6=6.0_kreal integer::nst,i,j nst=ubound(stress,1) if(nst.ne.6)then write(*,*)'ERROR: wrong size of the stress tensor!' stop endif sx=stress(1); sy=stress(2); sz=stress(3) txy=stress(4); tyz=stress(5); tzx=stress(6) sigm=(sx+sy+sz)/r3 dx=sx-sigm; dy=sy-sigm; dz=sz-sigm m1=zero; m2=zero m1(1:3,1:3)=one/(r3*sigm) do i=1,3 m2(i,i)=two m2(i+3,i+3)=r6 end do m2(1,2)=-one m2(1,3)=-one m2(2,3)=-one m3(1,1)=dx m3(1,2)=dz m3(1,3)=dy m3(1,4)=txy m3(1,5)=-two*tyz m3(1,6)=tzx m3(2,2)=dy m3(2,3)=dx m3(2,4)=txy m3(2,5)=tyz m3(2,6)=-two*tzx m3(3,3)=dz m3(3,4)=-two*txy m3(3,5)=tyz m3(3,6)=tzx m3(4,4)=-r3*dz m3(4,5)=r3*tzx m3(4,6)=r3*tyz m3(5,5)=-r3*dx m3(5,6)=r3*txy m3(6,6)=-r3*dy do i=1,6 do j=i+1,6 m1(j,i)=m1(i,j) m2(j,i)=m2(i,j) m3(j,i)=m3(i,j) end do end do m1=m1/r3; m2=m2/r3; m3=m3/r3 return end subroutine formm !=============================================================================== end module plastic_library !===============================================================================
gpl-3.0
wdzhou/mantid
Framework/Kernel/src/FilterChannel.cpp
3
2667
#include "MantidKernel/FilterChannel.h" #include <MantidKernel/StringTokenizer.h> #include <Poco/LoggingRegistry.h> #include <Poco/Message.h> #include <algorithm> namespace Poco { FilterChannel::FilterChannel() : _channel(nullptr), _priority(8) {} FilterChannel::~FilterChannel() { close(); } void FilterChannel::addChannel(Channel *pChannel) { poco_check_ptr(pChannel); std::lock_guard<std::mutex> lock(_mutex); pChannel->duplicate(); _channel = pChannel; } void FilterChannel::setProperty(const std::string &name, const std::string &value) { if (name.compare(0, 7, "channel") == 0) { Mantid::Kernel::StringTokenizer tokenizer( value, ",;", Mantid::Kernel::StringTokenizer::TOK_IGNORE_EMPTY | Mantid::Kernel::StringTokenizer::TOK_TRIM); for (const auto &piece : tokenizer) { addChannel(LoggingRegistry::defaultRegistry().channelForName(piece)); } } else if (name.compare(0, 5, "level") == 0) { setPriority(value); } else Channel::setProperty(name, value); } void FilterChannel::log(const Message &msg) { std::lock_guard<std::mutex> lock(_mutex); if ((_channel) && (msg.getPriority() <= _priority)) { _channel->log(msg); } } void FilterChannel::close() { std::lock_guard<std::mutex> lock(_mutex); if (_channel != nullptr) { _channel->release(); } } const FilterChannel &FilterChannel::setPriority(const int &priority) { _priority = priority; return *this; } const FilterChannel &FilterChannel::setPriority(const std::string &priority) { // take a local copy of the input std::string workPriority = priority; // convert to upper case std::transform(workPriority.begin(), workPriority.end(), workPriority.begin(), toupper); // if there is a prefix strip it off if (workPriority.compare(0, 5, "PRIO_") == 0) { workPriority = workPriority.substr(5, workPriority.length() - 5); } if (workPriority.compare(0, 2, "FA") == 0) // PRIO_FATAL _priority = 1; else if (workPriority.compare(0, 2, "CR") == 0) // PRIO_CRITICAL _priority = 2; else if (workPriority.compare(0, 2, "ER") == 0) // PRIO_ERROR _priority = 3; else if (workPriority.compare(0, 2, "WA") == 0) // PRIO_WARNING _priority = 4; else if (workPriority.compare(0, 2, "NO") == 0) // PRIO_NOTICE _priority = 5; else if (workPriority.compare(0, 2, "IN") == 0) // PRIO_INFORMATION _priority = 6; else if (workPriority.compare(0, 2, "DE") == 0) // PRIO_DEBUG _priority = 7; else if (workPriority.compare(0, 2, "TR") == 0) // PRIO_TRACE _priority = 8; return *this; } } // namespace Poco
gpl-3.0
Tsunamical/nds4droid
app/src/main/jni/desmume/src/android/7z/CPP/7zip/UI/FileManager/OverwriteDialog_rc.cpp
3
4566
// OverwriteDialog_rc.cpp #include "StdAfx.h" // For compilers that support precompilation, includes "wx/wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif // for all others, include the necessary headers (this file is usually all you // need because it includes almost all "standard" wxWidgets headers) #ifndef WX_PRECOMP #include "wx/wx.h" #endif #include "OverwriteDialogRes.h" #include "Windows/Control/DialogImpl.h" /* IDD_DIALOG_OVERWRITE DIALOG 0, 0, xSize, ySize MY_MODAL_DIALOG_STYLE CAPTION "Confirm File Replace" MY_FONT BEGIN LTEXT "Destination folder already contains processed file.", IDC_STATIC_OVERWRITE_HEADER, marg, 7, xSize2, 8 LTEXT "Would you like to replace the existing file", IDC_STATIC_OVERWRITE_QUESTION_BEGIN, marg, 28, xSize2, 8 ICON "", IDC_STATIC_OVERWRITE_OLD_FILE_ICON, marg, 44, iconSize, iconSize LTEXT "", IDC_STATIC_OVERWRITE_OLD_FILE_SIZE_TIME, fiXPos, 44, fiXSize, fiYSize, SS_NOPREFIX LTEXT "with this one?",IDC_STATIC_OVERWRITE_QUESTION_END, marg, 98, xSize2, 8 ICON "",IDC_STATIC_OVERWRITE_NEW_FILE_ICON, marg, 114, iconSize, iconSize LTEXT "",IDC_STATIC_OVERWRITE_NEW_FILE_SIZE_TIME, fiXPos, 114, fiXSize, fiYSize, SS_NOPREFIX PUSHBUTTON "&Yes", IDYES, 78, b2YPos, bXSize, bYSize PUSHBUTTON "Yes to &All", IDC_BUTTON_OVERWRITE_YES_TO_ALL, 152, b2YPos, bXSize, bYSize PUSHBUTTON "&No", IDNO, 226, b2YPos, bXSize, bYSize PUSHBUTTON "No to A&ll", IDC_BUTTON_OVERWRITE_NO_TO_ALL, 300, b2YPos, bXSize, bYSize PUSHBUTTON "A&uto Rename", IDC_BUTTON_OVERWRITE_AUTO_RENAME, 181, b1YPos, 109, bYSize PUSHBUTTON "&Cancel", IDCANCEL, 300, b1YPos, bXSize, bYSize END */ class COverwriteDialogImpl : public NWindows::NControl::CModalDialogImpl { public: COverwriteDialogImpl(NWindows::NControl::CModalDialog *dialog,wxWindow * parent , int id) : CModalDialogImpl(dialog,parent, id, wxT("Confirm File Replace")) { ///Sizer for adding the controls created by users wxBoxSizer* topsizer = new wxBoxSizer(wxVERTICAL); topsizer->Add(new wxStaticText(this, IDC_STATIC_OVERWRITE_HEADER, _T("Destination folder already contains processed file.")) , 0 ,wxALL | wxALIGN_LEFT, 5 ); topsizer->Add(new wxStaticText(this, IDC_STATIC_OVERWRITE_QUESTION_BEGIN, _T("Would you like to replace the existing file")) , 0 ,wxALL | wxALIGN_LEFT, 5 ); // FIXME ICON "", IDC_STATIC_OVERWRITE_OLD_FILE_ICON, marg, 44, iconSize, iconSize topsizer->Add(new wxStaticText(this, IDC_STATIC_OVERWRITE_OLD_FILE_SIZE_TIME, _T(""), wxDefaultPosition, wxDefaultSize, wxALIGN_LEFT) , 0 ,wxALL | wxALIGN_LEFT, 15 ); topsizer->Add(new wxStaticText(this, IDC_STATIC_OVERWRITE_QUESTION_END, _T("with this one?")) , 0 ,wxALL | wxALIGN_LEFT, 5 ); // FIXME ICON "",IDC_STATIC_OVERWRITE_NEW_FILE_ICON, marg, 114, iconSize, iconSize topsizer->Add(new wxStaticText(this, IDC_STATIC_OVERWRITE_NEW_FILE_SIZE_TIME, _T(""), wxDefaultPosition, wxDefaultSize, wxALIGN_LEFT) , 0 ,wxALL | wxALIGN_LEFT, 15 ); wxBoxSizer* Sizer1 = new wxBoxSizer(wxHORIZONTAL); Sizer1->Add(new wxButton(this, wxID_YES, _T("&Yes")) , 0, wxALL | wxALIGN_RIGHT, 5); Sizer1->Add(new wxButton(this, IDC_BUTTON_OVERWRITE_YES_TO_ALL, _T("Yes to &All")) , 0, wxALL | wxALIGN_RIGHT, 5); Sizer1->Add(new wxButton(this, wxID_NO, _T("&No")) , 0, wxALL | wxALIGN_RIGHT, 5); Sizer1->Add(new wxButton(this, IDC_BUTTON_OVERWRITE_NO_TO_ALL, _T("No to A&ll")) , 0, wxALL | wxALIGN_RIGHT, 5); topsizer->Add(Sizer1 , 0, wxALL | wxALIGN_RIGHT, 5); wxBoxSizer* Sizer2 = new wxBoxSizer(wxHORIZONTAL); Sizer2->Add(new wxButton(this, IDC_BUTTON_OVERWRITE_AUTO_RENAME, _T("A&uto Rename")) , 0, wxALL | wxALIGN_RIGHT, 5); Sizer2->Add(new wxButton(this, wxID_CANCEL, _T("&Cancel")) , 0, wxALL | wxALIGN_RIGHT, 5); topsizer->Add(Sizer2 , 1, wxALL | wxALIGN_RIGHT, 5); this->OnInit(); SetSizer(topsizer); // use the sizer for layout topsizer->SetSizeHints(this); // set size hints to honour minimum size } private: // Any class wishing to process wxWindows events must use this macro DECLARE_EVENT_TABLE() }; static CStringTable g_stringTable[] = { { IDS_FILE_MODIFIED, L"modified on" }, { IDS_FILE_SIZE, L"{0} bytes" }, { 0 , 0 } }; REGISTER_DIALOG(IDD_DIALOG_OVERWRITE,COverwriteDialog,g_stringTable) BEGIN_EVENT_TABLE(COverwriteDialogImpl, wxDialog) EVT_BUTTON(wxID_ANY, CModalDialogImpl::OnAnyButton) END_EVENT_TABLE()
gpl-3.0
blackheartevony/https---github.com-calamares-calamares-manjaro
src/calamares/main.cpp
3
2184
/* === This file is part of Calamares - <http://github.com/calamares> === * * Copyright 2014, Teo Mrnjavac <teo@kde.org> * * Calamares 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. * * Calamares 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 Calamares. If not, see <http://www.gnu.org/licenses/>. */ #include "CalamaresApplication.h" #include "kdsingleapplicationguard/kdsingleapplicationguard.h" #include "utils/CalamaresUtils.h" #include "utils/Logger.h" #include <QCommandLineParser> #include <QDebug> #include <QDir> int main( int argc, char* argv[] ) { CalamaresApplication a( argc, argv ); QCommandLineParser parser; parser.setApplicationDescription( "Distribution-independent installer framework" ); parser.addHelpOption(); parser.addVersionOption(); QCommandLineOption debugOption( QStringList() << "d" << "debug", "Verbose output for debugging purposes." ); parser.addOption( debugOption ); QCommandLineOption configOption( QStringList() << "c" << "config", "Configuration directory to use, for testing purposes.", "config" ); parser.addOption( configOption ); parser.process( a ); a.setDebug( parser.isSet( debugOption ) ); if ( parser.isSet( configOption ) ) CalamaresUtils::setAppDataDir( QDir( parser.value( configOption ) ) ); KDSingleApplicationGuard guard( KDSingleApplicationGuard::AutoKillOtherInstances ); int returnCode = 0; if ( guard.isPrimaryInstance() ) { a.init(); returnCode = a.exec(); } else qDebug() << "Calamares is already running, shutting down."; return returnCode; }
gpl-3.0
seemoo-lab/nexmon
buildtools/mpfr-3.1.4/src/reldiff.c
3
2170
/* mpfr_reldiff -- compute relative difference of two floating-point numbers. Copyright 2000-2001, 2004-2016 Free Software Foundation, Inc. Contributed by the AriC and Caramba projects, INRIA. This file is part of the GNU MPFR Library. The GNU MPFR Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. The GNU MPFR Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU MPFR Library; see the file COPYING.LESSER. If not, see http://www.gnu.org/licenses/ or write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "mpfr-impl.h" /* reldiff(b, c) = abs(b-c)/b */ void mpfr_reldiff (mpfr_ptr a, mpfr_srcptr b, mpfr_srcptr c, mpfr_rnd_t rnd_mode) { mpfr_t b_copy; if (MPFR_ARE_SINGULAR (b, c)) { if (MPFR_IS_NAN(b) || MPFR_IS_NAN(c)) { MPFR_SET_NAN(a); return; } else if (MPFR_IS_INF(b)) { if (MPFR_IS_INF (c) && (MPFR_SIGN (c) == MPFR_SIGN (b))) MPFR_SET_ZERO(a); else MPFR_SET_NAN(a); return; } else if (MPFR_IS_INF(c)) { MPFR_SET_SAME_SIGN (a, b); MPFR_SET_INF (a); return; } else if (MPFR_IS_ZERO(b)) /* reldiff = abs(c)/c = sign(c) */ { mpfr_set_si (a, MPFR_INT_SIGN (c), rnd_mode); return; } /* Fall through */ } if (a == b) { mpfr_init2 (b_copy, MPFR_PREC(b)); mpfr_set (b_copy, b, MPFR_RNDN); } mpfr_sub (a, b, c, rnd_mode); mpfr_abs (a, a, rnd_mode); /* for compatibility with MPF */ mpfr_div (a, a, (a == b) ? b_copy : b, rnd_mode); if (a == b) mpfr_clear (b_copy); }
gpl-3.0
macchina-io/macchina.io
platform/Data/src/Session.cpp
3
1640
// // Session.cpp // // Library: Data // Package: DataCore // Module: Session // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // SPDX-License-Identifier: BSL-1.0 // #include "Poco/Data/Session.h" #include "Poco/Data/SessionFactory.h" #include "Poco/String.h" #include "Poco/URI.h" #include <algorithm> namespace Poco { namespace Data { Session::Session(Poco::AutoPtr<SessionImpl> pImpl): _pImpl(pImpl), _statementCreator(pImpl) { poco_check_ptr (pImpl.get()); } Session::Session(const std::string& connector, const std::string& connectionString, std::size_t timeout) { Session newSession(SessionFactory::instance().create(connector, connectionString, timeout)); swap(newSession); } Session::Session(const std::string& connection, std::size_t timeout) { Session newSession(SessionFactory::instance().create(connection, timeout)); swap(newSession); } Session::Session(const Session& other): _pImpl(other._pImpl), _statementCreator(other._statementCreator) { } Session::Session(Session&& other) noexcept: _pImpl(std::move(other._pImpl)), _statementCreator(std::move(other._statementCreator)) { } Session::~Session() { } Session& Session::operator = (const Session& other) { Session tmp(other); swap(tmp); return *this; } Session& Session::operator = (Session&& other) noexcept { _pImpl = std::move(other._pImpl); _statementCreator = std::move(other._statementCreator); return *this; } void Session::swap(Session& other) { using std::swap; swap(_statementCreator, other._statementCreator); swap(_pImpl, other._pImpl); } } } // namespace Poco::Data
gpl-3.0
kloper/openvrml
src/node/x3d-geospatial/geo_origin.cpp
3
3800
// -*- Mode: C++; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 78 -*- // // OpenVRML // // Copyright 2006, 2007, 2008, 2009 Braden McDaniel // // 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 3 of the License, or (at your // option) any later version. // // This library is distributed in the hope that it will be useful, but WITHOUT // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or // FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public // License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this library; if not, see <http://www.gnu.org/licenses/>. // # include "geo_origin.h" # include "geospatial-common.h" # include <openvrml/node_impl_util.h> # include <boost/array.hpp> # ifdef HAVE_CONFIG_H # include <config.h> # endif using namespace openvrml; using namespace openvrml::node_impl_util; using namespace std; namespace { /** * @brief Represents GeoOrigin node instances. */ class OPENVRML_LOCAL geo_origin_node : public abstract_node<geo_origin_node> { friend class openvrml_node_x3d_geospatial::geo_origin_metatype; exposedfield<sfvec3d> geo_coords_; exposedfield<mfstring> geo_system_; sfbool rotate_y_up_; public: geo_origin_node(const node_type & type, const boost::shared_ptr<openvrml::scope> & scope); virtual ~geo_origin_node() OPENVRML_NOTHROW; }; /** * @var geo_origin_node::geo_origin_metatype * * @brief Class object for GeoOrigin nodes. */ /** * @var geo_origin_node::geo_coords_ * * @brief geo_coords exposedField */ /** * @var geo_origin_node::geo_system_ * * @brief geo_system exposedField */ /** * @var geo_origin_node::rotate_yup_ * * @brief rotate_yup field */ /** * @brief Construct. * * @param type the node_type associated with this node. * @param scope the scope to which the node belongs. */ geo_origin_node:: geo_origin_node(const node_type & type, const boost::shared_ptr<openvrml::scope> & scope): node(type, scope), abstract_node<self_t>(type, scope), geo_coords_(*this), geo_system_(*this, openvrml_node_x3d_geospatial::default_geo_system) {} /** * @brief Destroy. */ geo_origin_node::~geo_origin_node() OPENVRML_NOTHROW {} } /** * @brief @c node_metatype identifier. */ const char * const openvrml_node_x3d_geospatial::geo_origin_metatype::id = "urn:X-openvrml:node:GeoOrigin"; /** * @brief Construct. * * @param browser the @c browser associated with this @c geo_origin_metatype. */ openvrml_node_x3d_geospatial::geo_origin_metatype:: geo_origin_metatype(openvrml::browser & browser): node_metatype(geo_origin_metatype::id, browser) {} /** * @brief Destroy. */ openvrml_node_x3d_geospatial::geo_origin_metatype::~geo_origin_metatype() OPENVRML_NOTHROW {} # define GEO_ORIGIN_INTERFACE_SEQ \ ((exposedfield, sfnode, "metadata", metadata)) \ ((exposedfield, sfvec3d, "geoCoords", geo_coords_)) \ ((exposedfield, mfstring, "geoSystem", geo_system_)) \ ((field, sfbool, "rotateYUp", rotate_y_up_)) OPENVRML_NODE_IMPL_UTIL_DEFINE_DO_CREATE_TYPE(openvrml_node_x3d_geospatial, geo_origin_metatype, geo_origin_node, GEO_ORIGIN_INTERFACE_SEQ)
gpl-3.0
rggjan/Gimp-Matting
app/gegl/gimpoperationcolormode.c
3
2909
/* GIMP - The GNU Image Manipulation Program * Copyright (C) 1995 Spencer Kimball and Peter Mattis * * gimpoperationcolormode.c * Copyright (C) 2008 Michael Natterer <mitch@gimp.org> * * 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 "config.h" #include <gegl-plugin.h> #include "gimp-gegl-types.h" #include "gimpoperationcolormode.h" static gboolean gimp_operation_color_mode_process (GeglOperation *operation, void *in_buf, void *aux_buf, void *out_buf, glong samples, const GeglRectangle *roi); G_DEFINE_TYPE (GimpOperationColorMode, gimp_operation_color_mode, GIMP_TYPE_OPERATION_POINT_LAYER_MODE) static void gimp_operation_color_mode_class_init (GimpOperationColorModeClass *klass) { GeglOperationClass *operation_class; GeglOperationPointComposerClass *point_class; operation_class = GEGL_OPERATION_CLASS (klass); point_class = GEGL_OPERATION_POINT_COMPOSER_CLASS (klass); operation_class->name = "gimp:color-mode"; operation_class->description = "GIMP color mode operation"; point_class->process = gimp_operation_color_mode_process; } static void gimp_operation_color_mode_init (GimpOperationColorMode *self) { } static gboolean gimp_operation_color_mode_process (GeglOperation *operation, void *in_buf, void *aux_buf, void *out_buf, glong samples, const GeglRectangle *roi) { gfloat *in = in_buf; gfloat *layer = aux_buf; gfloat *out = out_buf; while (samples--) { out[RED] = in[RED]; out[GREEN] = in[GREEN]; out[BLUE] = in[BLUE]; out[ALPHA] = in[ALPHA]; in += 4; layer += 4; out += 4; } return TRUE; }
gpl-3.0
kumanna/itpp
gtests/siso_test.cpp
3
7253
/*! * \file * \brief SISO class test program * \author Bogdan Cristea * * ------------------------------------------------------------------------- * * Copyright (C) 1995-2013 (see AUTHORS file for a list of contributors) * * This file is part of IT++ - a C++ library of mathematical, signal * processing, speech processing, and communications classes and functions. * * IT++ 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. * * IT++ 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 IT++. If not, see <http://www.gnu.org/licenses/>. * * ------------------------------------------------------------------------- */ #include "itpp/itcomm.h" #include "gtest/gtest.h" using namespace itpp; using std::string; static void assert_vec_p(const vec &ref, const vec &act, int line) { static const double tol = 1e-4; ASSERT_EQ(ref.length(), act.length()) << line; for (int n = 0; n < ref.length(); ++n) { ASSERT_NEAR(ref(n), act(n), tol) << line; } } #define assert_vec(ref, act) assert_vec_p(ref, act, __LINE__) TEST(SISO, all) { //general parameters string map_metric="maxlogMAP"; ivec gen = "07 05";//octal form, feedback first int constraint_length = 3; int nb_errors_lim = 300; int nb_bits_lim = int(1e4); int perm_len = (1<<14);//total number of bits in a block (with tail) int nb_iter = 10;//number of iterations in the turbo decoder vec EbN0_dB = "0.0 0.5 1.0 1.5 2.0"; double R = 1.0/3.0;//coding rate (non punctured PCCC) double Ec = 1.0;//coded bit energy //other parameters int nb_bits = perm_len-(constraint_length-1);//number of bits in a block (without tail) vec sigma2 = (0.5*Ec/R)*pow(inv_dB(EbN0_dB), -1.0);//N0/2 double Lc;//scaling factor int nb_blocks;//number of blocks int nb_errors; ivec perm(perm_len); ivec inv_perm(perm_len); bvec bits(nb_bits); int cod_bits_len = perm_len*gen.length(); bmat cod1_bits;//tail is added bvec tail; bvec cod2_input; bmat cod2_bits; int rec_len = int(1.0/R)*perm_len; bvec coded_bits(rec_len); vec rec(rec_len); vec dec1_intrinsic_coded(cod_bits_len); vec dec2_intrinsic_coded(cod_bits_len); vec apriori_data(perm_len);//a priori LLR for information bits vec extrinsic_coded(perm_len); vec extrinsic_data(perm_len); bvec rec_bits(perm_len); int snr_len = EbN0_dB.length(); mat ber(nb_iter,snr_len); ber.zeros(); register int en,n; //Recursive Systematic Convolutional Code Rec_Syst_Conv_Code cc; cc.set_generator_polynomials(gen, constraint_length);//initial state should be the zero state //BPSK modulator BPSK bpsk; //AWGN channel AWGN_Channel channel; //SISO modules SISO siso; siso.set_generators(gen, constraint_length); siso.set_map_metric(map_metric); //BER BERC berc; //Fix random generators RNG_reset(12345); //main loop for (en=0;en<snr_len;en++) { channel.set_noise(sigma2(en)); Lc = -2/sigma2(en);//normalisation factor for intrinsic information (take into account the BPSK mapping) nb_errors = 0; nb_blocks = 0; while ((nb_errors<nb_errors_lim) && (nb_blocks*nb_bits<nb_bits_lim))//if at the last iteration the nb. of errors is inferior to lim, then process another block { //permutation perm = sort_index(randu(perm_len)); //inverse permutation inv_perm = sort_index(perm); //bits generation bits = randb(nb_bits); //parallel concatenated convolutional code cc.encode_tail(bits, tail, cod1_bits);//tail is added here to information bits to close the trellis cod2_input = concat(bits, tail); cc.encode(cod2_input(perm), cod2_bits); for (n=0;n<perm_len;n++)//output with no puncturing { coded_bits(3*n) = cod2_input(n);//systematic output coded_bits(3*n+1) = cod1_bits(n,0);//first parity output coded_bits(3*n+2) = cod2_bits(n,0);//second parity output } //BPSK modulation (1->-1,0->+1) + AWGN channel rec = channel(bpsk.modulate_bits(coded_bits)); //form input for SISO blocks for (n=0;n<perm_len;n++) { dec1_intrinsic_coded(2*n) = Lc*rec(3*n); dec1_intrinsic_coded(2*n+1) = Lc*rec(3*n+1); dec2_intrinsic_coded(2*n) = 0.0;//systematic output of the CC is already used in decoder1 dec2_intrinsic_coded(2*n+1) = Lc*rec(3*n+2); } //turbo decoder apriori_data.zeros();//a priori LLR for information bits for (n=0;n<nb_iter;n++) { //first decoder siso.rsc(extrinsic_coded, extrinsic_data, dec1_intrinsic_coded, apriori_data, true); //interleave apriori_data = extrinsic_data(perm); //second decoder siso.rsc(extrinsic_coded, extrinsic_data, dec2_intrinsic_coded, apriori_data, false); //decision apriori_data += extrinsic_data;//a posteriori information rec_bits = bpsk.demodulate_bits(-apriori_data(inv_perm));//take into account the BPSK mapping //count errors berc.clear(); berc.count(bits, rec_bits.left(nb_bits)); ber(n,en) += berc.get_errorrate(); //deinterleave for the next iteration apriori_data = extrinsic_data(inv_perm); }//end iterations nb_errors += int(berc.get_errors());//get number of errors at the last iteration nb_blocks++; }//end blocks (while loop) //compute BER over all tx blocks ber.set_col(en, ber.get_col(en)/nb_blocks); } // Results for max log MAP algorithm vec ref = "0.158039 0.110731 0.0770358 0.0445611 0.0235014"; assert_vec(ref, ber.get_row(0)); ref = "0.14168 0.0783177 0.0273471 0.00494445 0.00128189"; assert_vec(ref, ber.get_row(1)); ref = "0.141375 0.0565865 0.00817971 0.000305213 0"; assert_vec(ref, ber.get_row(2)); ref = "0.142412 0.0421194 0.000732511 0 0"; assert_vec(ref, ber.get_row(3)); ref = "0.144244 0.0282017 0.000183128 0 0"; assert_vec(ref, ber.get_row(4)); ref = "0.145587 0.0142229 0 0 0"; assert_vec(ref, ber.get_row(5)); ref = "0.148517 0.00714199 0 0 0"; assert_vec(ref, ber.get_row(6)); ref = "0.141619 0.00225858 0 0 0"; assert_vec(ref, ber.get_row(7)); ref = "0.149676 0.000549383 0 0 0"; assert_vec(ref, ber.get_row(8)); ref = "0.14461 0 0 0 0"; assert_vec(ref, ber.get_row(9)); }
gpl-3.0
javierag/samba
source3/winbindd/winbindd_pam.c
4
71732
/* Unix SMB/CIFS implementation. Winbind daemon - pam auth funcions Copyright (C) Andrew Tridgell 2000 Copyright (C) Tim Potter 2001 Copyright (C) Andrew Bartlett 2001-2002 Copyright (C) Guenther Deschner 2005 This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "includes.h" #include "winbindd.h" #include "../libcli/auth/libcli_auth.h" #include "../librpc/gen_ndr/ndr_samr_c.h" #include "rpc_client/cli_pipe.h" #include "rpc_client/cli_samr.h" #include "../librpc/gen_ndr/ndr_netlogon.h" #include "rpc_client/cli_netlogon.h" #include "smb_krb5.h" #include "../lib/crypto/arcfour.h" #include "../libcli/security/security.h" #include "ads.h" #include "../librpc/gen_ndr/krb5pac.h" #include "passdb/machine_sid.h" #include "auth.h" #include "../lib/tsocket/tsocket.h" #include "auth/kerberos/pac_utils.h" #include "auth/gensec/gensec.h" #include "librpc/crypto/gse_krb5.h" #include "lib/afs/afs_funcs.h" #undef DBGC_CLASS #define DBGC_CLASS DBGC_WINBIND #define LOGON_KRB5_FAIL_CLOCK_SKEW 0x02000000 static NTSTATUS append_info3_as_txt(TALLOC_CTX *mem_ctx, struct winbindd_response *resp, struct netr_SamInfo3 *info3) { char *ex; uint32_t i; resp->data.auth.info3.logon_time = nt_time_to_unix(info3->base.logon_time); resp->data.auth.info3.logoff_time = nt_time_to_unix(info3->base.logoff_time); resp->data.auth.info3.kickoff_time = nt_time_to_unix(info3->base.kickoff_time); resp->data.auth.info3.pass_last_set_time = nt_time_to_unix(info3->base.last_password_change); resp->data.auth.info3.pass_can_change_time = nt_time_to_unix(info3->base.allow_password_change); resp->data.auth.info3.pass_must_change_time = nt_time_to_unix(info3->base.force_password_change); resp->data.auth.info3.logon_count = info3->base.logon_count; resp->data.auth.info3.bad_pw_count = info3->base.bad_password_count; resp->data.auth.info3.user_rid = info3->base.rid; resp->data.auth.info3.group_rid = info3->base.primary_gid; sid_to_fstring(resp->data.auth.info3.dom_sid, info3->base.domain_sid); resp->data.auth.info3.num_groups = info3->base.groups.count; resp->data.auth.info3.user_flgs = info3->base.user_flags; resp->data.auth.info3.acct_flags = info3->base.acct_flags; resp->data.auth.info3.num_other_sids = info3->sidcount; fstrcpy(resp->data.auth.info3.user_name, info3->base.account_name.string); fstrcpy(resp->data.auth.info3.full_name, info3->base.full_name.string); fstrcpy(resp->data.auth.info3.logon_script, info3->base.logon_script.string); fstrcpy(resp->data.auth.info3.profile_path, info3->base.profile_path.string); fstrcpy(resp->data.auth.info3.home_dir, info3->base.home_directory.string); fstrcpy(resp->data.auth.info3.dir_drive, info3->base.home_drive.string); fstrcpy(resp->data.auth.info3.logon_srv, info3->base.logon_server.string); fstrcpy(resp->data.auth.info3.logon_dom, info3->base.logon_domain.string); ex = talloc_strdup(mem_ctx, ""); NT_STATUS_HAVE_NO_MEMORY(ex); for (i=0; i < info3->base.groups.count; i++) { ex = talloc_asprintf_append_buffer(ex, "0x%08X:0x%08X\n", info3->base.groups.rids[i].rid, info3->base.groups.rids[i].attributes); NT_STATUS_HAVE_NO_MEMORY(ex); } for (i=0; i < info3->sidcount; i++) { char *sid; sid = dom_sid_string(mem_ctx, info3->sids[i].sid); NT_STATUS_HAVE_NO_MEMORY(sid); ex = talloc_asprintf_append_buffer(ex, "%s:0x%08X\n", sid, info3->sids[i].attributes); NT_STATUS_HAVE_NO_MEMORY(ex); talloc_free(sid); } resp->extra_data.data = ex; resp->length += talloc_get_size(ex); return NT_STATUS_OK; } static NTSTATUS append_info3_as_ndr(TALLOC_CTX *mem_ctx, struct winbindd_response *resp, struct netr_SamInfo3 *info3) { DATA_BLOB blob; enum ndr_err_code ndr_err; ndr_err = ndr_push_struct_blob(&blob, mem_ctx, info3, (ndr_push_flags_fn_t)ndr_push_netr_SamInfo3); if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) { DEBUG(0,("append_info3_as_ndr: failed to append\n")); return ndr_map_error2ntstatus(ndr_err); } resp->extra_data.data = blob.data; resp->length += blob.length; return NT_STATUS_OK; } static NTSTATUS append_unix_username(TALLOC_CTX *mem_ctx, struct winbindd_response *resp, const struct netr_SamInfo3 *info3, const char *name_domain, const char *name_user) { /* We've been asked to return the unix username, per 'winbind use default domain' settings and the like */ const char *nt_username, *nt_domain; nt_domain = talloc_strdup(mem_ctx, info3->base.logon_domain.string); if (!nt_domain) { /* If the server didn't give us one, just use the one * we sent them */ nt_domain = name_domain; } nt_username = talloc_strdup(mem_ctx, info3->base.account_name.string); if (!nt_username) { /* If the server didn't give us one, just use the one * we sent them */ nt_username = name_user; } fill_domain_username(resp->data.auth.unix_username, nt_domain, nt_username, true); DEBUG(5, ("Setting unix username to [%s]\n", resp->data.auth.unix_username)); return NT_STATUS_OK; } static NTSTATUS append_afs_token(TALLOC_CTX *mem_ctx, struct winbindd_response *resp, const struct netr_SamInfo3 *info3, const char *name_domain, const char *name_user) { char *afsname = NULL; char *cell; char *token; afsname = talloc_strdup(mem_ctx, lp_afs_username_map()); if (afsname == NULL) { return NT_STATUS_NO_MEMORY; } afsname = talloc_string_sub(mem_ctx, lp_afs_username_map(), "%D", name_domain); afsname = talloc_string_sub(mem_ctx, afsname, "%u", name_user); afsname = talloc_string_sub(mem_ctx, afsname, "%U", name_user); { struct dom_sid user_sid; fstring sidstr; sid_compose(&user_sid, info3->base.domain_sid, info3->base.rid); sid_to_fstring(sidstr, &user_sid); afsname = talloc_string_sub(mem_ctx, afsname, "%s", sidstr); } if (afsname == NULL) { return NT_STATUS_NO_MEMORY; } if (!strlower_m(afsname)) { return NT_STATUS_INVALID_PARAMETER; } DEBUG(10, ("Generating token for user %s\n", afsname)); cell = strchr(afsname, '@'); if (cell == NULL) { return NT_STATUS_NO_MEMORY; } *cell = '\0'; cell += 1; token = afs_createtoken_str(afsname, cell); if (token == NULL) { return NT_STATUS_OK; } resp->extra_data.data = talloc_strdup(mem_ctx, token); if (resp->extra_data.data == NULL) { return NT_STATUS_NO_MEMORY; } resp->length += strlen((const char *)resp->extra_data.data)+1; return NT_STATUS_OK; } static NTSTATUS check_info3_in_group(struct netr_SamInfo3 *info3, const char *group_sid) /** * Check whether a user belongs to a group or list of groups. * * @param mem_ctx talloc memory context. * @param info3 user information, including group membership info. * @param group_sid One or more groups , separated by commas. * * @return NT_STATUS_OK on success, * NT_STATUS_LOGON_FAILURE if the user does not belong, * or other NT_STATUS_IS_ERR(status) for other kinds of failure. */ { struct dom_sid *require_membership_of_sid; uint32_t num_require_membership_of_sid; char *req_sid; const char *p; struct dom_sid sid; size_t i; struct security_token *token; TALLOC_CTX *frame = talloc_stackframe(); NTSTATUS status; /* Parse the 'required group' SID */ if (!group_sid || !group_sid[0]) { /* NO sid supplied, all users may access */ TALLOC_FREE(frame); return NT_STATUS_OK; } token = talloc_zero(talloc_tos(), struct security_token); if (token == NULL) { DEBUG(0, ("talloc failed\n")); TALLOC_FREE(frame); return NT_STATUS_NO_MEMORY; } num_require_membership_of_sid = 0; require_membership_of_sid = NULL; p = group_sid; while (next_token_talloc(talloc_tos(), &p, &req_sid, ",")) { if (!string_to_sid(&sid, req_sid)) { DEBUG(0, ("check_info3_in_group: could not parse %s " "as a SID!", req_sid)); TALLOC_FREE(frame); return NT_STATUS_INVALID_PARAMETER; } status = add_sid_to_array(talloc_tos(), &sid, &require_membership_of_sid, &num_require_membership_of_sid); if (!NT_STATUS_IS_OK(status)) { DEBUG(0, ("add_sid_to_array failed\n")); TALLOC_FREE(frame); return status; } } status = sid_array_from_info3(talloc_tos(), info3, &token->sids, &token->num_sids, true); if (!NT_STATUS_IS_OK(status)) { TALLOC_FREE(frame); return status; } if (!NT_STATUS_IS_OK(status = add_aliases(get_global_sam_sid(), token)) || !NT_STATUS_IS_OK(status = add_aliases(&global_sid_Builtin, token))) { DEBUG(3, ("could not add aliases: %s\n", nt_errstr(status))); TALLOC_FREE(frame); return status; } security_token_debug(DBGC_CLASS, 10, token); for (i=0; i<num_require_membership_of_sid; i++) { DEBUG(10, ("Checking SID %s\n", sid_string_dbg( &require_membership_of_sid[i]))); if (nt_token_check_sid(&require_membership_of_sid[i], token)) { DEBUG(10, ("Access ok\n")); TALLOC_FREE(frame); return NT_STATUS_OK; } } /* Do not distinguish this error from a wrong username/pw */ TALLOC_FREE(frame); return NT_STATUS_LOGON_FAILURE; } struct winbindd_domain *find_auth_domain(uint8_t flags, const char *domain_name) { struct winbindd_domain *domain; if (IS_DC) { domain = find_domain_from_name_noinit(domain_name); if (domain == NULL) { DEBUG(3, ("Authentication for domain [%s] refused " "as it is not a trusted domain\n", domain_name)); } return domain; } if (strequal(domain_name, get_global_sam_name())) { return find_domain_from_name_noinit(domain_name); } /* we can auth against trusted domains */ if (flags & WBFLAG_PAM_CONTACT_TRUSTDOM) { domain = find_domain_from_name_noinit(domain_name); if (domain == NULL) { DEBUG(3, ("Authentication for domain [%s] skipped " "as it is not a trusted domain\n", domain_name)); } else { return domain; } } return find_our_domain(); } static void fill_in_password_policy(struct winbindd_response *r, const struct samr_DomInfo1 *p) { r->data.auth.policy.min_length_password = p->min_password_length; r->data.auth.policy.password_history = p->password_history_length; r->data.auth.policy.password_properties = p->password_properties; r->data.auth.policy.expire = nt_time_to_unix_abs((const NTTIME *)&(p->max_password_age)); r->data.auth.policy.min_passwordage = nt_time_to_unix_abs((const NTTIME *)&(p->min_password_age)); } static NTSTATUS fillup_password_policy(struct winbindd_domain *domain, struct winbindd_response *response) { TALLOC_CTX *frame = talloc_stackframe(); struct winbindd_methods *methods; NTSTATUS status; struct samr_DomInfo1 password_policy; if ( !winbindd_can_contact_domain( domain ) ) { DEBUG(5,("fillup_password_policy: No inbound trust to " "contact domain %s\n", domain->name)); status = NT_STATUS_NOT_SUPPORTED; goto done; } methods = domain->methods; status = methods->password_policy(domain, talloc_tos(), &password_policy); if (NT_STATUS_IS_ERR(status)) { goto done; } fill_in_password_policy(response, &password_policy); done: TALLOC_FREE(frame); return NT_STATUS_OK; } static NTSTATUS get_max_bad_attempts_from_lockout_policy(struct winbindd_domain *domain, TALLOC_CTX *mem_ctx, uint16 *lockout_threshold) { struct winbindd_methods *methods; NTSTATUS status = NT_STATUS_UNSUCCESSFUL; struct samr_DomInfo12 lockout_policy; *lockout_threshold = 0; methods = domain->methods; status = methods->lockout_policy(domain, mem_ctx, &lockout_policy); if (NT_STATUS_IS_ERR(status)) { return status; } *lockout_threshold = lockout_policy.lockout_threshold; return NT_STATUS_OK; } static NTSTATUS get_pwd_properties(struct winbindd_domain *domain, TALLOC_CTX *mem_ctx, uint32 *password_properties) { struct winbindd_methods *methods; NTSTATUS status = NT_STATUS_UNSUCCESSFUL; struct samr_DomInfo1 password_policy; *password_properties = 0; methods = domain->methods; status = methods->password_policy(domain, mem_ctx, &password_policy); if (NT_STATUS_IS_ERR(status)) { return status; } *password_properties = password_policy.password_properties; return NT_STATUS_OK; } #ifdef HAVE_KRB5 static const char *generate_krb5_ccache(TALLOC_CTX *mem_ctx, const char *type, uid_t uid, const char **user_ccache_file) { /* accept FILE and WRFILE as krb5_cc_type from the client and then * build the full ccname string based on the user's uid here - * Guenther*/ const char *gen_cc = NULL; if (uid != -1) { if (strequal(type, "FILE")) { gen_cc = talloc_asprintf( mem_ctx, "FILE:/tmp/krb5cc_%d", uid); } if (strequal(type, "WRFILE")) { gen_cc = talloc_asprintf( mem_ctx, "WRFILE:/tmp/krb5cc_%d", uid); } if (strequal(type, "KEYRING")) { gen_cc = talloc_asprintf( mem_ctx, "KEYRING:persistent:%d", uid); } if (strnequal(type, "FILE:/", 6) || strnequal(type, "WRFILE:/", 8) || strnequal(type, "DIR:/", 5)) { /* we allow only one "%u" substitution */ char *p; p = strchr(type, '%'); if (p != NULL) { p++; if (p != NULL && *p == 'u' && strchr(p, '%') == NULL) { char uid_str[sizeof("18446744073709551615")]; snprintf(uid_str, sizeof(uid_str), "%u", uid); gen_cc = talloc_string_sub2(mem_ctx, type, "%u", uid_str, /* remove_unsafe_characters */ false, /* replace_once */ true, /* allow_trailing_dollar */ false); } } } } *user_ccache_file = gen_cc; if (gen_cc == NULL) { gen_cc = talloc_strdup(mem_ctx, "MEMORY:winbindd_pam_ccache"); } if (gen_cc == NULL) { DEBUG(0,("out of memory\n")); return NULL; } DEBUG(10, ("using ccache: %s%s\n", gen_cc, (*user_ccache_file == NULL) ? " (internal)":"")); return gen_cc; } #endif uid_t get_uid_from_request(struct winbindd_request *request) { uid_t uid; uid = request->data.auth.uid; if (uid < 0) { DEBUG(1,("invalid uid: '%u'\n", (unsigned int)uid)); return -1; } return uid; } /********************************************************************** Authenticate a user with a clear text password using Kerberos and fill up ccache if required **********************************************************************/ static NTSTATUS winbindd_raw_kerberos_login(TALLOC_CTX *mem_ctx, struct winbindd_domain *domain, const char *user, const char *pass, const char *krb5_cc_type, uid_t uid, struct netr_SamInfo3 **info3, fstring krb5ccname) { #ifdef HAVE_KRB5 NTSTATUS result = NT_STATUS_UNSUCCESSFUL; krb5_error_code krb5_ret; const char *cc = NULL; const char *principal_s = NULL; const char *service = NULL; char *realm = NULL; fstring name_domain, name_user; time_t ticket_lifetime = 0; time_t renewal_until = 0; ADS_STRUCT *ads; time_t time_offset = 0; const char *user_ccache_file; struct PAC_LOGON_INFO *logon_info = NULL; struct PAC_DATA *pac_data = NULL; struct PAC_DATA_CTR *pac_data_ctr = NULL; const char *local_service; int i; *info3 = NULL; if (domain->alt_name == NULL) { return NT_STATUS_INVALID_PARAMETER; } /* 1st step: * prepare a krb5_cc_cache string for the user */ if (uid == -1) { DEBUG(0,("no valid uid\n")); } cc = generate_krb5_ccache(mem_ctx, krb5_cc_type, uid, &user_ccache_file); if (cc == NULL) { return NT_STATUS_NO_MEMORY; } /* 2nd step: * get kerberos properties */ if (domain->private_data) { ads = (ADS_STRUCT *)domain->private_data; time_offset = ads->auth.time_offset; } /* 3rd step: * do kerberos auth and setup ccache as the user */ parse_domain_user(user, name_domain, name_user); realm = talloc_strdup(mem_ctx, domain->alt_name); if (realm == NULL) { return NT_STATUS_NO_MEMORY; } if (!strupper_m(realm)) { return NT_STATUS_INVALID_PARAMETER; } principal_s = talloc_asprintf(mem_ctx, "%s@%s", name_user, realm); if (principal_s == NULL) { return NT_STATUS_NO_MEMORY; } service = talloc_asprintf(mem_ctx, "%s/%s@%s", KRB5_TGS_NAME, realm, realm); if (service == NULL) { return NT_STATUS_NO_MEMORY; } local_service = talloc_asprintf(mem_ctx, "%s$@%s", lp_netbios_name(), lp_realm()); if (local_service == NULL) { return NT_STATUS_NO_MEMORY; } /* if this is a user ccache, we need to act as the user to let the krb5 * library handle the chown, etc. */ /************************ ENTERING NON-ROOT **********************/ if (user_ccache_file != NULL) { set_effective_uid(uid); DEBUG(10,("winbindd_raw_kerberos_login: uid is %d\n", uid)); } result = kerberos_return_pac(mem_ctx, principal_s, pass, time_offset, &ticket_lifetime, &renewal_until, cc, true, true, WINBINDD_PAM_AUTH_KRB5_RENEW_TIME, NULL, local_service, &pac_data_ctr); if (user_ccache_file != NULL) { gain_root_privilege(); } /************************ RETURNED TO ROOT **********************/ if (!NT_STATUS_IS_OK(result)) { goto failed; } if (pac_data_ctr == NULL) { goto failed; } pac_data = pac_data_ctr->pac_data; if (pac_data == NULL) { goto failed; } for (i=0; i < pac_data->num_buffers; i++) { if (pac_data->buffers[i].type != PAC_TYPE_LOGON_INFO) { continue; } logon_info = pac_data->buffers[i].info->logon_info.info; if (!logon_info) { return NT_STATUS_INVALID_PARAMETER; } break; } *info3 = &logon_info->info3; DEBUG(10,("winbindd_raw_kerberos_login: winbindd validated ticket of %s\n", principal_s)); /* if we had a user's ccache then return that string for the pam * environment */ if (user_ccache_file != NULL) { fstrcpy(krb5ccname, user_ccache_file); result = add_ccache_to_list(principal_s, cc, service, user, pass, realm, uid, time(NULL), ticket_lifetime, renewal_until, false); if (!NT_STATUS_IS_OK(result)) { DEBUG(10,("winbindd_raw_kerberos_login: failed to add ccache to list: %s\n", nt_errstr(result))); } } else { /* need to delete the memory cred cache, it is not used anymore */ krb5_ret = ads_kdestroy(cc); if (krb5_ret) { DEBUG(3,("winbindd_raw_kerberos_login: " "could not destroy krb5 credential cache: " "%s\n", error_message(krb5_ret))); } } return NT_STATUS_OK; failed: /* * Do not delete an existing valid credential cache, if the user * e.g. enters a wrong password */ if ((strequal(krb5_cc_type, "FILE") || strequal(krb5_cc_type, "WRFILE")) && user_ccache_file != NULL) { return result; } /* we could have created a new credential cache with a valid tgt in it * but we werent able to get or verify the service ticket for this * local host and therefor didn't get the PAC, we need to remove that * cache entirely now */ krb5_ret = ads_kdestroy(cc); if (krb5_ret) { DEBUG(3,("winbindd_raw_kerberos_login: " "could not destroy krb5 credential cache: " "%s\n", error_message(krb5_ret))); } if (!NT_STATUS_IS_OK(remove_ccache(user))) { DEBUG(3,("winbindd_raw_kerberos_login: " "could not remove ccache for user %s\n", user)); } return result; #else return NT_STATUS_NOT_SUPPORTED; #endif /* HAVE_KRB5 */ } /**************************************************************** ****************************************************************/ bool check_request_flags(uint32_t flags) { uint32_t flags_edata = WBFLAG_PAM_AFS_TOKEN | WBFLAG_PAM_INFO3_TEXT | WBFLAG_PAM_INFO3_NDR; if ( ( (flags & flags_edata) == WBFLAG_PAM_AFS_TOKEN) || ( (flags & flags_edata) == WBFLAG_PAM_INFO3_NDR) || ( (flags & flags_edata) == WBFLAG_PAM_INFO3_TEXT)|| !(flags & flags_edata) ) { return true; } DEBUG(1, ("check_request_flags: invalid request flags[0x%08X]\n", flags)); return false; } /**************************************************************** ****************************************************************/ NTSTATUS append_auth_data(TALLOC_CTX *mem_ctx, struct winbindd_response *resp, uint32_t request_flags, struct netr_SamInfo3 *info3, const char *name_domain, const char *name_user) { NTSTATUS result; if (request_flags & WBFLAG_PAM_USER_SESSION_KEY) { memcpy(resp->data.auth.user_session_key, info3->base.key.key, sizeof(resp->data.auth.user_session_key) /* 16 */); } if (request_flags & WBFLAG_PAM_LMKEY) { memcpy(resp->data.auth.first_8_lm_hash, info3->base.LMSessKey.key, sizeof(resp->data.auth.first_8_lm_hash) /* 8 */); } if (request_flags & WBFLAG_PAM_UNIX_NAME) { result = append_unix_username(mem_ctx, resp, info3, name_domain, name_user); if (!NT_STATUS_IS_OK(result)) { DEBUG(10,("Failed to append Unix Username: %s\n", nt_errstr(result))); return result; } } /* currently, anything from here on potentially overwrites extra_data. */ if (request_flags & WBFLAG_PAM_INFO3_NDR) { result = append_info3_as_ndr(mem_ctx, resp, info3); if (!NT_STATUS_IS_OK(result)) { DEBUG(10,("Failed to append INFO3 (NDR): %s\n", nt_errstr(result))); return result; } } if (request_flags & WBFLAG_PAM_INFO3_TEXT) { result = append_info3_as_txt(mem_ctx, resp, info3); if (!NT_STATUS_IS_OK(result)) { DEBUG(10,("Failed to append INFO3 (TXT): %s\n", nt_errstr(result))); return result; } } if (request_flags & WBFLAG_PAM_AFS_TOKEN) { result = append_afs_token(mem_ctx, resp, info3, name_domain, name_user); if (!NT_STATUS_IS_OK(result)) { DEBUG(10,("Failed to append AFS token: %s\n", nt_errstr(result))); return result; } } return NT_STATUS_OK; } static NTSTATUS winbindd_dual_pam_auth_cached(struct winbindd_domain *domain, struct winbindd_cli_state *state, struct netr_SamInfo3 **info3) { NTSTATUS result = NT_STATUS_LOGON_FAILURE; uint16 max_allowed_bad_attempts; fstring name_domain, name_user; struct dom_sid sid; enum lsa_SidType type; uchar new_nt_pass[NT_HASH_LEN]; const uint8 *cached_nt_pass; const uint8 *cached_salt; struct netr_SamInfo3 *my_info3; time_t kickoff_time, must_change_time; bool password_good = false; #ifdef HAVE_KRB5 struct winbindd_tdc_domain *tdc_domain = NULL; #endif *info3 = NULL; ZERO_STRUCTP(info3); DEBUG(10,("winbindd_dual_pam_auth_cached\n")); /* Parse domain and username */ parse_domain_user(state->request->data.auth.user, name_domain, name_user); if (!lookup_cached_name(name_domain, name_user, &sid, &type)) { DEBUG(10,("winbindd_dual_pam_auth_cached: no such user in the cache\n")); return NT_STATUS_NO_SUCH_USER; } if (type != SID_NAME_USER) { DEBUG(10,("winbindd_dual_pam_auth_cached: not a user (%s)\n", sid_type_lookup(type))); return NT_STATUS_LOGON_FAILURE; } result = winbindd_get_creds(domain, state->mem_ctx, &sid, &my_info3, &cached_nt_pass, &cached_salt); if (!NT_STATUS_IS_OK(result)) { DEBUG(10,("winbindd_dual_pam_auth_cached: failed to get creds: %s\n", nt_errstr(result))); return result; } *info3 = my_info3; E_md4hash(state->request->data.auth.pass, new_nt_pass); dump_data_pw("new_nt_pass", new_nt_pass, NT_HASH_LEN); dump_data_pw("cached_nt_pass", cached_nt_pass, NT_HASH_LEN); if (cached_salt) { dump_data_pw("cached_salt", cached_salt, NT_HASH_LEN); } if (cached_salt) { /* In this case we didn't store the nt_hash itself, but the MD5 combination of salt + nt_hash. */ uchar salted_hash[NT_HASH_LEN]; E_md5hash(cached_salt, new_nt_pass, salted_hash); password_good = (memcmp(cached_nt_pass, salted_hash, NT_HASH_LEN) == 0); } else { /* Old cached cred - direct store of nt_hash (bad bad bad !). */ password_good = (memcmp(cached_nt_pass, new_nt_pass, NT_HASH_LEN) == 0); } if (password_good) { /* User *DOES* know the password, update logon_time and reset * bad_pw_count */ my_info3->base.user_flags |= NETLOGON_CACHED_ACCOUNT; if (my_info3->base.acct_flags & ACB_AUTOLOCK) { return NT_STATUS_ACCOUNT_LOCKED_OUT; } if (my_info3->base.acct_flags & ACB_DISABLED) { return NT_STATUS_ACCOUNT_DISABLED; } if (my_info3->base.acct_flags & ACB_WSTRUST) { return NT_STATUS_NOLOGON_WORKSTATION_TRUST_ACCOUNT; } if (my_info3->base.acct_flags & ACB_SVRTRUST) { return NT_STATUS_NOLOGON_SERVER_TRUST_ACCOUNT; } if (my_info3->base.acct_flags & ACB_DOMTRUST) { return NT_STATUS_NOLOGON_INTERDOMAIN_TRUST_ACCOUNT; } if (!(my_info3->base.acct_flags & ACB_NORMAL)) { DEBUG(0,("winbindd_dual_pam_auth_cached: whats wrong with that one?: 0x%08x\n", my_info3->base.acct_flags)); return NT_STATUS_LOGON_FAILURE; } kickoff_time = nt_time_to_unix(my_info3->base.kickoff_time); if (kickoff_time != 0 && time(NULL) > kickoff_time) { return NT_STATUS_ACCOUNT_EXPIRED; } must_change_time = nt_time_to_unix(my_info3->base.force_password_change); if (must_change_time != 0 && must_change_time < time(NULL)) { /* we allow grace logons when the password has expired */ my_info3->base.user_flags |= NETLOGON_GRACE_LOGON; /* return NT_STATUS_PASSWORD_EXPIRED; */ goto success; } #ifdef HAVE_KRB5 if ((state->request->flags & WBFLAG_PAM_KRB5) && ((tdc_domain = wcache_tdc_fetch_domain(state->mem_ctx, name_domain)) != NULL) && ((tdc_domain->trust_type & LSA_TRUST_TYPE_UPLEVEL) || /* used to cope with the case winbindd starting without network. */ !strequal(tdc_domain->domain_name, tdc_domain->dns_name))) { uid_t uid = -1; const char *cc = NULL; char *realm = NULL; const char *principal_s = NULL; const char *service = NULL; const char *user_ccache_file; if (domain->alt_name == NULL) { return NT_STATUS_INVALID_PARAMETER; } uid = get_uid_from_request(state->request); if (uid == -1) { DEBUG(0,("winbindd_dual_pam_auth_cached: invalid uid\n")); return NT_STATUS_INVALID_PARAMETER; } cc = generate_krb5_ccache(state->mem_ctx, state->request->data.auth.krb5_cc_type, state->request->data.auth.uid, &user_ccache_file); if (cc == NULL) { return NT_STATUS_NO_MEMORY; } realm = talloc_strdup(state->mem_ctx, domain->alt_name); if (realm == NULL) { return NT_STATUS_NO_MEMORY; } if (!strupper_m(realm)) { return NT_STATUS_INVALID_PARAMETER; } principal_s = talloc_asprintf(state->mem_ctx, "%s@%s", name_user, realm); if (principal_s == NULL) { return NT_STATUS_NO_MEMORY; } service = talloc_asprintf(state->mem_ctx, "%s/%s@%s", KRB5_TGS_NAME, realm, realm); if (service == NULL) { return NT_STATUS_NO_MEMORY; } if (user_ccache_file != NULL) { fstrcpy(state->response->data.auth.krb5ccname, user_ccache_file); result = add_ccache_to_list(principal_s, cc, service, state->request->data.auth.user, state->request->data.auth.pass, realm, uid, time(NULL), time(NULL) + lp_winbind_cache_time(), time(NULL) + WINBINDD_PAM_AUTH_KRB5_RENEW_TIME, true); if (!NT_STATUS_IS_OK(result)) { DEBUG(10,("winbindd_dual_pam_auth_cached: failed " "to add ccache to list: %s\n", nt_errstr(result))); } } } #endif /* HAVE_KRB5 */ success: /* FIXME: we possibly should handle logon hours as well (does xp when * offline?) see auth/auth_sam.c:sam_account_ok for details */ unix_to_nt_time(&my_info3->base.logon_time, time(NULL)); my_info3->base.bad_password_count = 0; result = winbindd_update_creds_by_info3(domain, state->request->data.auth.user, state->request->data.auth.pass, my_info3); if (!NT_STATUS_IS_OK(result)) { DEBUG(1,("winbindd_dual_pam_auth_cached: failed to update creds: %s\n", nt_errstr(result))); return result; } return NT_STATUS_OK; } /* User does *NOT* know the correct password, modify info3 accordingly, but only if online */ if (domain->online == false) { goto failed; } /* failure of this is not critical */ result = get_max_bad_attempts_from_lockout_policy(domain, state->mem_ctx, &max_allowed_bad_attempts); if (!NT_STATUS_IS_OK(result)) { DEBUG(10,("winbindd_dual_pam_auth_cached: failed to get max_allowed_bad_attempts. " "Won't be able to honour account lockout policies\n")); } /* increase counter */ my_info3->base.bad_password_count++; if (max_allowed_bad_attempts == 0) { goto failed; } /* lockout user */ if (my_info3->base.bad_password_count >= max_allowed_bad_attempts) { uint32 password_properties; result = get_pwd_properties(domain, state->mem_ctx, &password_properties); if (!NT_STATUS_IS_OK(result)) { DEBUG(10,("winbindd_dual_pam_auth_cached: failed to get password properties.\n")); } if ((my_info3->base.rid != DOMAIN_RID_ADMINISTRATOR) || (password_properties & DOMAIN_PASSWORD_LOCKOUT_ADMINS)) { my_info3->base.acct_flags |= ACB_AUTOLOCK; } } failed: result = winbindd_update_creds_by_info3(domain, state->request->data.auth.user, NULL, my_info3); if (!NT_STATUS_IS_OK(result)) { DEBUG(0,("winbindd_dual_pam_auth_cached: failed to update creds %s\n", nt_errstr(result))); } return NT_STATUS_LOGON_FAILURE; } static NTSTATUS winbindd_dual_pam_auth_kerberos(struct winbindd_domain *domain, struct winbindd_cli_state *state, struct netr_SamInfo3 **info3) { struct winbindd_domain *contact_domain; fstring name_domain, name_user; NTSTATUS result; DEBUG(10,("winbindd_dual_pam_auth_kerberos\n")); /* Parse domain and username */ parse_domain_user(state->request->data.auth.user, name_domain, name_user); /* what domain should we contact? */ if ( IS_DC ) { if (!(contact_domain = find_domain_from_name(name_domain))) { DEBUG(3, ("Authentication for domain for [%s] -> [%s]\\[%s] failed as %s is not a trusted domain\n", state->request->data.auth.user, name_domain, name_user, name_domain)); result = NT_STATUS_NO_SUCH_USER; goto done; } } else { if (is_myname(name_domain)) { DEBUG(3, ("Authentication for domain %s (local domain to this server) not supported at this stage\n", name_domain)); result = NT_STATUS_NO_SUCH_USER; goto done; } contact_domain = find_domain_from_name(name_domain); if (contact_domain == NULL) { DEBUG(3, ("Authentication for domain for [%s] -> [%s]\\[%s] failed as %s is not a trusted domain\n", state->request->data.auth.user, name_domain, name_user, name_domain)); result = NT_STATUS_NO_SUCH_USER; goto done; } } if (contact_domain->initialized && contact_domain->active_directory) { goto try_login; } if (!contact_domain->initialized) { init_dc_connection(contact_domain, false); } if (!contact_domain->active_directory) { DEBUG(3,("krb5 auth requested but domain is not Active Directory\n")); return NT_STATUS_INVALID_LOGON_TYPE; } try_login: result = winbindd_raw_kerberos_login( state->mem_ctx, contact_domain, state->request->data.auth.user, state->request->data.auth.pass, state->request->data.auth.krb5_cc_type, get_uid_from_request(state->request), info3, state->response->data.auth.krb5ccname); done: return result; } static NTSTATUS winbindd_dual_auth_passdb(TALLOC_CTX *mem_ctx, uint32_t logon_parameters, const char *domain, const char *user, const DATA_BLOB *challenge, const DATA_BLOB *lm_resp, const DATA_BLOB *nt_resp, struct netr_SamInfo3 **pinfo3) { struct auth_context *auth_context; struct auth_serversupplied_info *server_info; struct auth_usersupplied_info *user_info = NULL; struct tsocket_address *local; struct netr_SamInfo3 *info3; NTSTATUS status; int rc; TALLOC_CTX *frame = talloc_stackframe(); rc = tsocket_address_inet_from_strings(frame, "ip", "127.0.0.1", 0, &local); if (rc < 0) { TALLOC_FREE(frame); return NT_STATUS_NO_MEMORY; } status = make_user_info(frame, &user_info, user, user, domain, domain, lp_netbios_name(), local, lm_resp, nt_resp, NULL, NULL, NULL, AUTH_PASSWORD_RESPONSE); if (!NT_STATUS_IS_OK(status)) { DEBUG(10, ("make_user_info failed: %s\n", nt_errstr(status))); TALLOC_FREE(frame); return status; } user_info->logon_parameters = logon_parameters; /* We don't want any more mapping of the username */ user_info->mapped_state = True; /* We don't want to come back to winbindd or to do PAM account checks */ user_info->flags |= USER_INFO_LOCAL_SAM_ONLY | USER_INFO_INFO3_AND_NO_AUTHZ; status = make_auth_context_fixed(frame, &auth_context, challenge->data); if (!NT_STATUS_IS_OK(status)) { DEBUG(0, ("Failed to test authentication with check_sam_security_info3: %s\n", nt_errstr(status))); TALLOC_FREE(frame); return status; } status = auth_check_ntlm_password(mem_ctx, auth_context, user_info, &server_info); if (!NT_STATUS_IS_OK(status)) { TALLOC_FREE(frame); return status; } info3 = talloc_zero(mem_ctx, struct netr_SamInfo3); if (info3 == NULL) { TALLOC_FREE(frame); return NT_STATUS_NO_MEMORY; } status = serverinfo_to_SamInfo3(server_info, info3); if (!NT_STATUS_IS_OK(status)) { TALLOC_FREE(frame); TALLOC_FREE(info3); DEBUG(0, ("serverinfo_to_SamInfo3 failed: %s\n", nt_errstr(status))); return status; } *pinfo3 = info3; DEBUG(10, ("Authenticaticating user %s\\%s returned %s\n", domain, user, nt_errstr(status))); TALLOC_FREE(frame); return status; } static NTSTATUS winbind_samlogon_retry_loop(struct winbindd_domain *domain, TALLOC_CTX *mem_ctx, uint32_t logon_parameters, const char *server, const char *username, const char *password, const char *domainname, const char *workstation, const uint8_t chal[8], DATA_BLOB lm_response, DATA_BLOB nt_response, bool interactive, struct netr_SamInfo3 **info3) { int attempts = 0; int netr_attempts = 0; bool retry = false; NTSTATUS result; do { struct rpc_pipe_client *netlogon_pipe; uint8_t authoritative = 0; uint32_t flags = 0; ZERO_STRUCTP(info3); retry = false; result = cm_connect_netlogon(domain, &netlogon_pipe); if (!NT_STATUS_IS_OK(result)) { DEBUG(3,("Could not open handle to NETLOGON pipe " "(error: %s, attempts: %d)\n", nt_errstr(result), netr_attempts)); /* After the first retry always close the connection */ if (netr_attempts > 0) { DEBUG(3, ("This is again a problem for this " "particular call, forcing the close " "of this connection\n")); invalidate_cm_connection(domain); } /* After the second retry failover to the next DC */ if (netr_attempts > 1) { /* * If the netlogon server is not reachable then * it is possible that the DC is rebuilding * sysvol and shutdown netlogon for that time. * We should failover to the next dc. */ DEBUG(3, ("This is the third problem for this " "particular call, adding DC to the " "negative cache list\n")); add_failed_connection_entry(domain->name, domain->dcname, result); saf_delete(domain->name); } /* Only allow 3 retries */ if (netr_attempts < 3) { DEBUG(3, ("The connection to netlogon " "failed, retrying\n")); netr_attempts++; retry = true; continue; } return result; } netr_attempts = 0; if (interactive && username != NULL && password != NULL) { result = rpccli_netlogon_password_logon(domain->conn.netlogon_creds, netlogon_pipe->binding_handle, mem_ctx, logon_parameters, domainname, username, password, workstation, NetlogonInteractiveInformation, info3); } else { result = rpccli_netlogon_network_logon(domain->conn.netlogon_creds, netlogon_pipe->binding_handle, mem_ctx, logon_parameters, username, domainname, workstation, chal, lm_response, nt_response, &authoritative, &flags, info3); } /* * we increment this after the "feature negotiation" * for can_do_samlogon_ex and can_do_validation6 */ attempts += 1; /* We have to try a second time as cm_connect_netlogon might not yet have noticed that the DC has killed our connection. */ if (!rpccli_is_connected(netlogon_pipe)) { retry = true; continue; } /* if we get access denied, a possible cause was that we had and open connection to the DC, but someone changed our machine account password out from underneath us using 'net rpc changetrustpw' */ if ( NT_STATUS_EQUAL(result, NT_STATUS_ACCESS_DENIED) ) { DEBUG(3,("winbind_samlogon_retry_loop: sam_logon returned " "ACCESS_DENIED. Maybe the trust account " "password was changed and we didn't know it. " "Killing connections to domain %s\n", domainname)); invalidate_cm_connection(domain); retry = true; } if (NT_STATUS_EQUAL(result, NT_STATUS_RPC_PROCNUM_OUT_OF_RANGE)) { /* * Got DCERPC_FAULT_OP_RNG_ERROR for SamLogon * (no Ex). This happens against old Samba * DCs, if LogonSamLogonEx() fails with an error * e.g. NT_STATUS_NO_SUCH_USER or NT_STATUS_WRONG_PASSWORD. * * The server will log something like this: * api_net_sam_logon_ex: Failed to marshall NET_R_SAM_LOGON_EX. * * This sets the whole connection into a fault_state mode * and all following request get NT_STATUS_RPC_PROCNUM_OUT_OF_RANGE. * * This also happens to our retry with LogonSamLogonWithFlags() * and LogonSamLogon(). * * In order to recover from this situation, we need to * drop the connection. */ invalidate_cm_connection(domain); result = NT_STATUS_LOGON_FAILURE; break; } } while ( (attempts < 2) && retry ); if (NT_STATUS_EQUAL(result, NT_STATUS_IO_TIMEOUT)) { DEBUG(3,("winbind_samlogon_retry_loop: sam_network_logon(ex) " "returned NT_STATUS_IO_TIMEOUT after the retry." "Killing connections to domain %s\n", domainname)); invalidate_cm_connection(domain); } return result; } static NTSTATUS winbindd_dual_pam_auth_samlogon(TALLOC_CTX *mem_ctx, struct winbindd_domain *domain, const char *user, const char *pass, uint32_t request_flags, struct netr_SamInfo3 **info3) { uchar chal[8]; DATA_BLOB lm_resp; DATA_BLOB nt_resp; unsigned char local_nt_response[24]; fstring name_domain, name_user; NTSTATUS result; struct netr_SamInfo3 *my_info3 = NULL; *info3 = NULL; DEBUG(10,("winbindd_dual_pam_auth_samlogon\n")); /* Parse domain and username */ parse_domain_user(user, name_domain, name_user); /* do password magic */ generate_random_buffer(chal, sizeof(chal)); if (lp_client_ntlmv2_auth()) { DATA_BLOB server_chal; DATA_BLOB names_blob; server_chal = data_blob_const(chal, 8); /* note that the 'workgroup' here is for the local machine. The 'server name' must match the 'workstation' passed to the actual SamLogon call. */ names_blob = NTLMv2_generate_names_blob( mem_ctx, lp_netbios_name(), lp_workgroup()); if (!SMBNTLMv2encrypt(mem_ctx, name_user, name_domain, pass, &server_chal, &names_blob, &lm_resp, &nt_resp, NULL, NULL)) { data_blob_free(&names_blob); DEBUG(0, ("winbindd_pam_auth: SMBNTLMv2encrypt() failed!\n")); result = NT_STATUS_NO_MEMORY; goto done; } data_blob_free(&names_blob); } else { lm_resp = data_blob_null; SMBNTencrypt(pass, chal, local_nt_response); nt_resp = data_blob_talloc(mem_ctx, local_nt_response, sizeof(local_nt_response)); } if (strequal(name_domain, get_global_sam_name())) { DATA_BLOB chal_blob = data_blob_const(chal, sizeof(chal)); result = winbindd_dual_auth_passdb( mem_ctx, 0, name_domain, name_user, &chal_blob, &lm_resp, &nt_resp, info3); /* * We need to try the remote NETLOGON server if this is NOT_IMPLEMENTED */ if (!NT_STATUS_EQUAL(result, NT_STATUS_NOT_IMPLEMENTED)) { goto done; } } /* check authentication loop */ result = winbind_samlogon_retry_loop(domain, mem_ctx, 0, domain->dcname, name_user, pass, name_domain, lp_netbios_name(), chal, lm_resp, nt_resp, true, /* interactive */ &my_info3); if (!NT_STATUS_IS_OK(result)) { goto done; } /* handle the case where a NT4 DC does not fill in the acct_flags in * the samlogon reply info3. When accurate info3 is required by the * caller, we look up the account flags ourselve - gd */ if ((request_flags & WBFLAG_PAM_INFO3_TEXT) && NT_STATUS_IS_OK(result) && (my_info3->base.acct_flags == 0)) { struct rpc_pipe_client *samr_pipe; struct policy_handle samr_domain_handle, user_pol; union samr_UserInfo *info = NULL; NTSTATUS status_tmp, result_tmp; uint32 acct_flags; struct dcerpc_binding_handle *b; status_tmp = cm_connect_sam(domain, mem_ctx, false, &samr_pipe, &samr_domain_handle); if (!NT_STATUS_IS_OK(status_tmp)) { DEBUG(3, ("could not open handle to SAMR pipe: %s\n", nt_errstr(status_tmp))); goto done; } b = samr_pipe->binding_handle; status_tmp = dcerpc_samr_OpenUser(b, mem_ctx, &samr_domain_handle, MAXIMUM_ALLOWED_ACCESS, my_info3->base.rid, &user_pol, &result_tmp); if (!NT_STATUS_IS_OK(status_tmp)) { DEBUG(3, ("could not open user handle on SAMR pipe: %s\n", nt_errstr(status_tmp))); goto done; } if (!NT_STATUS_IS_OK(result_tmp)) { DEBUG(3, ("could not open user handle on SAMR pipe: %s\n", nt_errstr(result_tmp))); goto done; } status_tmp = dcerpc_samr_QueryUserInfo(b, mem_ctx, &user_pol, 16, &info, &result_tmp); if (!NT_STATUS_IS_OK(status_tmp)) { DEBUG(3, ("could not query user info on SAMR pipe: %s\n", nt_errstr(status_tmp))); dcerpc_samr_Close(b, mem_ctx, &user_pol, &result_tmp); goto done; } if (!NT_STATUS_IS_OK(result_tmp)) { DEBUG(3, ("could not query user info on SAMR pipe: %s\n", nt_errstr(result_tmp))); dcerpc_samr_Close(b, mem_ctx, &user_pol, &result_tmp); goto done; } acct_flags = info->info16.acct_flags; if (acct_flags == 0) { dcerpc_samr_Close(b, mem_ctx, &user_pol, &result_tmp); goto done; } my_info3->base.acct_flags = acct_flags; DEBUG(10,("successfully retrieved acct_flags 0x%x\n", acct_flags)); dcerpc_samr_Close(b, mem_ctx, &user_pol, &result_tmp); } *info3 = my_info3; done: return result; } enum winbindd_result winbindd_dual_pam_auth(struct winbindd_domain *domain, struct winbindd_cli_state *state) { NTSTATUS result = NT_STATUS_LOGON_FAILURE; NTSTATUS krb5_result = NT_STATUS_OK; fstring name_domain, name_user; char *mapped_user; fstring domain_user; struct netr_SamInfo3 *info3 = NULL; NTSTATUS name_map_status = NT_STATUS_UNSUCCESSFUL; /* Ensure null termination */ state->request->data.auth.user[sizeof(state->request->data.auth.user)-1]='\0'; /* Ensure null termination */ state->request->data.auth.pass[sizeof(state->request->data.auth.pass)-1]='\0'; DEBUG(3, ("[%5lu]: dual pam auth %s\n", (unsigned long)state->pid, state->request->data.auth.user)); /* Parse domain and username */ name_map_status = normalize_name_unmap(state->mem_ctx, state->request->data.auth.user, &mapped_user); /* If the name normalization didnt' actually do anything, just use the original name */ if (!NT_STATUS_IS_OK(name_map_status) && !NT_STATUS_EQUAL(name_map_status, NT_STATUS_FILE_RENAMED)) { mapped_user = state->request->data.auth.user; } parse_domain_user(mapped_user, name_domain, name_user); if ( mapped_user != state->request->data.auth.user ) { fstr_sprintf( domain_user, "%s%c%s", name_domain, *lp_winbind_separator(), name_user ); strlcpy( state->request->data.auth.user, domain_user, sizeof(state->request->data.auth.user)); } if (!domain->online) { result = NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND; if (domain->startup) { /* Logons are very important to users. If we're offline and we get a request within the first 30 seconds of startup, try very hard to find a DC and go online. */ DEBUG(10,("winbindd_dual_pam_auth: domain: %s offline and auth " "request in startup mode.\n", domain->name )); winbindd_flush_negative_conn_cache(domain); result = init_dc_connection(domain, false); } } DEBUG(10,("winbindd_dual_pam_auth: domain: %s last was %s\n", domain->name, domain->online ? "online":"offline")); /* Check for Kerberos authentication */ if (domain->online && (state->request->flags & WBFLAG_PAM_KRB5)) { result = winbindd_dual_pam_auth_kerberos(domain, state, &info3); /* save for later */ krb5_result = result; if (NT_STATUS_IS_OK(result)) { DEBUG(10,("winbindd_dual_pam_auth_kerberos succeeded\n")); goto process_result; } else { DEBUG(10,("winbindd_dual_pam_auth_kerberos failed: %s\n", nt_errstr(result))); } if (NT_STATUS_EQUAL(result, NT_STATUS_NO_LOGON_SERVERS) || NT_STATUS_EQUAL(result, NT_STATUS_IO_TIMEOUT) || NT_STATUS_EQUAL(result, NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND)) { DEBUG(10,("winbindd_dual_pam_auth_kerberos setting domain to offline\n")); set_domain_offline( domain ); goto cached_logon; } /* there are quite some NT_STATUS errors where there is no * point in retrying with a samlogon, we explictly have to take * care not to increase the bad logon counter on the DC */ if (NT_STATUS_EQUAL(result, NT_STATUS_ACCOUNT_DISABLED) || NT_STATUS_EQUAL(result, NT_STATUS_ACCOUNT_EXPIRED) || NT_STATUS_EQUAL(result, NT_STATUS_ACCOUNT_LOCKED_OUT) || NT_STATUS_EQUAL(result, NT_STATUS_INVALID_LOGON_HOURS) || NT_STATUS_EQUAL(result, NT_STATUS_INVALID_WORKSTATION) || NT_STATUS_EQUAL(result, NT_STATUS_LOGON_FAILURE) || NT_STATUS_EQUAL(result, NT_STATUS_NO_SUCH_USER) || NT_STATUS_EQUAL(result, NT_STATUS_PASSWORD_EXPIRED) || NT_STATUS_EQUAL(result, NT_STATUS_PASSWORD_MUST_CHANGE) || NT_STATUS_EQUAL(result, NT_STATUS_WRONG_PASSWORD)) { goto done; } if (state->request->flags & WBFLAG_PAM_FALLBACK_AFTER_KRB5) { DEBUG(3,("falling back to samlogon\n")); goto sam_logon; } else { goto cached_logon; } } sam_logon: /* Check for Samlogon authentication */ if (domain->online) { result = winbindd_dual_pam_auth_samlogon( state->mem_ctx, domain, state->request->data.auth.user, state->request->data.auth.pass, state->request->flags, &info3); if (NT_STATUS_IS_OK(result)) { DEBUG(10,("winbindd_dual_pam_auth_samlogon succeeded\n")); /* add the Krb5 err if we have one */ if ( NT_STATUS_EQUAL(krb5_result, NT_STATUS_TIME_DIFFERENCE_AT_DC ) ) { info3->base.user_flags |= LOGON_KRB5_FAIL_CLOCK_SKEW; } goto process_result; } DEBUG(10,("winbindd_dual_pam_auth_samlogon failed: %s\n", nt_errstr(result))); if (NT_STATUS_EQUAL(result, NT_STATUS_NO_LOGON_SERVERS) || NT_STATUS_EQUAL(result, NT_STATUS_IO_TIMEOUT) || NT_STATUS_EQUAL(result, NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND)) { DEBUG(10,("winbindd_dual_pam_auth_samlogon setting domain to offline\n")); set_domain_offline( domain ); goto cached_logon; } if (domain->online) { /* We're still online - fail. */ goto done; } } cached_logon: /* Check for Cached logons */ if (!domain->online && (state->request->flags & WBFLAG_PAM_CACHED_LOGIN) && lp_winbind_offline_logon()) { result = winbindd_dual_pam_auth_cached(domain, state, &info3); if (NT_STATUS_IS_OK(result)) { DEBUG(10,("winbindd_dual_pam_auth_cached succeeded\n")); goto process_result; } else { DEBUG(10,("winbindd_dual_pam_auth_cached failed: %s\n", nt_errstr(result))); goto done; } } process_result: if (NT_STATUS_IS_OK(result)) { struct dom_sid user_sid; /* In all codepaths where result == NT_STATUS_OK info3 must have been initialized. */ if (!info3) { result = NT_STATUS_INTERNAL_ERROR; goto done; } sid_compose(&user_sid, info3->base.domain_sid, info3->base.rid); if (info3->base.full_name.string == NULL) { struct netr_SamInfo3 *cached_info3; cached_info3 = netsamlogon_cache_get(state->mem_ctx, &user_sid); if (cached_info3 != NULL && cached_info3->base.full_name.string != NULL) { info3->base.full_name.string = talloc_strdup(info3, cached_info3->base.full_name.string); } else { /* this might fail so we dont check the return code */ wcache_query_user_fullname(domain, info3, &user_sid, &info3->base.full_name.string); } } wcache_invalidate_samlogon(find_domain_from_name(name_domain), &user_sid); netsamlogon_cache_store(name_user, info3); /* save name_to_sid info as early as possible (only if this is our primary domain so we don't invalidate the cache entry by storing the seq_num for the wrong domain). */ if ( domain->primary ) { cache_name2sid(domain, name_domain, name_user, SID_NAME_USER, &user_sid); } /* Check if the user is in the right group */ result = check_info3_in_group( info3, state->request->data.auth.require_membership_of_sid); if (!NT_STATUS_IS_OK(result)) { DEBUG(3, ("User %s is not in the required group (%s), so plaintext authentication is rejected\n", state->request->data.auth.user, state->request->data.auth.require_membership_of_sid)); goto done; } result = append_auth_data(state->mem_ctx, state->response, state->request->flags, info3, name_domain, name_user); if (!NT_STATUS_IS_OK(result)) { goto done; } if ((state->request->flags & WBFLAG_PAM_CACHED_LOGIN) && lp_winbind_offline_logon()) { result = winbindd_store_creds(domain, state->request->data.auth.user, state->request->data.auth.pass, info3); } if (state->request->flags & WBFLAG_PAM_GET_PWD_POLICY) { struct winbindd_domain *our_domain = find_our_domain(); /* This is not entirely correct I believe, but it is consistent. Only apply the password policy settings too warn users for our own domain. Cannot obtain these from trusted DCs all the time so don't do it at all. -- jerry */ result = NT_STATUS_NOT_SUPPORTED; if (our_domain == domain ) { result = fillup_password_policy( our_domain, state->response); } if (!NT_STATUS_IS_OK(result) && !NT_STATUS_EQUAL(result, NT_STATUS_NOT_SUPPORTED) ) { DEBUG(10,("Failed to get password policies for domain %s: %s\n", domain->name, nt_errstr(result))); goto done; } } result = NT_STATUS_OK; } done: /* give us a more useful (more correct?) error code */ if ((NT_STATUS_EQUAL(result, NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND) || (NT_STATUS_EQUAL(result, NT_STATUS_UNSUCCESSFUL)))) { result = NT_STATUS_NO_LOGON_SERVERS; } set_auth_errors(state->response, result); DEBUG(NT_STATUS_IS_OK(result) ? 5 : 2, ("Plain-text authentication for user %s returned %s (PAM: %d)\n", state->request->data.auth.user, state->response->data.auth.nt_status_string, state->response->data.auth.pam_error)); return NT_STATUS_IS_OK(result) ? WINBINDD_OK : WINBINDD_ERROR; } NTSTATUS winbind_dual_SamLogon(struct winbindd_domain *domain, TALLOC_CTX *mem_ctx, uint32_t logon_parameters, const char *name_user, const char *name_domain, const char *workstation, const uint8_t chal[8], DATA_BLOB lm_response, DATA_BLOB nt_response, struct netr_SamInfo3 **info3) { NTSTATUS result; if (strequal(name_domain, get_global_sam_name())) { DATA_BLOB chal_blob = data_blob_const( chal, 8); result = winbindd_dual_auth_passdb( mem_ctx, logon_parameters, name_domain, name_user, &chal_blob, &lm_response, &nt_response, info3); /* * We need to try the remote NETLOGON server if this is NOT_IMPLEMENTED */ if (!NT_STATUS_EQUAL(result, NT_STATUS_NOT_IMPLEMENTED)) { goto process_result; } } result = winbind_samlogon_retry_loop(domain, mem_ctx, logon_parameters, domain->dcname, name_user, NULL, /* password */ name_domain, /* Bug #3248 - found by Stefan Burkei. */ workstation, /* We carefully set this above so use it... */ chal, lm_response, nt_response, false, /* interactive */ info3); if (!NT_STATUS_IS_OK(result)) { goto done; } process_result: if (NT_STATUS_IS_OK(result)) { struct dom_sid user_sid; sid_compose(&user_sid, (*info3)->base.domain_sid, (*info3)->base.rid); if ((*info3)->base.full_name.string == NULL) { struct netr_SamInfo3 *cached_info3; cached_info3 = netsamlogon_cache_get(mem_ctx, &user_sid); if (cached_info3 != NULL && cached_info3->base.full_name.string != NULL) { (*info3)->base.full_name.string = talloc_strdup(*info3, cached_info3->base.full_name.string); } else { /* this might fail so we dont check the return code */ wcache_query_user_fullname(domain, *info3, &user_sid, &(*info3)->base.full_name.string); } } wcache_invalidate_samlogon(find_domain_from_name(name_domain), &user_sid); netsamlogon_cache_store(name_user, *info3); } done: /* give us a more useful (more correct?) error code */ if ((NT_STATUS_EQUAL(result, NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND) || (NT_STATUS_EQUAL(result, NT_STATUS_UNSUCCESSFUL)))) { result = NT_STATUS_NO_LOGON_SERVERS; } DEBUG(NT_STATUS_IS_OK(result) ? 5 : 2, ("NTLM CRAP authentication for user [%s]\\[%s] returned %s\n", name_domain, name_user, nt_errstr(result))); return result; } enum winbindd_result winbindd_dual_pam_auth_crap(struct winbindd_domain *domain, struct winbindd_cli_state *state) { NTSTATUS result; struct netr_SamInfo3 *info3 = NULL; const char *name_user = NULL; const char *name_domain = NULL; const char *workstation; DATA_BLOB lm_resp, nt_resp; /* This is child-only, so no check for privileged access is needed anymore */ /* Ensure null termination */ state->request->data.auth_crap.user[sizeof(state->request->data.auth_crap.user)-1]=0; state->request->data.auth_crap.domain[sizeof(state->request->data.auth_crap.domain)-1]=0; name_user = state->request->data.auth_crap.user; name_domain = state->request->data.auth_crap.domain; workstation = state->request->data.auth_crap.workstation; DEBUG(3, ("[%5lu]: pam auth crap domain: %s user: %s\n", (unsigned long)state->pid, name_domain, name_user)); if (state->request->data.auth_crap.lm_resp_len > sizeof(state->request->data.auth_crap.lm_resp) || state->request->data.auth_crap.nt_resp_len > sizeof(state->request->data.auth_crap.nt_resp)) { if (!(state->request->flags & WBFLAG_BIG_NTLMV2_BLOB) || state->request->extra_len != state->request->data.auth_crap.nt_resp_len) { DEBUG(0, ("winbindd_pam_auth_crap: invalid password length %u/%u\n", state->request->data.auth_crap.lm_resp_len, state->request->data.auth_crap.nt_resp_len)); result = NT_STATUS_INVALID_PARAMETER; goto done; } } lm_resp = data_blob_talloc(state->mem_ctx, state->request->data.auth_crap.lm_resp, state->request->data.auth_crap.lm_resp_len); if (state->request->flags & WBFLAG_BIG_NTLMV2_BLOB) { nt_resp = data_blob_talloc(state->mem_ctx, state->request->extra_data.data, state->request->data.auth_crap.nt_resp_len); } else { nt_resp = data_blob_talloc(state->mem_ctx, state->request->data.auth_crap.nt_resp, state->request->data.auth_crap.nt_resp_len); } result = winbind_dual_SamLogon(domain, state->mem_ctx, state->request->data.auth_crap.logon_parameters, name_user, name_domain, /* Bug #3248 - found by Stefan Burkei. */ workstation, /* We carefully set this above so use it... */ state->request->data.auth_crap.chal, lm_resp, nt_resp, &info3); if (!NT_STATUS_IS_OK(result)) { goto done; } if (NT_STATUS_IS_OK(result)) { /* Check if the user is in the right group */ result = check_info3_in_group( info3, state->request->data.auth_crap.require_membership_of_sid); if (!NT_STATUS_IS_OK(result)) { DEBUG(3, ("User %s is not in the required group (%s), so " "crap authentication is rejected\n", state->request->data.auth_crap.user, state->request->data.auth_crap.require_membership_of_sid)); goto done; } result = append_auth_data(state->mem_ctx, state->response, state->request->flags, info3, name_domain, name_user); if (!NT_STATUS_IS_OK(result)) { goto done; } } done: if (state->request->flags & WBFLAG_PAM_NT_STATUS_SQUASH) { result = nt_status_squash(result); } set_auth_errors(state->response, result); return NT_STATUS_IS_OK(result) ? WINBINDD_OK : WINBINDD_ERROR; } enum winbindd_result winbindd_dual_pam_chauthtok(struct winbindd_domain *contact_domain, struct winbindd_cli_state *state) { char *oldpass; char *newpass = NULL; struct policy_handle dom_pol; struct rpc_pipe_client *cli = NULL; bool got_info = false; struct samr_DomInfo1 *info = NULL; struct userPwdChangeFailureInformation *reject = NULL; NTSTATUS result = NT_STATUS_UNSUCCESSFUL; fstring domain, user; struct dcerpc_binding_handle *b = NULL; ZERO_STRUCT(dom_pol); DEBUG(3, ("[%5lu]: dual pam chauthtok %s\n", (unsigned long)state->pid, state->request->data.auth.user)); if (!parse_domain_user(state->request->data.chauthtok.user, domain, user)) { goto done; } /* Change password */ oldpass = state->request->data.chauthtok.oldpass; newpass = state->request->data.chauthtok.newpass; /* Initialize reject reason */ state->response->data.auth.reject_reason = Undefined; /* Get sam handle */ result = cm_connect_sam(contact_domain, state->mem_ctx, true, &cli, &dom_pol); if (!NT_STATUS_IS_OK(result)) { DEBUG(1, ("could not get SAM handle on DC for %s\n", domain)); goto done; } b = cli->binding_handle; result = rpccli_samr_chgpasswd_user3(cli, state->mem_ctx, user, newpass, oldpass, &info, &reject); /* Windows 2003 returns NT_STATUS_PASSWORD_RESTRICTION */ if (NT_STATUS_EQUAL(result, NT_STATUS_PASSWORD_RESTRICTION) ) { fill_in_password_policy(state->response, info); state->response->data.auth.reject_reason = reject->extendedFailureReason; got_info = true; } /* atm the pidl generated rpccli_samr_ChangePasswordUser3 function will * return with NT_STATUS_BUFFER_TOO_SMALL for w2k dcs as w2k just * returns with 4byte error code (NT_STATUS_NOT_SUPPORTED) which is too * short to comply with the samr_ChangePasswordUser3 idl - gd */ /* only fallback when the chgpasswd_user3 call is not supported */ if (NT_STATUS_EQUAL(result, NT_STATUS_RPC_PROCNUM_OUT_OF_RANGE) || NT_STATUS_EQUAL(result, NT_STATUS_NOT_SUPPORTED) || NT_STATUS_EQUAL(result, NT_STATUS_BUFFER_TOO_SMALL) || NT_STATUS_EQUAL(result, NT_STATUS_NOT_IMPLEMENTED)) { DEBUG(10,("Password change with chgpasswd_user3 failed with: %s, retrying chgpasswd_user2\n", nt_errstr(result))); result = rpccli_samr_chgpasswd_user2(cli, state->mem_ctx, user, newpass, oldpass); /* Windows 2000 returns NT_STATUS_ACCOUNT_RESTRICTION. Map to the same status code as Windows 2003. */ if ( NT_STATUS_EQUAL(NT_STATUS_ACCOUNT_RESTRICTION, result ) ) { result = NT_STATUS_PASSWORD_RESTRICTION; } } done: if (NT_STATUS_IS_OK(result) && (state->request->flags & WBFLAG_PAM_CACHED_LOGIN) && lp_winbind_offline_logon()) { result = winbindd_update_creds_by_name(contact_domain, user, newpass); /* Again, this happens when we login from gdm or xdm * and the password expires, *BUT* cached crendentials * doesn't exist. winbindd_update_creds_by_name() * returns NT_STATUS_NO_SUCH_USER. * This is not a failure. * --- BoYang * */ if (NT_STATUS_EQUAL(result, NT_STATUS_NO_SUCH_USER)) { result = NT_STATUS_OK; } if (!NT_STATUS_IS_OK(result)) { DEBUG(10, ("Failed to store creds: %s\n", nt_errstr(result))); goto process_result; } } if (!NT_STATUS_IS_OK(result) && !got_info && contact_domain) { NTSTATUS policy_ret; policy_ret = fillup_password_policy( contact_domain, state->response); /* failure of this is non critical, it will just provide no * additional information to the client why the change has * failed - Guenther */ if (!NT_STATUS_IS_OK(policy_ret)) { DEBUG(10,("Failed to get password policies: %s\n", nt_errstr(policy_ret))); goto process_result; } } process_result: if (strequal(contact_domain->name, get_global_sam_name())) { /* FIXME: internal rpc pipe does not cache handles yet */ if (b) { if (is_valid_policy_hnd(&dom_pol)) { NTSTATUS _result; dcerpc_samr_Close(b, state->mem_ctx, &dom_pol, &_result); } TALLOC_FREE(cli); } } set_auth_errors(state->response, result); DEBUG(NT_STATUS_IS_OK(result) ? 5 : 2, ("Password change for user [%s]\\[%s] returned %s (PAM: %d)\n", domain, user, state->response->data.auth.nt_status_string, state->response->data.auth.pam_error)); return NT_STATUS_IS_OK(result) ? WINBINDD_OK : WINBINDD_ERROR; } enum winbindd_result winbindd_dual_pam_logoff(struct winbindd_domain *domain, struct winbindd_cli_state *state) { NTSTATUS result = NT_STATUS_NOT_SUPPORTED; DEBUG(3, ("[%5lu]: pam dual logoff %s\n", (unsigned long)state->pid, state->request->data.logoff.user)); if (!(state->request->flags & WBFLAG_PAM_KRB5)) { result = NT_STATUS_OK; goto process_result; } if (state->request->data.logoff.krb5ccname[0] == '\0') { result = NT_STATUS_OK; goto process_result; } #ifdef HAVE_KRB5 if (state->request->data.logoff.uid < 0) { DEBUG(0,("winbindd_pam_logoff: invalid uid\n")); goto process_result; } /* what we need here is to find the corresponding krb5 ccache name *we* * created for a given username and destroy it */ if (!ccache_entry_exists(state->request->data.logoff.user)) { result = NT_STATUS_OK; DEBUG(10,("winbindd_pam_logoff: no entry found.\n")); goto process_result; } if (!ccache_entry_identical(state->request->data.logoff.user, state->request->data.logoff.uid, state->request->data.logoff.krb5ccname)) { DEBUG(0,("winbindd_pam_logoff: cached entry differs.\n")); goto process_result; } result = remove_ccache(state->request->data.logoff.user); if (!NT_STATUS_IS_OK(result)) { DEBUG(0,("winbindd_pam_logoff: failed to remove ccache: %s\n", nt_errstr(result))); goto process_result; } /* * Remove any mlock'ed memory creds in the child * we might be using for krb5 ticket renewal. */ winbindd_delete_memory_creds(state->request->data.logoff.user); #else result = NT_STATUS_NOT_SUPPORTED; #endif process_result: set_auth_errors(state->response, result); return NT_STATUS_IS_OK(result) ? WINBINDD_OK : WINBINDD_ERROR; } /* Change user password with auth crap*/ enum winbindd_result winbindd_dual_pam_chng_pswd_auth_crap(struct winbindd_domain *domainSt, struct winbindd_cli_state *state) { NTSTATUS result; DATA_BLOB new_nt_password; DATA_BLOB old_nt_hash_enc; DATA_BLOB new_lm_password; DATA_BLOB old_lm_hash_enc; fstring domain,user; struct policy_handle dom_pol; struct winbindd_domain *contact_domain = domainSt; struct rpc_pipe_client *cli = NULL; struct dcerpc_binding_handle *b = NULL; ZERO_STRUCT(dom_pol); /* Ensure null termination */ state->request->data.chng_pswd_auth_crap.user[ sizeof(state->request->data.chng_pswd_auth_crap.user)-1]=0; state->request->data.chng_pswd_auth_crap.domain[ sizeof(state->request->data.chng_pswd_auth_crap.domain)-1]=0; *domain = 0; *user = 0; DEBUG(3, ("[%5lu]: pam change pswd auth crap domain: %s user: %s\n", (unsigned long)state->pid, state->request->data.chng_pswd_auth_crap.domain, state->request->data.chng_pswd_auth_crap.user)); if (lp_winbind_offline_logon()) { DEBUG(0,("Refusing password change as winbind offline logons are enabled. ")); DEBUGADD(0,("Changing passwords here would risk inconsistent logons\n")); result = NT_STATUS_ACCESS_DENIED; goto done; } if (*state->request->data.chng_pswd_auth_crap.domain) { fstrcpy(domain,state->request->data.chng_pswd_auth_crap.domain); } else { parse_domain_user(state->request->data.chng_pswd_auth_crap.user, domain, user); if(!*domain) { DEBUG(3,("no domain specified with username (%s) - " "failing auth\n", state->request->data.chng_pswd_auth_crap.user)); result = NT_STATUS_NO_SUCH_USER; goto done; } } if (!*domain && lp_winbind_use_default_domain()) { fstrcpy(domain,lp_workgroup()); } if(!*user) { fstrcpy(user, state->request->data.chng_pswd_auth_crap.user); } DEBUG(3, ("[%5lu]: pam auth crap domain: %s user: %s\n", (unsigned long)state->pid, domain, user)); /* Change password */ new_nt_password = data_blob_const( state->request->data.chng_pswd_auth_crap.new_nt_pswd, state->request->data.chng_pswd_auth_crap.new_nt_pswd_len); old_nt_hash_enc = data_blob_const( state->request->data.chng_pswd_auth_crap.old_nt_hash_enc, state->request->data.chng_pswd_auth_crap.old_nt_hash_enc_len); if(state->request->data.chng_pswd_auth_crap.new_lm_pswd_len > 0) { new_lm_password = data_blob_const( state->request->data.chng_pswd_auth_crap.new_lm_pswd, state->request->data.chng_pswd_auth_crap.new_lm_pswd_len); old_lm_hash_enc = data_blob_const( state->request->data.chng_pswd_auth_crap.old_lm_hash_enc, state->request->data.chng_pswd_auth_crap.old_lm_hash_enc_len); } else { new_lm_password = data_blob_null; old_lm_hash_enc = data_blob_null; } /* Get sam handle */ result = cm_connect_sam(contact_domain, state->mem_ctx, true, &cli, &dom_pol); if (!NT_STATUS_IS_OK(result)) { DEBUG(1, ("could not get SAM handle on DC for %s\n", domain)); goto done; } b = cli->binding_handle; result = rpccli_samr_chng_pswd_auth_crap( cli, state->mem_ctx, user, new_nt_password, old_nt_hash_enc, new_lm_password, old_lm_hash_enc); done: if (strequal(contact_domain->name, get_global_sam_name())) { /* FIXME: internal rpc pipe does not cache handles yet */ if (b) { if (is_valid_policy_hnd(&dom_pol)) { NTSTATUS _result; dcerpc_samr_Close(b, state->mem_ctx, &dom_pol, &_result); } TALLOC_FREE(cli); } } set_auth_errors(state->response, result); DEBUG(NT_STATUS_IS_OK(result) ? 5 : 2, ("Password change for user [%s]\\[%s] returned %s (PAM: %d)\n", domain, user, state->response->data.auth.nt_status_string, state->response->data.auth.pam_error)); return NT_STATUS_IS_OK(result) ? WINBINDD_OK : WINBINDD_ERROR; } #ifdef HAVE_KRB5 static NTSTATUS extract_pac_vrfy_sigs(TALLOC_CTX *mem_ctx, DATA_BLOB pac_blob, struct PAC_LOGON_INFO **logon_info) { krb5_context krbctx = NULL; krb5_error_code k5ret; krb5_keytab keytab; krb5_kt_cursor cursor; krb5_keytab_entry entry; NTSTATUS status = NT_STATUS_UNSUCCESSFUL; ZERO_STRUCT(entry); ZERO_STRUCT(cursor); k5ret = krb5_init_context(&krbctx); if (k5ret) { DEBUG(1, ("Failed to initialize kerberos context: %s\n", error_message(k5ret))); status = krb5_to_nt_status(k5ret); goto out; } k5ret = gse_krb5_get_server_keytab(krbctx, &keytab); if (k5ret) { DEBUG(1, ("Failed to get keytab: %s\n", error_message(k5ret))); status = krb5_to_nt_status(k5ret); goto out_free; } k5ret = krb5_kt_start_seq_get(krbctx, keytab, &cursor); if (k5ret) { DEBUG(1, ("Failed to start seq: %s\n", error_message(k5ret))); status = krb5_to_nt_status(k5ret); goto out_keytab; } k5ret = krb5_kt_next_entry(krbctx, keytab, &entry, &cursor); while (k5ret == 0) { status = kerberos_pac_logon_info(mem_ctx, pac_blob, krbctx, NULL, KRB5_KT_KEY(&entry), NULL, 0, logon_info); if (NT_STATUS_IS_OK(status)) { break; } k5ret = smb_krb5_kt_free_entry(krbctx, &entry); k5ret = krb5_kt_next_entry(krbctx, keytab, &entry, &cursor); } k5ret = krb5_kt_end_seq_get(krbctx, keytab, &cursor); if (k5ret) { DEBUG(1, ("Failed to end seq: %s\n", error_message(k5ret))); } out_keytab: k5ret = krb5_kt_close(krbctx, keytab); if (k5ret) { DEBUG(1, ("Failed to close keytab: %s\n", error_message(k5ret))); } out_free: krb5_free_context(krbctx); out: return status; } NTSTATUS winbindd_pam_auth_pac_send(struct winbindd_cli_state *state, struct netr_SamInfo3 **info3) { struct winbindd_request *req = state->request; DATA_BLOB pac_blob; struct PAC_LOGON_INFO *logon_info = NULL; struct netr_SamInfo3 *info3_copy = NULL; NTSTATUS result; pac_blob = data_blob_const(req->extra_data.data, req->extra_len); result = extract_pac_vrfy_sigs(state->mem_ctx, pac_blob, &logon_info); if (!NT_STATUS_IS_OK(result) && !NT_STATUS_EQUAL(result, NT_STATUS_ACCESS_DENIED)) { DEBUG(1, ("Error during PAC signature verification: %s\n", nt_errstr(result))); return result; } if (logon_info) { /* Signature verification succeeded, trust the PAC */ result = create_info3_from_pac_logon_info(state->mem_ctx, logon_info, &info3_copy); if (!NT_STATUS_IS_OK(result)) { return result; } netsamlogon_cache_store(NULL, info3_copy); } else { /* Try without signature verification */ result = kerberos_pac_logon_info(state->mem_ctx, pac_blob, NULL, NULL, NULL, NULL, 0, &logon_info); if (!NT_STATUS_IS_OK(result)) { DEBUG(10, ("Could not extract PAC: %s\n", nt_errstr(result))); return result; } if (logon_info) { /* * Don't strictly need to copy here, * but it makes it explicit we're * returning a copy talloc'ed off * the state->mem_ctx. */ info3_copy = copy_netr_SamInfo3(state->mem_ctx, &logon_info->info3); if (info3_copy == NULL) { return NT_STATUS_NO_MEMORY; } } } *info3 = info3_copy; return NT_STATUS_OK; } #else /* HAVE_KRB5 */ NTSTATUS winbindd_pam_auth_pac_send(struct winbindd_cli_state *state, struct netr_SamInfo3 **info3) { return NT_STATUS_NO_SUCH_USER; } #endif /* HAVE_KRB5 */
gpl-3.0
evgenyz/gnome-builder
plugins/gnome-code-assistance/gca-diagnostics.c
4
35276
/* * Generated by gdbus-codegen 2.42.0. DO NOT EDIT. * * The license of this code is the same as for the source it was derived from. */ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "gca-diagnostics.h" #include <string.h> #ifdef G_OS_UNIX # include <gio/gunixfdlist.h> #endif typedef struct { GDBusArgInfo parent_struct; gboolean use_gvariant; } _ExtendedGDBusArgInfo; typedef struct { GDBusMethodInfo parent_struct; const gchar *signal_name; gboolean pass_fdlist; } _ExtendedGDBusMethodInfo; typedef struct { GDBusSignalInfo parent_struct; const gchar *signal_name; } _ExtendedGDBusSignalInfo; typedef struct { GDBusPropertyInfo parent_struct; const gchar *hyphen_name; gboolean use_gvariant; } _ExtendedGDBusPropertyInfo; typedef struct { GDBusInterfaceInfo parent_struct; const gchar *hyphen_name; } _ExtendedGDBusInterfaceInfo; typedef struct { const _ExtendedGDBusPropertyInfo *info; guint prop_id; GValue orig_value; /* the value before the change */ } ChangedProperty; static void _changed_property_free (ChangedProperty *data) { g_value_unset (&data->orig_value); g_free (data); } static gboolean _g_strv_equal0 (gchar **a, gchar **b) { gboolean ret = FALSE; guint n; if (a == NULL && b == NULL) { ret = TRUE; goto out; } if (a == NULL || b == NULL) goto out; if (g_strv_length (a) != g_strv_length (b)) goto out; for (n = 0; a[n] != NULL; n++) if (g_strcmp0 (a[n], b[n]) != 0) goto out; ret = TRUE; out: return ret; } static gboolean _g_variant_equal0 (GVariant *a, GVariant *b) { gboolean ret = FALSE; if (a == NULL && b == NULL) { ret = TRUE; goto out; } if (a == NULL || b == NULL) goto out; ret = g_variant_equal (a, b); out: return ret; } G_GNUC_UNUSED static gboolean _g_value_equal (const GValue *a, const GValue *b) { gboolean ret = FALSE; g_assert (G_VALUE_TYPE (a) == G_VALUE_TYPE (b)); switch (G_VALUE_TYPE (a)) { case G_TYPE_BOOLEAN: ret = (g_value_get_boolean (a) == g_value_get_boolean (b)); break; case G_TYPE_UCHAR: ret = (g_value_get_uchar (a) == g_value_get_uchar (b)); break; case G_TYPE_INT: ret = (g_value_get_int (a) == g_value_get_int (b)); break; case G_TYPE_UINT: ret = (g_value_get_uint (a) == g_value_get_uint (b)); break; case G_TYPE_INT64: ret = (g_value_get_int64 (a) == g_value_get_int64 (b)); break; case G_TYPE_UINT64: ret = (g_value_get_uint64 (a) == g_value_get_uint64 (b)); break; case G_TYPE_DOUBLE: { /* Avoid -Wfloat-equal warnings by doing a direct bit compare */ gdouble da = g_value_get_double (a); gdouble db = g_value_get_double (b); ret = memcmp (&da, &db, sizeof (gdouble)) == 0; } break; case G_TYPE_STRING: ret = (g_strcmp0 (g_value_get_string (a), g_value_get_string (b)) == 0); break; case G_TYPE_VARIANT: ret = _g_variant_equal0 (g_value_get_variant (a), g_value_get_variant (b)); break; default: if (G_VALUE_TYPE (a) == G_TYPE_STRV) ret = _g_strv_equal0 (g_value_get_boxed (a), g_value_get_boxed (b)); else g_critical ("_g_value_equal() does not handle type %s", g_type_name (G_VALUE_TYPE (a))); break; } return ret; } /* ------------------------------------------------------------------------ * Code for interface org.gnome.CodeAssist.v1.Diagnostics * ------------------------------------------------------------------------ */ /** * SECTION:GcaDiagnostics * @title: GcaDiagnostics * @short_description: Generated C code for the org.gnome.CodeAssist.v1.Diagnostics D-Bus interface * * This section contains code for working with the <link linkend="gdbus-interface-org-gnome-CodeAssist-v1-Diagnostics.top_of_page">org.gnome.CodeAssist.v1.Diagnostics</link> D-Bus interface in C. */ /* ---- Introspection data for org.gnome.CodeAssist.v1.Diagnostics ---- */ static const _ExtendedGDBusArgInfo _gca_diagnostics_method_info_diagnostics_OUT_ARG_unnamed_arg0 = { { -1, (gchar *) "unnamed_arg0", (gchar *) "a(ua((x(xx)(xx))s)a(x(xx)(xx))s)", NULL }, FALSE }; static const _ExtendedGDBusArgInfo * const _gca_diagnostics_method_info_diagnostics_OUT_ARG_pointers[] = { &_gca_diagnostics_method_info_diagnostics_OUT_ARG_unnamed_arg0, NULL }; static const _ExtendedGDBusMethodInfo _gca_diagnostics_method_info_diagnostics = { { -1, (gchar *) "Diagnostics", NULL, (GDBusArgInfo **) &_gca_diagnostics_method_info_diagnostics_OUT_ARG_pointers, NULL }, "handle-diagnostics", FALSE }; static const _ExtendedGDBusMethodInfo * const _gca_diagnostics_method_info_pointers[] = { &_gca_diagnostics_method_info_diagnostics, NULL }; static const _ExtendedGDBusInterfaceInfo _gca_diagnostics_interface_info = { { -1, (gchar *) "org.gnome.CodeAssist.v1.Diagnostics", (GDBusMethodInfo **) &_gca_diagnostics_method_info_pointers, NULL, NULL, NULL }, "diagnostics", }; /** * gca_diagnostics_interface_info: * * Gets a machine-readable description of the <link linkend="gdbus-interface-org-gnome-CodeAssist-v1-Diagnostics.top_of_page">org.gnome.CodeAssist.v1.Diagnostics</link> D-Bus interface. * * Returns: (transfer none): A #GDBusInterfaceInfo. Do not free. */ GDBusInterfaceInfo * gca_diagnostics_interface_info (void) { return (GDBusInterfaceInfo *) &_gca_diagnostics_interface_info.parent_struct; } /** * gca_diagnostics_override_properties: * @klass: The class structure for a #GObject<!-- -->-derived class. * @property_id_begin: The property id to assign to the first overridden property. * * Overrides all #GObject properties in the #GcaDiagnostics interface for a concrete class. * The properties are overridden in the order they are defined. * * Returns: The last property id. */ guint gca_diagnostics_override_properties (GObjectClass *klass, guint property_id_begin) { return property_id_begin - 1; } /** * GcaDiagnostics: * * Abstract interface type for the D-Bus interface <link linkend="gdbus-interface-org-gnome-CodeAssist-v1-Diagnostics.top_of_page">org.gnome.CodeAssist.v1.Diagnostics</link>. */ /** * GcaDiagnosticsIface: * @parent_iface: The parent interface. * @handle_diagnostics: Handler for the #GcaDiagnostics::handle-diagnostics signal. * * Virtual table for the D-Bus interface <link linkend="gdbus-interface-org-gnome-CodeAssist-v1-Diagnostics.top_of_page">org.gnome.CodeAssist.v1.Diagnostics</link>. */ typedef GcaDiagnosticsIface GcaDiagnosticsInterface; G_DEFINE_INTERFACE (GcaDiagnostics, gca_diagnostics, G_TYPE_OBJECT); static void gca_diagnostics_default_init (GcaDiagnosticsIface *iface) { /* GObject signals for incoming D-Bus method calls: */ /** * GcaDiagnostics::handle-diagnostics: * @object: A #GcaDiagnostics. * @invocation: A #GDBusMethodInvocation. * * Signal emitted when a remote caller is invoking the <link linkend="gdbus-method-org-gnome-CodeAssist-v1-Diagnostics.Diagnostics">Diagnostics()</link> D-Bus method. * * If a signal handler returns %TRUE, it means the signal handler will handle the invocation (e.g. take a reference to @invocation and eventually call gca_diagnostics_complete_diagnostics() or e.g. g_dbus_method_invocation_return_error() on it) and no order signal handlers will run. If no signal handler handles the invocation, the %G_DBUS_ERROR_UNKNOWN_METHOD error is returned. * * Returns: %TRUE if the invocation was handled, %FALSE to let other signal handlers run. */ g_signal_new ("handle-diagnostics", G_TYPE_FROM_INTERFACE (iface), G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GcaDiagnosticsIface, handle_diagnostics), g_signal_accumulator_true_handled, NULL, g_cclosure_marshal_generic, G_TYPE_BOOLEAN, 1, G_TYPE_DBUS_METHOD_INVOCATION); } /** * gca_diagnostics_call_diagnostics: * @proxy: A #GcaDiagnosticsProxy. * @cancellable: (allow-none): A #GCancellable or %NULL. * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL. * @user_data: User data to pass to @callback. * * Asynchronously invokes the <link linkend="gdbus-method-org-gnome-CodeAssist-v1-Diagnostics.Diagnostics">Diagnostics()</link> D-Bus method on @proxy. * When the operation is finished, @callback will be invoked in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link> of the thread you are calling this method from. * You can then call gca_diagnostics_call_diagnostics_finish() to get the result of the operation. * * See gca_diagnostics_call_diagnostics_sync() for the synchronous, blocking version of this method. */ void gca_diagnostics_call_diagnostics ( GcaDiagnostics *proxy, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data) { g_dbus_proxy_call (G_DBUS_PROXY (proxy), "Diagnostics", g_variant_new ("()"), G_DBUS_CALL_FLAGS_NONE, -1, cancellable, callback, user_data); } /** * gca_diagnostics_call_diagnostics_finish: * @proxy: A #GcaDiagnosticsProxy. * @out_unnamed_arg0: (out): Return location for return parameter or %NULL to ignore. * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to gca_diagnostics_call_diagnostics(). * @error: Return location for error or %NULL. * * Finishes an operation started with gca_diagnostics_call_diagnostics(). * * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. */ gboolean gca_diagnostics_call_diagnostics_finish ( GcaDiagnostics *proxy, GVariant **out_unnamed_arg0, GAsyncResult *res, GError **error) { GVariant *_ret; _ret = g_dbus_proxy_call_finish (G_DBUS_PROXY (proxy), res, error); if (_ret == NULL) goto _out; g_variant_get (_ret, "(@a(ua((x(xx)(xx))s)a(x(xx)(xx))s))", out_unnamed_arg0); g_variant_unref (_ret); _out: return _ret != NULL; } /** * gca_diagnostics_call_diagnostics_sync: * @proxy: A #GcaDiagnosticsProxy. * @out_unnamed_arg0: (out): Return location for return parameter or %NULL to ignore. * @cancellable: (allow-none): A #GCancellable or %NULL. * @error: Return location for error or %NULL. * * Synchronously invokes the <link linkend="gdbus-method-org-gnome-CodeAssist-v1-Diagnostics.Diagnostics">Diagnostics()</link> D-Bus method on @proxy. The calling thread is blocked until a reply is received. * * See gca_diagnostics_call_diagnostics() for the asynchronous version of this method. * * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. */ gboolean gca_diagnostics_call_diagnostics_sync ( GcaDiagnostics *proxy, GVariant **out_unnamed_arg0, GCancellable *cancellable, GError **error) { GVariant *_ret; _ret = g_dbus_proxy_call_sync (G_DBUS_PROXY (proxy), "Diagnostics", g_variant_new ("()"), G_DBUS_CALL_FLAGS_NONE, -1, cancellable, error); if (_ret == NULL) goto _out; g_variant_get (_ret, "(@a(ua((x(xx)(xx))s)a(x(xx)(xx))s))", out_unnamed_arg0); g_variant_unref (_ret); _out: return _ret != NULL; } /** * gca_diagnostics_complete_diagnostics: * @object: A #GcaDiagnostics. * @invocation: (transfer full): A #GDBusMethodInvocation. * @unnamed_arg0: Parameter to return. * * Helper function used in service implementations to finish handling invocations of the <link linkend="gdbus-method-org-gnome-CodeAssist-v1-Diagnostics.Diagnostics">Diagnostics()</link> D-Bus method. If you instead want to finish handling an invocation by returning an error, use g_dbus_method_invocation_return_error() or similar. * * This method will free @invocation, you cannot use it afterwards. */ void gca_diagnostics_complete_diagnostics ( GcaDiagnostics *object, GDBusMethodInvocation *invocation, GVariant *unnamed_arg0) { g_dbus_method_invocation_return_value (invocation, g_variant_new ("(@a(ua((x(xx)(xx))s)a(x(xx)(xx))s))", unnamed_arg0)); } /* ------------------------------------------------------------------------ */ /** * GcaDiagnosticsProxy: * * The #GcaDiagnosticsProxy structure contains only private data and should only be accessed using the provided API. */ /** * GcaDiagnosticsProxyClass: * @parent_class: The parent class. * * Class structure for #GcaDiagnosticsProxy. */ struct _GcaDiagnosticsProxyPrivate { GData *qdata; }; static void gca_diagnostics_proxy_iface_init (GcaDiagnosticsIface *iface); #if GLIB_VERSION_MAX_ALLOWED >= GLIB_VERSION_2_38 G_DEFINE_TYPE_WITH_CODE (GcaDiagnosticsProxy, gca_diagnostics_proxy, G_TYPE_DBUS_PROXY, G_ADD_PRIVATE (GcaDiagnosticsProxy) G_IMPLEMENT_INTERFACE (GCA_TYPE_DIAGNOSTICS, gca_diagnostics_proxy_iface_init)); #else G_DEFINE_TYPE_WITH_CODE (GcaDiagnosticsProxy, gca_diagnostics_proxy, G_TYPE_DBUS_PROXY, G_IMPLEMENT_INTERFACE (GCA_TYPE_DIAGNOSTICS, gca_diagnostics_proxy_iface_init)); #endif static void gca_diagnostics_proxy_finalize (GObject *object) { GcaDiagnosticsProxy *proxy = GCA_DIAGNOSTICS_PROXY (object); g_datalist_clear (&proxy->priv->qdata); G_OBJECT_CLASS (gca_diagnostics_proxy_parent_class)->finalize (object); } static void gca_diagnostics_proxy_get_property (GObject *object, guint prop_id, GValue *value, GParamSpec *pspec G_GNUC_UNUSED) { } static void gca_diagnostics_proxy_set_property (GObject *object, guint prop_id, const GValue *value, GParamSpec *pspec G_GNUC_UNUSED) { } static void gca_diagnostics_proxy_g_signal (GDBusProxy *proxy, const gchar *sender_name G_GNUC_UNUSED, const gchar *signal_name, GVariant *parameters) { _ExtendedGDBusSignalInfo *info; GVariantIter iter; GVariant *child; GValue *paramv; guint num_params; guint n; guint signal_id; info = (_ExtendedGDBusSignalInfo *) g_dbus_interface_info_lookup_signal ((GDBusInterfaceInfo *) &_gca_diagnostics_interface_info.parent_struct, signal_name); if (info == NULL) return; num_params = g_variant_n_children (parameters); paramv = g_new0 (GValue, num_params + 1); g_value_init (&paramv[0], GCA_TYPE_DIAGNOSTICS); g_value_set_object (&paramv[0], proxy); g_variant_iter_init (&iter, parameters); n = 1; while ((child = g_variant_iter_next_value (&iter)) != NULL) { _ExtendedGDBusArgInfo *arg_info = (_ExtendedGDBusArgInfo *) info->parent_struct.args[n - 1]; if (arg_info->use_gvariant) { g_value_init (&paramv[n], G_TYPE_VARIANT); g_value_set_variant (&paramv[n], child); n++; } else g_dbus_gvariant_to_gvalue (child, &paramv[n++]); g_variant_unref (child); } signal_id = g_signal_lookup (info->signal_name, GCA_TYPE_DIAGNOSTICS); g_signal_emitv (paramv, signal_id, 0, NULL); for (n = 0; n < num_params + 1; n++) g_value_unset (&paramv[n]); g_free (paramv); } static void gca_diagnostics_proxy_g_properties_changed (GDBusProxy *_proxy, GVariant *changed_properties, const gchar *const *invalidated_properties) { GcaDiagnosticsProxy *proxy = GCA_DIAGNOSTICS_PROXY (_proxy); guint n; const gchar *key; GVariantIter *iter; _ExtendedGDBusPropertyInfo *info; g_variant_get (changed_properties, "a{sv}", &iter); while (g_variant_iter_next (iter, "{&sv}", &key, NULL)) { info = (_ExtendedGDBusPropertyInfo *) g_dbus_interface_info_lookup_property ((GDBusInterfaceInfo *) &_gca_diagnostics_interface_info.parent_struct, key); g_datalist_remove_data (&proxy->priv->qdata, key); if (info != NULL) g_object_notify (G_OBJECT (proxy), info->hyphen_name); } g_variant_iter_free (iter); for (n = 0; invalidated_properties[n] != NULL; n++) { info = (_ExtendedGDBusPropertyInfo *) g_dbus_interface_info_lookup_property ((GDBusInterfaceInfo *) &_gca_diagnostics_interface_info.parent_struct, invalidated_properties[n]); g_datalist_remove_data (&proxy->priv->qdata, invalidated_properties[n]); if (info != NULL) g_object_notify (G_OBJECT (proxy), info->hyphen_name); } } static void gca_diagnostics_proxy_init (GcaDiagnosticsProxy *proxy) { #if GLIB_VERSION_MAX_ALLOWED >= GLIB_VERSION_2_38 proxy->priv = gca_diagnostics_proxy_get_instance_private (proxy); #else proxy->priv = G_TYPE_INSTANCE_GET_PRIVATE (proxy, GCA_TYPE_DIAGNOSTICS_PROXY, GcaDiagnosticsProxyPrivate); #endif g_dbus_proxy_set_interface_info (G_DBUS_PROXY (proxy), gca_diagnostics_interface_info ()); } static void gca_diagnostics_proxy_class_init (GcaDiagnosticsProxyClass *klass) { GObjectClass *gobject_class; GDBusProxyClass *proxy_class; gobject_class = G_OBJECT_CLASS (klass); gobject_class->finalize = gca_diagnostics_proxy_finalize; gobject_class->get_property = gca_diagnostics_proxy_get_property; gobject_class->set_property = gca_diagnostics_proxy_set_property; proxy_class = G_DBUS_PROXY_CLASS (klass); proxy_class->g_signal = gca_diagnostics_proxy_g_signal; proxy_class->g_properties_changed = gca_diagnostics_proxy_g_properties_changed; #if GLIB_VERSION_MAX_ALLOWED < GLIB_VERSION_2_38 g_type_class_add_private (klass, sizeof (GcaDiagnosticsProxyPrivate)); #endif } static void gca_diagnostics_proxy_iface_init (GcaDiagnosticsIface *iface) { } /** * gca_diagnostics_proxy_new: * @connection: A #GDBusConnection. * @flags: Flags from the #GDBusProxyFlags enumeration. * @name: (allow-none): A bus name (well-known or unique) or %NULL if @connection is not a message bus connection. * @object_path: An object path. * @cancellable: (allow-none): A #GCancellable or %NULL. * @callback: A #GAsyncReadyCallback to call when the request is satisfied. * @user_data: User data to pass to @callback. * * Asynchronously creates a proxy for the D-Bus interface <link linkend="gdbus-interface-org-gnome-CodeAssist-v1-Diagnostics.top_of_page">org.gnome.CodeAssist.v1.Diagnostics</link>. See g_dbus_proxy_new() for more details. * * When the operation is finished, @callback will be invoked in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link> of the thread you are calling this method from. * You can then call gca_diagnostics_proxy_new_finish() to get the result of the operation. * * See gca_diagnostics_proxy_new_sync() for the synchronous, blocking version of this constructor. */ void gca_diagnostics_proxy_new ( GDBusConnection *connection, GDBusProxyFlags flags, const gchar *name, const gchar *object_path, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data) { g_async_initable_new_async (GCA_TYPE_DIAGNOSTICS_PROXY, G_PRIORITY_DEFAULT, cancellable, callback, user_data, "g-flags", flags, "g-name", name, "g-connection", connection, "g-object-path", object_path, "g-interface-name", "org.gnome.CodeAssist.v1.Diagnostics", NULL); } /** * gca_diagnostics_proxy_new_finish: * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to gca_diagnostics_proxy_new(). * @error: Return location for error or %NULL * * Finishes an operation started with gca_diagnostics_proxy_new(). * * Returns: (transfer full) (type GcaDiagnosticsProxy): The constructed proxy object or %NULL if @error is set. */ GcaDiagnostics * gca_diagnostics_proxy_new_finish ( GAsyncResult *res, GError **error) { GObject *ret; GObject *source_object; source_object = g_async_result_get_source_object (res); ret = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object), res, error); g_object_unref (source_object); if (ret != NULL) return GCA_DIAGNOSTICS (ret); else return NULL; } /** * gca_diagnostics_proxy_new_sync: * @connection: A #GDBusConnection. * @flags: Flags from the #GDBusProxyFlags enumeration. * @name: (allow-none): A bus name (well-known or unique) or %NULL if @connection is not a message bus connection. * @object_path: An object path. * @cancellable: (allow-none): A #GCancellable or %NULL. * @error: Return location for error or %NULL * * Synchronously creates a proxy for the D-Bus interface <link linkend="gdbus-interface-org-gnome-CodeAssist-v1-Diagnostics.top_of_page">org.gnome.CodeAssist.v1.Diagnostics</link>. See g_dbus_proxy_new_sync() for more details. * * The calling thread is blocked until a reply is received. * * See gca_diagnostics_proxy_new() for the asynchronous version of this constructor. * * Returns: (transfer full) (type GcaDiagnosticsProxy): The constructed proxy object or %NULL if @error is set. */ GcaDiagnostics * gca_diagnostics_proxy_new_sync ( GDBusConnection *connection, GDBusProxyFlags flags, const gchar *name, const gchar *object_path, GCancellable *cancellable, GError **error) { GInitable *ret; ret = g_initable_new (GCA_TYPE_DIAGNOSTICS_PROXY, cancellable, error, "g-flags", flags, "g-name", name, "g-connection", connection, "g-object-path", object_path, "g-interface-name", "org.gnome.CodeAssist.v1.Diagnostics", NULL); if (ret != NULL) return GCA_DIAGNOSTICS (ret); else return NULL; } /** * gca_diagnostics_proxy_new_for_bus: * @bus_type: A #GBusType. * @flags: Flags from the #GDBusProxyFlags enumeration. * @name: A bus name (well-known or unique). * @object_path: An object path. * @cancellable: (allow-none): A #GCancellable or %NULL. * @callback: A #GAsyncReadyCallback to call when the request is satisfied. * @user_data: User data to pass to @callback. * * Like gca_diagnostics_proxy_new() but takes a #GBusType instead of a #GDBusConnection. * * When the operation is finished, @callback will be invoked in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link> of the thread you are calling this method from. * You can then call gca_diagnostics_proxy_new_for_bus_finish() to get the result of the operation. * * See gca_diagnostics_proxy_new_for_bus_sync() for the synchronous, blocking version of this constructor. */ void gca_diagnostics_proxy_new_for_bus ( GBusType bus_type, GDBusProxyFlags flags, const gchar *name, const gchar *object_path, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data) { g_async_initable_new_async (GCA_TYPE_DIAGNOSTICS_PROXY, G_PRIORITY_DEFAULT, cancellable, callback, user_data, "g-flags", flags, "g-name", name, "g-bus-type", bus_type, "g-object-path", object_path, "g-interface-name", "org.gnome.CodeAssist.v1.Diagnostics", NULL); } /** * gca_diagnostics_proxy_new_for_bus_finish: * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to gca_diagnostics_proxy_new_for_bus(). * @error: Return location for error or %NULL * * Finishes an operation started with gca_diagnostics_proxy_new_for_bus(). * * Returns: (transfer full) (type GcaDiagnosticsProxy): The constructed proxy object or %NULL if @error is set. */ GcaDiagnostics * gca_diagnostics_proxy_new_for_bus_finish ( GAsyncResult *res, GError **error) { GObject *ret; GObject *source_object; source_object = g_async_result_get_source_object (res); ret = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object), res, error); g_object_unref (source_object); if (ret != NULL) return GCA_DIAGNOSTICS (ret); else return NULL; } /** * gca_diagnostics_proxy_new_for_bus_sync: * @bus_type: A #GBusType. * @flags: Flags from the #GDBusProxyFlags enumeration. * @name: A bus name (well-known or unique). * @object_path: An object path. * @cancellable: (allow-none): A #GCancellable or %NULL. * @error: Return location for error or %NULL * * Like gca_diagnostics_proxy_new_sync() but takes a #GBusType instead of a #GDBusConnection. * * The calling thread is blocked until a reply is received. * * See gca_diagnostics_proxy_new_for_bus() for the asynchronous version of this constructor. * * Returns: (transfer full) (type GcaDiagnosticsProxy): The constructed proxy object or %NULL if @error is set. */ GcaDiagnostics * gca_diagnostics_proxy_new_for_bus_sync ( GBusType bus_type, GDBusProxyFlags flags, const gchar *name, const gchar *object_path, GCancellable *cancellable, GError **error) { GInitable *ret; ret = g_initable_new (GCA_TYPE_DIAGNOSTICS_PROXY, cancellable, error, "g-flags", flags, "g-name", name, "g-bus-type", bus_type, "g-object-path", object_path, "g-interface-name", "org.gnome.CodeAssist.v1.Diagnostics", NULL); if (ret != NULL) return GCA_DIAGNOSTICS (ret); else return NULL; } /* ------------------------------------------------------------------------ */ /** * GcaDiagnosticsSkeleton: * * The #GcaDiagnosticsSkeleton structure contains only private data and should only be accessed using the provided API. */ /** * GcaDiagnosticsSkeletonClass: * @parent_class: The parent class. * * Class structure for #GcaDiagnosticsSkeleton. */ struct _GcaDiagnosticsSkeletonPrivate { GValue *properties; GList *changed_properties; GSource *changed_properties_idle_source; GMainContext *context; GMutex lock; }; static void _gca_diagnostics_skeleton_handle_method_call ( GDBusConnection *connection G_GNUC_UNUSED, const gchar *sender G_GNUC_UNUSED, const gchar *object_path G_GNUC_UNUSED, const gchar *interface_name, const gchar *method_name, GVariant *parameters, GDBusMethodInvocation *invocation, gpointer user_data) { GcaDiagnosticsSkeleton *skeleton = GCA_DIAGNOSTICS_SKELETON (user_data); _ExtendedGDBusMethodInfo *info; GVariantIter iter; GVariant *child; GValue *paramv; guint num_params; guint num_extra; guint n; guint signal_id; GValue return_value = G_VALUE_INIT; info = (_ExtendedGDBusMethodInfo *) g_dbus_method_invocation_get_method_info (invocation); g_assert (info != NULL); num_params = g_variant_n_children (parameters); num_extra = info->pass_fdlist ? 3 : 2; paramv = g_new0 (GValue, num_params + num_extra); n = 0; g_value_init (&paramv[n], GCA_TYPE_DIAGNOSTICS); g_value_set_object (&paramv[n++], skeleton); g_value_init (&paramv[n], G_TYPE_DBUS_METHOD_INVOCATION); g_value_set_object (&paramv[n++], invocation); if (info->pass_fdlist) { #ifdef G_OS_UNIX g_value_init (&paramv[n], G_TYPE_UNIX_FD_LIST); g_value_set_object (&paramv[n++], g_dbus_message_get_unix_fd_list (g_dbus_method_invocation_get_message (invocation))); #else g_assert_not_reached (); #endif } g_variant_iter_init (&iter, parameters); while ((child = g_variant_iter_next_value (&iter)) != NULL) { _ExtendedGDBusArgInfo *arg_info = (_ExtendedGDBusArgInfo *) info->parent_struct.in_args[n - num_extra]; if (arg_info->use_gvariant) { g_value_init (&paramv[n], G_TYPE_VARIANT); g_value_set_variant (&paramv[n], child); n++; } else g_dbus_gvariant_to_gvalue (child, &paramv[n++]); g_variant_unref (child); } signal_id = g_signal_lookup (info->signal_name, GCA_TYPE_DIAGNOSTICS); g_value_init (&return_value, G_TYPE_BOOLEAN); g_signal_emitv (paramv, signal_id, 0, &return_value); if (!g_value_get_boolean (&return_value)) g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_UNKNOWN_METHOD, "Method %s is not implemented on interface %s", method_name, interface_name); g_value_unset (&return_value); for (n = 0; n < num_params + num_extra; n++) g_value_unset (&paramv[n]); g_free (paramv); } static GVariant * _gca_diagnostics_skeleton_handle_get_property ( GDBusConnection *connection G_GNUC_UNUSED, const gchar *sender G_GNUC_UNUSED, const gchar *object_path G_GNUC_UNUSED, const gchar *interface_name G_GNUC_UNUSED, const gchar *property_name, GError **error, gpointer user_data) { GcaDiagnosticsSkeleton *skeleton = GCA_DIAGNOSTICS_SKELETON (user_data); GValue value = G_VALUE_INIT; GParamSpec *pspec; _ExtendedGDBusPropertyInfo *info; GVariant *ret; ret = NULL; info = (_ExtendedGDBusPropertyInfo *) g_dbus_interface_info_lookup_property ((GDBusInterfaceInfo *) &_gca_diagnostics_interface_info.parent_struct, property_name); g_assert (info != NULL); pspec = g_object_class_find_property (G_OBJECT_GET_CLASS (skeleton), info->hyphen_name); if (pspec == NULL) { g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS, "No property with name %s", property_name); } else { g_value_init (&value, pspec->value_type); g_object_get_property (G_OBJECT (skeleton), info->hyphen_name, &value); ret = g_dbus_gvalue_to_gvariant (&value, G_VARIANT_TYPE (info->parent_struct.signature)); g_value_unset (&value); } return ret; } static gboolean _gca_diagnostics_skeleton_handle_set_property ( GDBusConnection *connection G_GNUC_UNUSED, const gchar *sender G_GNUC_UNUSED, const gchar *object_path G_GNUC_UNUSED, const gchar *interface_name G_GNUC_UNUSED, const gchar *property_name, GVariant *variant, GError **error, gpointer user_data) { GcaDiagnosticsSkeleton *skeleton = GCA_DIAGNOSTICS_SKELETON (user_data); GValue value = G_VALUE_INIT; GParamSpec *pspec; _ExtendedGDBusPropertyInfo *info; gboolean ret; ret = FALSE; info = (_ExtendedGDBusPropertyInfo *) g_dbus_interface_info_lookup_property ((GDBusInterfaceInfo *) &_gca_diagnostics_interface_info.parent_struct, property_name); g_assert (info != NULL); pspec = g_object_class_find_property (G_OBJECT_GET_CLASS (skeleton), info->hyphen_name); if (pspec == NULL) { g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS, "No property with name %s", property_name); } else { if (info->use_gvariant) g_value_set_variant (&value, variant); else g_dbus_gvariant_to_gvalue (variant, &value); g_object_set_property (G_OBJECT (skeleton), info->hyphen_name, &value); g_value_unset (&value); ret = TRUE; } return ret; } static const GDBusInterfaceVTable _gca_diagnostics_skeleton_vtable = { _gca_diagnostics_skeleton_handle_method_call, _gca_diagnostics_skeleton_handle_get_property, _gca_diagnostics_skeleton_handle_set_property, {NULL} }; static GDBusInterfaceInfo * gca_diagnostics_skeleton_dbus_interface_get_info (GDBusInterfaceSkeleton *skeleton G_GNUC_UNUSED) { return gca_diagnostics_interface_info (); } static GDBusInterfaceVTable * gca_diagnostics_skeleton_dbus_interface_get_vtable (GDBusInterfaceSkeleton *skeleton G_GNUC_UNUSED) { return (GDBusInterfaceVTable *) &_gca_diagnostics_skeleton_vtable; } static GVariant * gca_diagnostics_skeleton_dbus_interface_get_properties (GDBusInterfaceSkeleton *_skeleton) { GcaDiagnosticsSkeleton *skeleton = GCA_DIAGNOSTICS_SKELETON (_skeleton); GVariantBuilder builder; guint n; g_variant_builder_init (&builder, G_VARIANT_TYPE ("a{sv}")); if (_gca_diagnostics_interface_info.parent_struct.properties == NULL) goto out; for (n = 0; _gca_diagnostics_interface_info.parent_struct.properties[n] != NULL; n++) { GDBusPropertyInfo *info = _gca_diagnostics_interface_info.parent_struct.properties[n]; if (info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE) { GVariant *value; value = _gca_diagnostics_skeleton_handle_get_property (g_dbus_interface_skeleton_get_connection (G_DBUS_INTERFACE_SKELETON (skeleton)), NULL, g_dbus_interface_skeleton_get_object_path (G_DBUS_INTERFACE_SKELETON (skeleton)), "org.gnome.CodeAssist.v1.Diagnostics", info->name, NULL, skeleton); if (value != NULL) { g_variant_take_ref (value); g_variant_builder_add (&builder, "{sv}", info->name, value); g_variant_unref (value); } } } out: return g_variant_builder_end (&builder); } static void gca_diagnostics_skeleton_dbus_interface_flush (GDBusInterfaceSkeleton *_skeleton) { } static void gca_diagnostics_skeleton_iface_init (GcaDiagnosticsIface *iface); #if GLIB_VERSION_MAX_ALLOWED >= GLIB_VERSION_2_38 G_DEFINE_TYPE_WITH_CODE (GcaDiagnosticsSkeleton, gca_diagnostics_skeleton, G_TYPE_DBUS_INTERFACE_SKELETON, G_ADD_PRIVATE (GcaDiagnosticsSkeleton) G_IMPLEMENT_INTERFACE (GCA_TYPE_DIAGNOSTICS, gca_diagnostics_skeleton_iface_init)); #else G_DEFINE_TYPE_WITH_CODE (GcaDiagnosticsSkeleton, gca_diagnostics_skeleton, G_TYPE_DBUS_INTERFACE_SKELETON, G_IMPLEMENT_INTERFACE (GCA_TYPE_DIAGNOSTICS, gca_diagnostics_skeleton_iface_init)); #endif static void gca_diagnostics_skeleton_finalize (GObject *object) { GcaDiagnosticsSkeleton *skeleton = GCA_DIAGNOSTICS_SKELETON (object); g_list_free_full (skeleton->priv->changed_properties, (GDestroyNotify) _changed_property_free); if (skeleton->priv->changed_properties_idle_source != NULL) g_source_destroy (skeleton->priv->changed_properties_idle_source); g_main_context_unref (skeleton->priv->context); g_mutex_clear (&skeleton->priv->lock); G_OBJECT_CLASS (gca_diagnostics_skeleton_parent_class)->finalize (object); } static void gca_diagnostics_skeleton_init (GcaDiagnosticsSkeleton *skeleton) { #if GLIB_VERSION_MAX_ALLOWED >= GLIB_VERSION_2_38 skeleton->priv = gca_diagnostics_skeleton_get_instance_private (skeleton); #else skeleton->priv = G_TYPE_INSTANCE_GET_PRIVATE (skeleton, GCA_TYPE_DIAGNOSTICS_SKELETON, GcaDiagnosticsSkeletonPrivate); #endif g_mutex_init (&skeleton->priv->lock); skeleton->priv->context = g_main_context_ref_thread_default (); } static void gca_diagnostics_skeleton_class_init (GcaDiagnosticsSkeletonClass *klass) { GObjectClass *gobject_class; GDBusInterfaceSkeletonClass *skeleton_class; gobject_class = G_OBJECT_CLASS (klass); gobject_class->finalize = gca_diagnostics_skeleton_finalize; skeleton_class = G_DBUS_INTERFACE_SKELETON_CLASS (klass); skeleton_class->get_info = gca_diagnostics_skeleton_dbus_interface_get_info; skeleton_class->get_properties = gca_diagnostics_skeleton_dbus_interface_get_properties; skeleton_class->flush = gca_diagnostics_skeleton_dbus_interface_flush; skeleton_class->get_vtable = gca_diagnostics_skeleton_dbus_interface_get_vtable; #if GLIB_VERSION_MAX_ALLOWED < GLIB_VERSION_2_38 g_type_class_add_private (klass, sizeof (GcaDiagnosticsSkeletonPrivate)); #endif } static void gca_diagnostics_skeleton_iface_init (GcaDiagnosticsIface *iface) { } /** * gca_diagnostics_skeleton_new: * * Creates a skeleton object for the D-Bus interface <link linkend="gdbus-interface-org-gnome-CodeAssist-v1-Diagnostics.top_of_page">org.gnome.CodeAssist.v1.Diagnostics</link>. * * Returns: (transfer full) (type GcaDiagnosticsSkeleton): The skeleton object. */ GcaDiagnostics * gca_diagnostics_skeleton_new (void) { return GCA_DIAGNOSTICS (g_object_new (GCA_TYPE_DIAGNOSTICS_SKELETON, NULL)); }
gpl-3.0
aurelien-git/C
nagios_check/check_ping.c
4
18172
/***************************************************************************** * * Nagios check_ping plugin * * License: GPL * Copyright (c) 2000-2014 Nagios Plugins Development Team * * Description: * * This file contains the check_ping plugin * * Use the ping program to check connection statistics for a remote host. * * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * *****************************************************************************/ const char *progname = "check_ping"; const char *copyright = "2000-2014"; const char *email = "devel@nagios-plugins.org"; #include <stdio.h> // man stdio I/O library functions #include <limits.h> // determines various properties of various variables #include <stdlib.h> // environment variable - standard library definitions #include <string.h> // perform string operation on null-terminated strings #include <ctype.h> // convert uppercase or lowercase #include "common.h" //#include "netutils.h" //#include "popen.h" //#include "utils.h" #define WARN_DUPLICATES "DUPLICATES FOUND! " #define UNKNOWN_TRIP_TIME -1.0 /* -1 seconds */ enum { UNKNOWN_PACKET_LOSS = 200, /* 200% */ DEFAULT_MAX_PACKETS = 5 /* default no. of ICMP ECHO packets */ }; int process_arguments (int, char **); int get_threshold (char *, float *, int *); int validate_arguments (void); int run_ping (const char *cmd, const char *addr); int error_scan (char buf[MAX_INPUT_BUFFER], const char *addr); void print_usage (void); void print_help (void); int display_html = FALSE; int wpl = UNKNOWN_PACKET_LOSS; int cpl = UNKNOWN_PACKET_LOSS; float wrta = UNKNOWN_TRIP_TIME; float crta = UNKNOWN_TRIP_TIME; char **addresses = NULL; int n_addresses = 0; int max_addr = 1; int max_packets = -1; int verbose = 0; float rta = UNKNOWN_TRIP_TIME; int pl = UNKNOWN_PACKET_LOSS; char *warn_text; int main (int argc, char **argv) { char *cmd = NULL; char *rawcmd = NULL; int result = STATE_UNKNOWN; int this_result = STATE_UNKNOWN; int i; setlocale (LC_ALL, ""); setlocale (LC_NUMERIC, "C"); bindtextdomain (PACKAGE, LOCALEDIR); textdomain (PACKAGE); addresses = malloc (sizeof(char*) * max_addr); addresses[0] = NULL; /* Parse extra opts if any */ argv=np_extra_opts (&argc, argv, progname); if (process_arguments (argc, argv) == ERROR) usage4 (_("Could not parse arguments")); /* Set signal handling and alarm */ if (signal (SIGALRM, popen_timeout_alarm_handler) == SIG_ERR) { usage4 (_("Cannot catch SIGALRM")); } /* If ./configure finds ping has timeout values, set plugin alarm slightly * higher so that we can use response from command line ping */ #if defined(PING_PACKETS_FIRST) && defined(PING_HAS_TIMEOUT) alarm (timeout_interval + 1); #else alarm (timeout_interval); #endif for (i = 0 ; i < n_addresses ; i++) { #ifdef PING6_COMMAND if (address_family != AF_INET && is_inet6_addr(addresses[i])) rawcmd = strdup(PING6_COMMAND); else rawcmd = strdup(PING_COMMAND); #else rawcmd = strdup(PING_COMMAND); #endif /* does the host address of number of packets argument come first? */ #ifdef PING_PACKETS_FIRST # ifdef PING_HAS_TIMEOUT xasprintf (&cmd, rawcmd, timeout_interval, max_packets, addresses[i]); # else xasprintf (&cmd, rawcmd, max_packets, addresses[i]); # endif #else xasprintf (&cmd, rawcmd, addresses[i], max_packets); #endif if (verbose >= 2) printf ("CMD: %s\n", cmd); /* run the command */ this_result = run_ping (cmd, addresses[i]); if (pl == UNKNOWN_PACKET_LOSS || rta < 0.0) { printf ("%s\n", cmd); die (STATE_UNKNOWN, _("CRITICAL - Could not interpret output from ping command\n")); } if (pl >= cpl || rta >= crta || rta < 0) this_result = STATE_CRITICAL; else if (pl >= wpl || rta >= wrta) this_result = STATE_WARNING; else if (pl >= 0 && rta >= 0) this_result = max_state (STATE_OK, this_result); if (n_addresses > 1 && this_result != STATE_UNKNOWN) die (STATE_OK, "%s is alive\n", addresses[i]); if (display_html == TRUE) printf ("<A HREF='%s/traceroute.cgi?%s'>", CGIURL, addresses[i]); if (pl == 100) printf (_("PING %s - %sPacket loss = %d%%"), state_text (this_result), warn_text, pl); else printf (_("PING %s - %sPacket loss = %d%%, RTA = %2.2f ms"), state_text (this_result), warn_text, pl, rta); if (display_html == TRUE) printf ("</A>"); /* Print performance data */ printf("|%s", fperfdata ("rta", (double) rta, "ms", wrta>0?TRUE:FALSE, wrta, crta>0?TRUE:FALSE, crta, TRUE, 0, FALSE, 0)); printf(" %s\n", perfdata ("pl", (long) pl, "%", wpl>0?TRUE:FALSE, wpl, cpl>0?TRUE:FALSE, cpl, TRUE, 0, FALSE, 0)); if (verbose >= 2) printf ("%f:%d%% %f:%d%%\n", wrta, wpl, crta, cpl); result = max_state (result, this_result); free (rawcmd); free (cmd); } return result; } /* process command-line arguments */ int process_arguments (int argc, char **argv) { int c = 1; char *ptr; int option = 0; static struct option longopts[] = { STD_LONG_OPTS, {"packets", required_argument, 0, 'p'}, {"nohtml", no_argument, 0, 'n'}, {"link", no_argument, 0, 'L'}, {"use-ipv4", no_argument, 0, '4'}, {"use-ipv6", no_argument, 0, '6'}, {0, 0, 0, 0} }; if (argc < 2) return ERROR; for (c = 1; c < argc; c++) { if (strcmp ("-to", argv[c]) == 0) strcpy (argv[c], "-t"); if (strcmp ("-nohtml", argv[c]) == 0) strcpy (argv[c], "-n"); } while (1) { c = getopt_long (argc, argv, "VvhnL46t:c:w:H:p:", longopts, &option); if (c == -1 || c == EOF) break; switch (c) { case '?': /* usage */ usage5 (); case 'h': /* help */ print_help (); exit (STATE_OK); break; case 'V': /* version */ print_revision (progname, NP_VERSION); exit (STATE_OK); break; case 't': /* timeout period */ timeout_interval = parse_timeout_string(optarg); break; case 'v': /* verbose mode */ verbose++; break; case '4': /* IPv4 only */ address_family = AF_INET; break; case '6': /* IPv6 only */ #ifdef USE_IPV6 address_family = AF_INET6; #else usage (_("IPv6 support not available\n")); #endif break; case 'H': /* hostname */ ptr=optarg; while (1) { n_addresses++; if (n_addresses > max_addr) { max_addr *= 2; addresses = realloc (addresses, sizeof(char*) * max_addr); if (addresses == NULL) die (STATE_UNKNOWN, _("Could not realloc() addresses\n")); } addresses[n_addresses-1] = ptr; if ((ptr = index (ptr, ','))) { strcpy (ptr, ""); ptr += sizeof(char); } else { break; } } break; case 'p': /* number of packets to send */ if (is_intnonneg (optarg)) max_packets = atoi (optarg); else usage2 (_("<max_packets> (%s) must be a non-negative number\n"), optarg); break; case 'n': /* no HTML */ display_html = FALSE; break; case 'L': /* show HTML */ display_html = TRUE; break; case 'c': get_threshold (optarg, &crta, &cpl); break; case 'w': get_threshold (optarg, &wrta, &wpl); break; } } c = optind; if (c == argc) return validate_arguments (); if (addresses[0] == NULL) { if (is_host (argv[c]) == FALSE) { usage2 (_("Invalid hostname/address"), argv[c]); } else { addresses[0] = argv[c++]; n_addresses++; if (c == argc) return validate_arguments (); } } if (wpl == UNKNOWN_PACKET_LOSS) { if (is_intpercent (argv[c]) == FALSE) { printf (_("<wpl> (%s) must be an integer percentage\n"), argv[c]); return ERROR; } else { wpl = atoi (argv[c++]); if (c == argc) return validate_arguments (); } } if (cpl == UNKNOWN_PACKET_LOSS) { if (is_intpercent (argv[c]) == FALSE) { printf (_("<cpl> (%s) must be an integer percentage\n"), argv[c]); return ERROR; } else { cpl = atoi (argv[c++]); if (c == argc) return validate_arguments (); } } if (wrta < 0.0) { if (is_negative (argv[c])) { printf (_("<wrta> (%s) must be a non-negative number\n"), argv[c]); return ERROR; } else { wrta = atof (argv[c++]); if (c == argc) return validate_arguments (); } } if (crta < 0.0) { if (is_negative (argv[c])) { printf (_("<crta> (%s) must be a non-negative number\n"), argv[c]); return ERROR; } else { crta = atof (argv[c++]); if (c == argc) return validate_arguments (); } } if (max_packets == -1) { if (is_intnonneg (argv[c])) { max_packets = atoi (argv[c++]); } else { printf (_("<max_packets> (%s) must be a non-negative number\n"), argv[c]); return ERROR; } } return validate_arguments (); } int get_threshold (char *arg, float *trta, int *tpl) { if (is_intnonneg (arg) && sscanf (arg, "%f", trta) == 1) return OK; else if (strpbrk (arg, ",:") && strstr (arg, "%") && sscanf (arg, "%f%*[:,]%d%%", trta, tpl) == 2) return OK; else if (strstr (arg, "%") && sscanf (arg, "%d%%", tpl) == 1) return OK; usage2 (_("%s: Warning threshold must be integer or percentage!\n\n"), arg); return STATE_UNKNOWN; } int validate_arguments () { float max_seconds; int i; if (wrta < 0.0) { printf (_("<wrta> was not set\n")); return ERROR; } else if (crta < 0.0) { printf (_("<crta> was not set\n")); return ERROR; } else if (wpl == UNKNOWN_PACKET_LOSS) { printf (_("<wpl> was not set\n")); return ERROR; } else if (cpl == UNKNOWN_PACKET_LOSS) { printf (_("<cpl> was not set\n")); return ERROR; } else if (wrta > crta) { printf (_("<wrta> (%f) cannot be larger than <crta> (%f)\n"), wrta, crta); return ERROR; } else if (wpl > cpl) { printf (_("<wpl> (%d) cannot be larger than <cpl> (%d)\n"), wpl, cpl); return ERROR; } if (max_packets == -1) max_packets = DEFAULT_MAX_PACKETS; max_seconds = crta / 1000.0 * max_packets + max_packets; if (max_seconds > timeout_interval) timeout_interval = (int)max_seconds; for (i=0; i<n_addresses; i++) { if (is_host(addresses[i]) == FALSE) usage2 (_("Invalid hostname/address"), addresses[i]); } if (n_addresses == 0) { usage (_("You must specify a server address or host name")); } return OK; } int run_ping (const char *cmd, const char *addr) { char buf[MAX_INPUT_BUFFER]; int result = STATE_UNKNOWN; int match; if ((child_process = spopen (cmd)) == NULL) die (STATE_UNKNOWN, _("Could not open pipe: %s\n"), cmd); child_stderr = fdopen (child_stderr_array[fileno (child_process)], "r"); if (child_stderr == NULL) printf (_("Cannot open stderr for %s\n"), cmd); while (fgets (buf, MAX_INPUT_BUFFER - 1, child_process)) { if (verbose >= 3) printf("Output: %s", buf); result = max_state (result, error_scan (buf, addr)); /* get the percent loss statistics */ match = 0; if((sscanf(buf,"%*d packets transmitted, %*d packets received, +%*d errors, %d%% packet loss%n",&pl,&match) && match) || (sscanf(buf,"%*d packets transmitted, %*d packets received, +%*d duplicates, %d%% packet loss%n",&pl,&match) && match) || (sscanf(buf,"%*d packets transmitted, %*d received, +%*d duplicates, %d%% packet loss%n",&pl,&match) && match) || (sscanf(buf,"%*d packets transmitted, %*d packets received, %d%% packet loss%n",&pl,&match) && match) || (sscanf(buf,"%*d packets transmitted, %*d packets received, %d%% loss, time%n",&pl,&match) && match) || (sscanf(buf,"%*d packets transmitted, %*d received, %d%% loss, time%n",&pl,&match) && match) || (sscanf(buf,"%*d packets transmitted, %*d received, %d%% packet loss, time%n",&pl,&match) && match) || (sscanf(buf,"%*d packets transmitted, %*d received, +%*d errors, %d%% packet loss%n",&pl,&match) && match) || (sscanf(buf,"%*d packets transmitted %*d received, +%*d errors, %d%% packet loss%n",&pl,&match) && match) || (sscanf(buf,"%*[^(](%d%% %*[^)])%n",&pl,&match) && match) ) continue; /* get the round trip average */ else if((sscanf(buf,"round-trip min/avg/max = %*f/%f/%*f%n",&rta,&match) && match) || (sscanf(buf,"round-trip min/avg/max/mdev = %*f/%f/%*f/%*f%n",&rta,&match) && match) || (sscanf(buf,"round-trip min/avg/max/sdev = %*f/%f/%*f/%*f%n",&rta,&match) && match) || (sscanf(buf,"round-trip min/avg/max/stddev = %*f/%f/%*f/%*f%n",&rta,&match) && match) || (sscanf(buf,"round-trip min/avg/max/std-dev = %*f/%f/%*f/%*f%n",&rta,&match) && match) || (sscanf(buf,"round-trip (ms) min/avg/max = %*f/%f/%*f%n",&rta,&match) && match) || (sscanf(buf,"round-trip (ms) min/avg/max/stddev = %*f/%f/%*f/%*f%n",&rta,&match) && match) || (sscanf(buf,"rtt min/avg/max/mdev = %*f/%f/%*f/%*f ms%n",&rta,&match) && match) || (sscanf(buf, "%*[^=] = %*fms, %*[^=] = %*fms, %*[^=] = %fms%n", &rta, &match) && match) ) continue; } /* this is needed because there is no rta if all packets are lost */ if (pl == 100) rta = crta; /* check stderr, setting at least WARNING if there is output here */ /* Add warning into warn_text */ while (fgets (buf, MAX_INPUT_BUFFER - 1, child_stderr)) { if ( ! strstr(buf,"WARNING - no SO_TIMESTAMP support, falling back to SIOCGSTAMP") && ! strstr(buf,"Warning: time of day goes back") ) { if (verbose >= 3) { printf("Got stderr: %s", buf); } if ((result=error_scan(buf, addr)) == STATE_OK) { result = STATE_WARNING; if (warn_text == NULL) { warn_text = strdup(_("System call sent warnings to stderr ")); } else { xasprintf(&warn_text, "%s %s", warn_text, _("System call sent warnings to stderr ")); } } } } (void) fclose (child_stderr); spclose (child_process); if (warn_text == NULL) warn_text = strdup(""); return result; } int error_scan (char buf[MAX_INPUT_BUFFER], const char *addr) { if (strstr (buf, "Network is unreachable") || strstr (buf, "Destination Net Unreachable") ) die (STATE_CRITICAL, _("CRITICAL - Network Unreachable (%s)\n"), addr); else if (strstr (buf, "Destination Host Unreachable")) die (STATE_CRITICAL, _("CRITICAL - Host Unreachable (%s)\n"), addr); else if (strstr (buf, "Destination Port Unreachable")) die (STATE_CRITICAL, _("CRITICAL - Bogus ICMP: Port Unreachable (%s)\n"), addr); else if (strstr (buf, "Destination Protocol Unreachable")) die (STATE_CRITICAL, _("CRITICAL - Bogus ICMP: Protocol Unreachable (%s)\n"), addr); else if (strstr (buf, "Destination Net Prohibited")) die (STATE_CRITICAL, _("CRITICAL - Network Prohibited (%s)\n"), addr); else if (strstr (buf, "Destination Host Prohibited")) die (STATE_CRITICAL, _("CRITICAL - Host Prohibited (%s)\n"), addr); else if (strstr (buf, "Packet filtered")) die (STATE_CRITICAL, _("CRITICAL - Packet Filtered (%s)\n"), addr); else if (strstr (buf, "unknown host" )) die (STATE_CRITICAL, _("CRITICAL - Host not found (%s)\n"), addr); else if (strstr (buf, "Time to live exceeded")) die (STATE_CRITICAL, _("CRITICAL - Time to live exceeded (%s)\n"), addr); else if (strstr (buf, "Destination unreachable: ")) die (STATE_CRITICAL, _("CRITICAL - Destination Unreachable (%s)\n"), addr); if (strstr (buf, "(DUP!)") || strstr (buf, "DUPLICATES FOUND")) { if (warn_text == NULL) warn_text = strdup (_(WARN_DUPLICATES)); else if (! strstr (warn_text, _(WARN_DUPLICATES)) && xasprintf (&warn_text, "%s %s", warn_text, _(WARN_DUPLICATES)) == -1) die (STATE_UNKNOWN, _("Unable to realloc warn_text\n")); return (STATE_WARNING); } return (STATE_OK); } void print_help (void) { print_revision (progname, NP_VERSION); printf ("Copyright (c) 1999 Ethan Galstad <nagios@nagios.org>\n"); printf (COPYRIGHT, copyright, email); printf (_("Use ping to check connection statistics for a remote host.")); printf ("\n\n"); print_usage (); printf (UT_HELP_VRSN); printf (UT_EXTRA_OPTS); printf (UT_IPv46); printf (" %s\n", "-H, --hostname=HOST"); printf (" %s\n", _("host to ping")); printf (" %s\n", "-w, --warning=THRESHOLD"); printf (" %s\n", _("warning threshold pair")); printf (" %s\n", "-c, --critical=THRESHOLD"); printf (" %s\n", _("critical threshold pair")); printf (" %s\n", "-p, --packets=INTEGER"); printf (" %s ", _("number of ICMP ECHO packets to send")); printf (_("(Default: %d)\n"), DEFAULT_MAX_PACKETS); printf (" %s\n", "-L, --link"); printf (" %s\n", _("show HTML in the plugin output (obsoleted by urlize)")); printf (UT_CONN_TIMEOUT, DEFAULT_SOCKET_TIMEOUT); printf ("\n"); printf ("%s\n", _("THRESHOLD is <rta>,<pl>% where <rta> is the round trip average travel")); printf ("%s\n", _("time (ms) which triggers a WARNING or CRITICAL state, and <pl> is the")); printf ("%s\n", _("percentage of packet loss to trigger an alarm state.")); printf ("\n"); printf ("%s\n", _("This plugin uses the ping command to probe the specified host for packet loss")); printf ("%s\n", _("(percentage) and round trip average (milliseconds). It can produce HTML output")); printf ("%s\n", _("linking to a traceroute CGI contributed by Ian Cass. The CGI can be found in")); printf ("%s\n", _("the contrib area of the downloads section at http://www.nagios.org/")); printf (UT_SUPPORT); } void print_usage (void) { printf ("%s\n", _("Usage:")); printf ("%s -H <host_address> -w <wrta>,<wpl>%% -c <crta>,<cpl>%%\n", progname); printf (" [-p packets] [-t timeout] [-4|-6]\n"); }
gpl-3.0
briansorahan/libchuck
src/chuck_utils.cpp
4
2117
/*---------------------------------------------------------------------------- ChucK Concurrent, On-the-fly Audio Programming Language Compiler and Virtual Machine Copyright (c) 2004 Ge Wang and Perry R. Cook. All rights reserved. http://chuck.stanford.edu/ http://chuck.cs.princeton.edu/ 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 U.S.A. -----------------------------------------------------------------------------*/ //----------------------------------------------------------------------------- // file: chuck_utils.cpp // desc: common utils, adapted from Tiger Compiler Andrew Appel // // author: Ge Wang (ge@ccrma.stanford.edu | gewang@cs.princeton.edu) // adapted from: Andrew Appel (appel@cs.princeton.edu) // date: Summer 2002 //----------------------------------------------------------------------------- #include <stdio.h> #include <stdlib.h> #include <string.h> #include "chuck_utils.h" #include "chuck_errmsg.h" void * checked_malloc( int len ) { if( !len ) return NULL; void *p = calloc( len, 1 ); if( !p ) { EM_error2( 0, "out of memory!\n" ); exit( 1 ); } return p; } c_str cc_str( char * s ) { c_str p = (c_str)checked_malloc( strlen(s)+1 ); strcpy( p, s ); return p; } U_boolList U_BoolList( t_CKBOOL head, U_boolList tail ) { U_boolList list = (U_boolList)checked_malloc( sizeof(*list) ); list->head = head; list->tail = tail; return list; }
gpl-3.0
eabatalov/au-linux-kernel-autumn-2017
linux/drivers/gpu/drm/amd/amdgpu/amdgpu_cgs.c
4
30986
/* * Copyright 2015 Advanced Micro Devices, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * */ #include <linux/list.h> #include <linux/slab.h> #include <linux/pci.h> #include <linux/acpi.h> #include <drm/drmP.h> #include <linux/firmware.h> #include <drm/amdgpu_drm.h> #include "amdgpu.h" #include "cgs_linux.h" #include "atom.h" #include "amdgpu_ucode.h" struct amdgpu_cgs_device { struct cgs_device base; struct amdgpu_device *adev; }; #define CGS_FUNC_ADEV \ struct amdgpu_device *adev = \ ((struct amdgpu_cgs_device *)cgs_device)->adev static int amdgpu_cgs_alloc_gpu_mem(struct cgs_device *cgs_device, enum cgs_gpu_mem_type type, uint64_t size, uint64_t align, uint64_t min_offset, uint64_t max_offset, cgs_handle_t *handle) { CGS_FUNC_ADEV; uint16_t flags = 0; int ret = 0; uint32_t domain = 0; struct amdgpu_bo *obj; struct ttm_placement placement; struct ttm_place place; if (min_offset > max_offset) { BUG_ON(1); return -EINVAL; } /* fail if the alignment is not a power of 2 */ if (((align != 1) && (align & (align - 1))) || size == 0 || align == 0) return -EINVAL; switch(type) { case CGS_GPU_MEM_TYPE__VISIBLE_CONTIG_FB: case CGS_GPU_MEM_TYPE__VISIBLE_FB: flags = AMDGPU_GEM_CREATE_CPU_ACCESS_REQUIRED | AMDGPU_GEM_CREATE_VRAM_CONTIGUOUS; domain = AMDGPU_GEM_DOMAIN_VRAM; if (max_offset > adev->mc.real_vram_size) return -EINVAL; place.fpfn = min_offset >> PAGE_SHIFT; place.lpfn = max_offset >> PAGE_SHIFT; place.flags = TTM_PL_FLAG_WC | TTM_PL_FLAG_UNCACHED | TTM_PL_FLAG_VRAM; break; case CGS_GPU_MEM_TYPE__INVISIBLE_CONTIG_FB: case CGS_GPU_MEM_TYPE__INVISIBLE_FB: flags = AMDGPU_GEM_CREATE_NO_CPU_ACCESS | AMDGPU_GEM_CREATE_VRAM_CONTIGUOUS; domain = AMDGPU_GEM_DOMAIN_VRAM; if (adev->mc.visible_vram_size < adev->mc.real_vram_size) { place.fpfn = max(min_offset, adev->mc.visible_vram_size) >> PAGE_SHIFT; place.lpfn = min(max_offset, adev->mc.real_vram_size) >> PAGE_SHIFT; place.flags = TTM_PL_FLAG_WC | TTM_PL_FLAG_UNCACHED | TTM_PL_FLAG_VRAM; } break; case CGS_GPU_MEM_TYPE__GART_CACHEABLE: domain = AMDGPU_GEM_DOMAIN_GTT; place.fpfn = min_offset >> PAGE_SHIFT; place.lpfn = max_offset >> PAGE_SHIFT; place.flags = TTM_PL_FLAG_CACHED | TTM_PL_FLAG_TT; break; case CGS_GPU_MEM_TYPE__GART_WRITECOMBINE: flags = AMDGPU_GEM_CREATE_CPU_GTT_USWC; domain = AMDGPU_GEM_DOMAIN_GTT; place.fpfn = min_offset >> PAGE_SHIFT; place.lpfn = max_offset >> PAGE_SHIFT; place.flags = TTM_PL_FLAG_WC | TTM_PL_FLAG_TT | TTM_PL_FLAG_UNCACHED; break; default: return -EINVAL; } *handle = 0; placement.placement = &place; placement.num_placement = 1; placement.busy_placement = &place; placement.num_busy_placement = 1; ret = amdgpu_bo_create_restricted(adev, size, PAGE_SIZE, true, domain, flags, NULL, &placement, NULL, &obj); if (ret) { DRM_ERROR("(%d) bo create failed\n", ret); return ret; } *handle = (cgs_handle_t)obj; return ret; } static int amdgpu_cgs_free_gpu_mem(struct cgs_device *cgs_device, cgs_handle_t handle) { struct amdgpu_bo *obj = (struct amdgpu_bo *)handle; if (obj) { int r = amdgpu_bo_reserve(obj, true); if (likely(r == 0)) { amdgpu_bo_kunmap(obj); amdgpu_bo_unpin(obj); amdgpu_bo_unreserve(obj); } amdgpu_bo_unref(&obj); } return 0; } static int amdgpu_cgs_gmap_gpu_mem(struct cgs_device *cgs_device, cgs_handle_t handle, uint64_t *mcaddr) { int r; u64 min_offset, max_offset; struct amdgpu_bo *obj = (struct amdgpu_bo *)handle; WARN_ON_ONCE(obj->placement.num_placement > 1); min_offset = obj->placements[0].fpfn << PAGE_SHIFT; max_offset = obj->placements[0].lpfn << PAGE_SHIFT; r = amdgpu_bo_reserve(obj, true); if (unlikely(r != 0)) return r; r = amdgpu_bo_pin_restricted(obj, obj->prefered_domains, min_offset, max_offset, mcaddr); amdgpu_bo_unreserve(obj); return r; } static int amdgpu_cgs_gunmap_gpu_mem(struct cgs_device *cgs_device, cgs_handle_t handle) { int r; struct amdgpu_bo *obj = (struct amdgpu_bo *)handle; r = amdgpu_bo_reserve(obj, true); if (unlikely(r != 0)) return r; r = amdgpu_bo_unpin(obj); amdgpu_bo_unreserve(obj); return r; } static int amdgpu_cgs_kmap_gpu_mem(struct cgs_device *cgs_device, cgs_handle_t handle, void **map) { int r; struct amdgpu_bo *obj = (struct amdgpu_bo *)handle; r = amdgpu_bo_reserve(obj, true); if (unlikely(r != 0)) return r; r = amdgpu_bo_kmap(obj, map); amdgpu_bo_unreserve(obj); return r; } static int amdgpu_cgs_kunmap_gpu_mem(struct cgs_device *cgs_device, cgs_handle_t handle) { int r; struct amdgpu_bo *obj = (struct amdgpu_bo *)handle; r = amdgpu_bo_reserve(obj, true); if (unlikely(r != 0)) return r; amdgpu_bo_kunmap(obj); amdgpu_bo_unreserve(obj); return r; } static uint32_t amdgpu_cgs_read_register(struct cgs_device *cgs_device, unsigned offset) { CGS_FUNC_ADEV; return RREG32(offset); } static void amdgpu_cgs_write_register(struct cgs_device *cgs_device, unsigned offset, uint32_t value) { CGS_FUNC_ADEV; WREG32(offset, value); } static uint32_t amdgpu_cgs_read_ind_register(struct cgs_device *cgs_device, enum cgs_ind_reg space, unsigned index) { CGS_FUNC_ADEV; switch (space) { case CGS_IND_REG__MMIO: return RREG32_IDX(index); case CGS_IND_REG__PCIE: return RREG32_PCIE(index); case CGS_IND_REG__SMC: return RREG32_SMC(index); case CGS_IND_REG__UVD_CTX: return RREG32_UVD_CTX(index); case CGS_IND_REG__DIDT: return RREG32_DIDT(index); case CGS_IND_REG_GC_CAC: return RREG32_GC_CAC(index); case CGS_IND_REG__AUDIO_ENDPT: DRM_ERROR("audio endpt register access not implemented.\n"); return 0; } WARN(1, "Invalid indirect register space"); return 0; } static void amdgpu_cgs_write_ind_register(struct cgs_device *cgs_device, enum cgs_ind_reg space, unsigned index, uint32_t value) { CGS_FUNC_ADEV; switch (space) { case CGS_IND_REG__MMIO: return WREG32_IDX(index, value); case CGS_IND_REG__PCIE: return WREG32_PCIE(index, value); case CGS_IND_REG__SMC: return WREG32_SMC(index, value); case CGS_IND_REG__UVD_CTX: return WREG32_UVD_CTX(index, value); case CGS_IND_REG__DIDT: return WREG32_DIDT(index, value); case CGS_IND_REG_GC_CAC: return WREG32_GC_CAC(index, value); case CGS_IND_REG__AUDIO_ENDPT: DRM_ERROR("audio endpt register access not implemented.\n"); return; } WARN(1, "Invalid indirect register space"); } static int amdgpu_cgs_get_pci_resource(struct cgs_device *cgs_device, enum cgs_resource_type resource_type, uint64_t size, uint64_t offset, uint64_t *resource_base) { CGS_FUNC_ADEV; if (resource_base == NULL) return -EINVAL; switch (resource_type) { case CGS_RESOURCE_TYPE_MMIO: if (adev->rmmio_size == 0) return -ENOENT; if ((offset + size) > adev->rmmio_size) return -EINVAL; *resource_base = adev->rmmio_base; return 0; case CGS_RESOURCE_TYPE_DOORBELL: if (adev->doorbell.size == 0) return -ENOENT; if ((offset + size) > adev->doorbell.size) return -EINVAL; *resource_base = adev->doorbell.base; return 0; case CGS_RESOURCE_TYPE_FB: case CGS_RESOURCE_TYPE_IO: case CGS_RESOURCE_TYPE_ROM: default: return -EINVAL; } } static const void *amdgpu_cgs_atom_get_data_table(struct cgs_device *cgs_device, unsigned table, uint16_t *size, uint8_t *frev, uint8_t *crev) { CGS_FUNC_ADEV; uint16_t data_start; if (amdgpu_atom_parse_data_header( adev->mode_info.atom_context, table, size, frev, crev, &data_start)) return (uint8_t*)adev->mode_info.atom_context->bios + data_start; return NULL; } static int amdgpu_cgs_atom_get_cmd_table_revs(struct cgs_device *cgs_device, unsigned table, uint8_t *frev, uint8_t *crev) { CGS_FUNC_ADEV; if (amdgpu_atom_parse_cmd_header( adev->mode_info.atom_context, table, frev, crev)) return 0; return -EINVAL; } static int amdgpu_cgs_atom_exec_cmd_table(struct cgs_device *cgs_device, unsigned table, void *args) { CGS_FUNC_ADEV; return amdgpu_atom_execute_table( adev->mode_info.atom_context, table, args); } struct cgs_irq_params { unsigned src_id; cgs_irq_source_set_func_t set; cgs_irq_handler_func_t handler; void *private_data; }; static int cgs_set_irq_state(struct amdgpu_device *adev, struct amdgpu_irq_src *src, unsigned type, enum amdgpu_interrupt_state state) { struct cgs_irq_params *irq_params = (struct cgs_irq_params *)src->data; if (!irq_params) return -EINVAL; if (!irq_params->set) return -EINVAL; return irq_params->set(irq_params->private_data, irq_params->src_id, type, (int)state); } static int cgs_process_irq(struct amdgpu_device *adev, struct amdgpu_irq_src *source, struct amdgpu_iv_entry *entry) { struct cgs_irq_params *irq_params = (struct cgs_irq_params *)source->data; if (!irq_params) return -EINVAL; if (!irq_params->handler) return -EINVAL; return irq_params->handler(irq_params->private_data, irq_params->src_id, entry->iv_entry); } static const struct amdgpu_irq_src_funcs cgs_irq_funcs = { .set = cgs_set_irq_state, .process = cgs_process_irq, }; static int amdgpu_cgs_add_irq_source(void *cgs_device, unsigned client_id, unsigned src_id, unsigned num_types, cgs_irq_source_set_func_t set, cgs_irq_handler_func_t handler, void *private_data) { CGS_FUNC_ADEV; int ret = 0; struct cgs_irq_params *irq_params; struct amdgpu_irq_src *source = kzalloc(sizeof(struct amdgpu_irq_src), GFP_KERNEL); if (!source) return -ENOMEM; irq_params = kzalloc(sizeof(struct cgs_irq_params), GFP_KERNEL); if (!irq_params) { kfree(source); return -ENOMEM; } source->num_types = num_types; source->funcs = &cgs_irq_funcs; irq_params->src_id = src_id; irq_params->set = set; irq_params->handler = handler; irq_params->private_data = private_data; source->data = (void *)irq_params; ret = amdgpu_irq_add_id(adev, client_id, src_id, source); if (ret) { kfree(irq_params); kfree(source); } return ret; } static int amdgpu_cgs_irq_get(void *cgs_device, unsigned client_id, unsigned src_id, unsigned type) { CGS_FUNC_ADEV; if (!adev->irq.client[client_id].sources) return -EINVAL; return amdgpu_irq_get(adev, adev->irq.client[client_id].sources[src_id], type); } static int amdgpu_cgs_irq_put(void *cgs_device, unsigned client_id, unsigned src_id, unsigned type) { CGS_FUNC_ADEV; if (!adev->irq.client[client_id].sources) return -EINVAL; return amdgpu_irq_put(adev, adev->irq.client[client_id].sources[src_id], type); } static int amdgpu_cgs_set_clockgating_state(struct cgs_device *cgs_device, enum amd_ip_block_type block_type, enum amd_clockgating_state state) { CGS_FUNC_ADEV; int i, r = -1; for (i = 0; i < adev->num_ip_blocks; i++) { if (!adev->ip_blocks[i].status.valid) continue; if (adev->ip_blocks[i].version->type == block_type) { r = adev->ip_blocks[i].version->funcs->set_clockgating_state( (void *)adev, state); break; } } return r; } static int amdgpu_cgs_set_powergating_state(struct cgs_device *cgs_device, enum amd_ip_block_type block_type, enum amd_powergating_state state) { CGS_FUNC_ADEV; int i, r = -1; for (i = 0; i < adev->num_ip_blocks; i++) { if (!adev->ip_blocks[i].status.valid) continue; if (adev->ip_blocks[i].version->type == block_type) { r = adev->ip_blocks[i].version->funcs->set_powergating_state( (void *)adev, state); break; } } return r; } static uint32_t fw_type_convert(struct cgs_device *cgs_device, uint32_t fw_type) { CGS_FUNC_ADEV; enum AMDGPU_UCODE_ID result = AMDGPU_UCODE_ID_MAXIMUM; switch (fw_type) { case CGS_UCODE_ID_SDMA0: result = AMDGPU_UCODE_ID_SDMA0; break; case CGS_UCODE_ID_SDMA1: result = AMDGPU_UCODE_ID_SDMA1; break; case CGS_UCODE_ID_CP_CE: result = AMDGPU_UCODE_ID_CP_CE; break; case CGS_UCODE_ID_CP_PFP: result = AMDGPU_UCODE_ID_CP_PFP; break; case CGS_UCODE_ID_CP_ME: result = AMDGPU_UCODE_ID_CP_ME; break; case CGS_UCODE_ID_CP_MEC: case CGS_UCODE_ID_CP_MEC_JT1: result = AMDGPU_UCODE_ID_CP_MEC1; break; case CGS_UCODE_ID_CP_MEC_JT2: /* for VI. JT2 should be the same as JT1, because: 1, MEC2 and MEC1 use exactly same FW. 2, JT2 is not pached but JT1 is. */ if (adev->asic_type >= CHIP_TOPAZ) result = AMDGPU_UCODE_ID_CP_MEC1; else result = AMDGPU_UCODE_ID_CP_MEC2; break; case CGS_UCODE_ID_RLC_G: result = AMDGPU_UCODE_ID_RLC_G; break; case CGS_UCODE_ID_STORAGE: result = AMDGPU_UCODE_ID_STORAGE; break; default: DRM_ERROR("Firmware type not supported\n"); } return result; } static int amdgpu_cgs_rel_firmware(struct cgs_device *cgs_device, enum cgs_ucode_id type) { CGS_FUNC_ADEV; if ((CGS_UCODE_ID_SMU == type) || (CGS_UCODE_ID_SMU_SK == type)) { release_firmware(adev->pm.fw); adev->pm.fw = NULL; return 0; } /* cannot release other firmware because they are not created by cgs */ return -EINVAL; } static uint16_t amdgpu_get_firmware_version(struct cgs_device *cgs_device, enum cgs_ucode_id type) { CGS_FUNC_ADEV; uint16_t fw_version = 0; switch (type) { case CGS_UCODE_ID_SDMA0: fw_version = adev->sdma.instance[0].fw_version; break; case CGS_UCODE_ID_SDMA1: fw_version = adev->sdma.instance[1].fw_version; break; case CGS_UCODE_ID_CP_CE: fw_version = adev->gfx.ce_fw_version; break; case CGS_UCODE_ID_CP_PFP: fw_version = adev->gfx.pfp_fw_version; break; case CGS_UCODE_ID_CP_ME: fw_version = adev->gfx.me_fw_version; break; case CGS_UCODE_ID_CP_MEC: fw_version = adev->gfx.mec_fw_version; break; case CGS_UCODE_ID_CP_MEC_JT1: fw_version = adev->gfx.mec_fw_version; break; case CGS_UCODE_ID_CP_MEC_JT2: fw_version = adev->gfx.mec_fw_version; break; case CGS_UCODE_ID_RLC_G: fw_version = adev->gfx.rlc_fw_version; break; case CGS_UCODE_ID_STORAGE: break; default: DRM_ERROR("firmware type %d do not have version\n", type); break; } return fw_version; } static int amdgpu_cgs_enter_safe_mode(struct cgs_device *cgs_device, bool en) { CGS_FUNC_ADEV; if (adev->gfx.rlc.funcs->enter_safe_mode == NULL || adev->gfx.rlc.funcs->exit_safe_mode == NULL) return 0; if (en) adev->gfx.rlc.funcs->enter_safe_mode(adev); else adev->gfx.rlc.funcs->exit_safe_mode(adev); return 0; } static int amdgpu_cgs_get_firmware_info(struct cgs_device *cgs_device, enum cgs_ucode_id type, struct cgs_firmware_info *info) { CGS_FUNC_ADEV; if ((CGS_UCODE_ID_SMU != type) && (CGS_UCODE_ID_SMU_SK != type)) { uint64_t gpu_addr; uint32_t data_size; const struct gfx_firmware_header_v1_0 *header; enum AMDGPU_UCODE_ID id; struct amdgpu_firmware_info *ucode; id = fw_type_convert(cgs_device, type); ucode = &adev->firmware.ucode[id]; if (ucode->fw == NULL) return -EINVAL; gpu_addr = ucode->mc_addr; header = (const struct gfx_firmware_header_v1_0 *)ucode->fw->data; data_size = le32_to_cpu(header->header.ucode_size_bytes); if ((type == CGS_UCODE_ID_CP_MEC_JT1) || (type == CGS_UCODE_ID_CP_MEC_JT2)) { gpu_addr += ALIGN(le32_to_cpu(header->header.ucode_size_bytes), PAGE_SIZE); data_size = le32_to_cpu(header->jt_size) << 2; } info->kptr = ucode->kaddr; info->image_size = data_size; info->mc_addr = gpu_addr; info->version = (uint16_t)le32_to_cpu(header->header.ucode_version); if (CGS_UCODE_ID_CP_MEC == type) info->image_size = (header->jt_offset) << 2; info->fw_version = amdgpu_get_firmware_version(cgs_device, type); info->feature_version = (uint16_t)le32_to_cpu(header->ucode_feature_version); } else { char fw_name[30] = {0}; int err = 0; uint32_t ucode_size; uint32_t ucode_start_address; const uint8_t *src; const struct smc_firmware_header_v1_0 *hdr; const struct common_firmware_header *header; struct amdgpu_firmware_info *ucode = NULL; if (!adev->pm.fw) { switch (adev->asic_type) { case CHIP_TOPAZ: if (((adev->pdev->device == 0x6900) && (adev->pdev->revision == 0x81)) || ((adev->pdev->device == 0x6900) && (adev->pdev->revision == 0x83)) || ((adev->pdev->device == 0x6907) && (adev->pdev->revision == 0x87))) { info->is_kicker = true; strcpy(fw_name, "amdgpu/topaz_k_smc.bin"); } else strcpy(fw_name, "amdgpu/topaz_smc.bin"); break; case CHIP_TONGA: if (((adev->pdev->device == 0x6939) && (adev->pdev->revision == 0xf1)) || ((adev->pdev->device == 0x6938) && (adev->pdev->revision == 0xf1))) { info->is_kicker = true; strcpy(fw_name, "amdgpu/tonga_k_smc.bin"); } else strcpy(fw_name, "amdgpu/tonga_smc.bin"); break; case CHIP_FIJI: strcpy(fw_name, "amdgpu/fiji_smc.bin"); break; case CHIP_POLARIS11: if (type == CGS_UCODE_ID_SMU) { if (((adev->pdev->device == 0x67ef) && ((adev->pdev->revision == 0xe0) || (adev->pdev->revision == 0xe2) || (adev->pdev->revision == 0xe5))) || ((adev->pdev->device == 0x67ff) && ((adev->pdev->revision == 0xcf) || (adev->pdev->revision == 0xef) || (adev->pdev->revision == 0xff)))) { info->is_kicker = true; strcpy(fw_name, "amdgpu/polaris11_k_smc.bin"); } else strcpy(fw_name, "amdgpu/polaris11_smc.bin"); } else if (type == CGS_UCODE_ID_SMU_SK) { strcpy(fw_name, "amdgpu/polaris11_smc_sk.bin"); } break; case CHIP_POLARIS10: if (type == CGS_UCODE_ID_SMU) { if ((adev->pdev->device == 0x67df) && ((adev->pdev->revision == 0xe0) || (adev->pdev->revision == 0xe3) || (adev->pdev->revision == 0xe4) || (adev->pdev->revision == 0xe5) || (adev->pdev->revision == 0xe7) || (adev->pdev->revision == 0xef))) { info->is_kicker = true; strcpy(fw_name, "amdgpu/polaris10_k_smc.bin"); } else strcpy(fw_name, "amdgpu/polaris10_smc.bin"); } else if (type == CGS_UCODE_ID_SMU_SK) { strcpy(fw_name, "amdgpu/polaris10_smc_sk.bin"); } break; case CHIP_POLARIS12: strcpy(fw_name, "amdgpu/polaris12_smc.bin"); break; case CHIP_VEGA10: strcpy(fw_name, "amdgpu/vega10_smc.bin"); break; default: DRM_ERROR("SMC firmware not supported\n"); return -EINVAL; } err = request_firmware(&adev->pm.fw, fw_name, adev->dev); if (err) { DRM_ERROR("Failed to request firmware\n"); return err; } err = amdgpu_ucode_validate(adev->pm.fw); if (err) { DRM_ERROR("Failed to load firmware \"%s\"", fw_name); release_firmware(adev->pm.fw); adev->pm.fw = NULL; return err; } if (adev->firmware.load_type == AMDGPU_FW_LOAD_PSP) { ucode = &adev->firmware.ucode[AMDGPU_UCODE_ID_SMC]; ucode->ucode_id = AMDGPU_UCODE_ID_SMC; ucode->fw = adev->pm.fw; header = (const struct common_firmware_header *)ucode->fw->data; adev->firmware.fw_size += ALIGN(le32_to_cpu(header->ucode_size_bytes), PAGE_SIZE); } } hdr = (const struct smc_firmware_header_v1_0 *) adev->pm.fw->data; amdgpu_ucode_print_smc_hdr(&hdr->header); adev->pm.fw_version = le32_to_cpu(hdr->header.ucode_version); ucode_size = le32_to_cpu(hdr->header.ucode_size_bytes); ucode_start_address = le32_to_cpu(hdr->ucode_start_addr); src = (const uint8_t *)(adev->pm.fw->data + le32_to_cpu(hdr->header.ucode_array_offset_bytes)); info->version = adev->pm.fw_version; info->image_size = ucode_size; info->ucode_start_address = ucode_start_address; info->kptr = (void *)src; } return 0; } static int amdgpu_cgs_is_virtualization_enabled(void *cgs_device) { CGS_FUNC_ADEV; return amdgpu_sriov_vf(adev); } static int amdgpu_cgs_query_system_info(struct cgs_device *cgs_device, struct cgs_system_info *sys_info) { CGS_FUNC_ADEV; if (NULL == sys_info) return -ENODEV; if (sizeof(struct cgs_system_info) != sys_info->size) return -ENODEV; switch (sys_info->info_id) { case CGS_SYSTEM_INFO_ADAPTER_BDF_ID: sys_info->value = adev->pdev->devfn | (adev->pdev->bus->number << 8); break; case CGS_SYSTEM_INFO_PCIE_GEN_INFO: sys_info->value = adev->pm.pcie_gen_mask; break; case CGS_SYSTEM_INFO_PCIE_MLW: sys_info->value = adev->pm.pcie_mlw_mask; break; case CGS_SYSTEM_INFO_PCIE_DEV: sys_info->value = adev->pdev->device; break; case CGS_SYSTEM_INFO_PCIE_REV: sys_info->value = adev->pdev->revision; break; case CGS_SYSTEM_INFO_CG_FLAGS: sys_info->value = adev->cg_flags; break; case CGS_SYSTEM_INFO_PG_FLAGS: sys_info->value = adev->pg_flags; break; case CGS_SYSTEM_INFO_GFX_CU_INFO: sys_info->value = adev->gfx.cu_info.number; break; case CGS_SYSTEM_INFO_GFX_SE_INFO: sys_info->value = adev->gfx.config.max_shader_engines; break; case CGS_SYSTEM_INFO_PCIE_SUB_SYS_ID: sys_info->value = adev->pdev->subsystem_device; break; case CGS_SYSTEM_INFO_PCIE_SUB_SYS_VENDOR_ID: sys_info->value = adev->pdev->subsystem_vendor; break; default: return -ENODEV; } return 0; } static int amdgpu_cgs_get_active_displays_info(struct cgs_device *cgs_device, struct cgs_display_info *info) { CGS_FUNC_ADEV; struct amdgpu_crtc *amdgpu_crtc; struct drm_device *ddev = adev->ddev; struct drm_crtc *crtc; uint32_t line_time_us, vblank_lines; struct cgs_mode_info *mode_info; if (info == NULL) return -EINVAL; mode_info = info->mode_info; if (mode_info) { /* always set the reference clock */ mode_info->ref_clock = adev->clock.spll.reference_freq; } if (adev->mode_info.num_crtc && adev->mode_info.mode_config_initialized) { list_for_each_entry(crtc, &ddev->mode_config.crtc_list, head) { amdgpu_crtc = to_amdgpu_crtc(crtc); if (crtc->enabled) { info->active_display_mask |= (1 << amdgpu_crtc->crtc_id); info->display_count++; } if (mode_info != NULL && crtc->enabled && amdgpu_crtc->enabled && amdgpu_crtc->hw_mode.clock) { line_time_us = (amdgpu_crtc->hw_mode.crtc_htotal * 1000) / amdgpu_crtc->hw_mode.clock; vblank_lines = amdgpu_crtc->hw_mode.crtc_vblank_end - amdgpu_crtc->hw_mode.crtc_vdisplay + (amdgpu_crtc->v_border * 2); mode_info->vblank_time_us = vblank_lines * line_time_us; mode_info->refresh_rate = drm_mode_vrefresh(&amdgpu_crtc->hw_mode); mode_info->ref_clock = adev->clock.spll.reference_freq; mode_info = NULL; } } } return 0; } static int amdgpu_cgs_notify_dpm_enabled(struct cgs_device *cgs_device, bool enabled) { CGS_FUNC_ADEV; adev->pm.dpm_enabled = enabled; return 0; } /** \brief evaluate acpi namespace object, handle or pathname must be valid * \param cgs_device * \param info input/output arguments for the control method * \return status */ #if defined(CONFIG_ACPI) static int amdgpu_cgs_acpi_eval_object(struct cgs_device *cgs_device, struct cgs_acpi_method_info *info) { CGS_FUNC_ADEV; acpi_handle handle; struct acpi_object_list input; struct acpi_buffer output = { ACPI_ALLOCATE_BUFFER, NULL }; union acpi_object *params, *obj; uint8_t name[5] = {'\0'}; struct cgs_acpi_method_argument *argument; uint32_t i, count; acpi_status status; int result; handle = ACPI_HANDLE(&adev->pdev->dev); if (!handle) return -ENODEV; memset(&input, 0, sizeof(struct acpi_object_list)); /* validate input info */ if (info->size != sizeof(struct cgs_acpi_method_info)) return -EINVAL; input.count = info->input_count; if (info->input_count > 0) { if (info->pinput_argument == NULL) return -EINVAL; argument = info->pinput_argument; for (i = 0; i < info->input_count; i++) { if (((argument->type == ACPI_TYPE_STRING) || (argument->type == ACPI_TYPE_BUFFER)) && (argument->pointer == NULL)) return -EINVAL; argument++; } } if (info->output_count > 0) { if (info->poutput_argument == NULL) return -EINVAL; argument = info->poutput_argument; for (i = 0; i < info->output_count; i++) { if (((argument->type == ACPI_TYPE_STRING) || (argument->type == ACPI_TYPE_BUFFER)) && (argument->pointer == NULL)) return -EINVAL; argument++; } } /* The path name passed to acpi_evaluate_object should be null terminated */ if ((info->field & CGS_ACPI_FIELD_METHOD_NAME) != 0) { strncpy(name, (char *)&(info->name), sizeof(uint32_t)); name[4] = '\0'; } /* parse input parameters */ if (input.count > 0) { input.pointer = params = kzalloc(sizeof(union acpi_object) * input.count, GFP_KERNEL); if (params == NULL) return -EINVAL; argument = info->pinput_argument; for (i = 0; i < input.count; i++) { params->type = argument->type; switch (params->type) { case ACPI_TYPE_INTEGER: params->integer.value = argument->value; break; case ACPI_TYPE_STRING: params->string.length = argument->data_length; params->string.pointer = argument->pointer; break; case ACPI_TYPE_BUFFER: params->buffer.length = argument->data_length; params->buffer.pointer = argument->pointer; break; default: break; } params++; argument++; } } /* parse output info */ count = info->output_count; argument = info->poutput_argument; /* evaluate the acpi method */ status = acpi_evaluate_object(handle, name, &input, &output); if (ACPI_FAILURE(status)) { result = -EIO; goto free_input; } /* return the output info */ obj = output.pointer; if (count > 1) { if ((obj->type != ACPI_TYPE_PACKAGE) || (obj->package.count != count)) { result = -EIO; goto free_obj; } params = obj->package.elements; } else params = obj; if (params == NULL) { result = -EIO; goto free_obj; } for (i = 0; i < count; i++) { if (argument->type != params->type) { result = -EIO; goto free_obj; } switch (params->type) { case ACPI_TYPE_INTEGER: argument->value = params->integer.value; break; case ACPI_TYPE_STRING: if ((params->string.length != argument->data_length) || (params->string.pointer == NULL)) { result = -EIO; goto free_obj; } strncpy(argument->pointer, params->string.pointer, params->string.length); break; case ACPI_TYPE_BUFFER: if (params->buffer.pointer == NULL) { result = -EIO; goto free_obj; } memcpy(argument->pointer, params->buffer.pointer, argument->data_length); break; default: break; } argument++; params++; } result = 0; free_obj: kfree(obj); free_input: kfree((void *)input.pointer); return result; } #else static int amdgpu_cgs_acpi_eval_object(struct cgs_device *cgs_device, struct cgs_acpi_method_info *info) { return -EIO; } #endif static int amdgpu_cgs_call_acpi_method(struct cgs_device *cgs_device, uint32_t acpi_method, uint32_t acpi_function, void *pinput, void *poutput, uint32_t output_count, uint32_t input_size, uint32_t output_size) { struct cgs_acpi_method_argument acpi_input[2] = { {0}, {0} }; struct cgs_acpi_method_argument acpi_output = {0}; struct cgs_acpi_method_info info = {0}; acpi_input[0].type = CGS_ACPI_TYPE_INTEGER; acpi_input[0].data_length = sizeof(uint32_t); acpi_input[0].value = acpi_function; acpi_input[1].type = CGS_ACPI_TYPE_BUFFER; acpi_input[1].data_length = input_size; acpi_input[1].pointer = pinput; acpi_output.type = CGS_ACPI_TYPE_BUFFER; acpi_output.data_length = output_size; acpi_output.pointer = poutput; info.size = sizeof(struct cgs_acpi_method_info); info.field = CGS_ACPI_FIELD_METHOD_NAME | CGS_ACPI_FIELD_INPUT_ARGUMENT_COUNT; info.input_count = 2; info.name = acpi_method; info.pinput_argument = acpi_input; info.output_count = output_count; info.poutput_argument = &acpi_output; return amdgpu_cgs_acpi_eval_object(cgs_device, &info); } static const struct cgs_ops amdgpu_cgs_ops = { .alloc_gpu_mem = amdgpu_cgs_alloc_gpu_mem, .free_gpu_mem = amdgpu_cgs_free_gpu_mem, .gmap_gpu_mem = amdgpu_cgs_gmap_gpu_mem, .gunmap_gpu_mem = amdgpu_cgs_gunmap_gpu_mem, .kmap_gpu_mem = amdgpu_cgs_kmap_gpu_mem, .kunmap_gpu_mem = amdgpu_cgs_kunmap_gpu_mem, .read_register = amdgpu_cgs_read_register, .write_register = amdgpu_cgs_write_register, .read_ind_register = amdgpu_cgs_read_ind_register, .write_ind_register = amdgpu_cgs_write_ind_register, .get_pci_resource = amdgpu_cgs_get_pci_resource, .atom_get_data_table = amdgpu_cgs_atom_get_data_table, .atom_get_cmd_table_revs = amdgpu_cgs_atom_get_cmd_table_revs, .atom_exec_cmd_table = amdgpu_cgs_atom_exec_cmd_table, .get_firmware_info = amdgpu_cgs_get_firmware_info, .rel_firmware = amdgpu_cgs_rel_firmware, .set_powergating_state = amdgpu_cgs_set_powergating_state, .set_clockgating_state = amdgpu_cgs_set_clockgating_state, .get_active_displays_info = amdgpu_cgs_get_active_displays_info, .notify_dpm_enabled = amdgpu_cgs_notify_dpm_enabled, .call_acpi_method = amdgpu_cgs_call_acpi_method, .query_system_info = amdgpu_cgs_query_system_info, .is_virtualization_enabled = amdgpu_cgs_is_virtualization_enabled, .enter_safe_mode = amdgpu_cgs_enter_safe_mode, }; static const struct cgs_os_ops amdgpu_cgs_os_ops = { .add_irq_source = amdgpu_cgs_add_irq_source, .irq_get = amdgpu_cgs_irq_get, .irq_put = amdgpu_cgs_irq_put }; struct cgs_device *amdgpu_cgs_create_device(struct amdgpu_device *adev) { struct amdgpu_cgs_device *cgs_device = kmalloc(sizeof(*cgs_device), GFP_KERNEL); if (!cgs_device) { DRM_ERROR("Couldn't allocate CGS device structure\n"); return NULL; } cgs_device->base.ops = &amdgpu_cgs_ops; cgs_device->base.os_ops = &amdgpu_cgs_os_ops; cgs_device->adev = adev; return (struct cgs_device *)cgs_device; } void amdgpu_cgs_destroy_device(struct cgs_device *cgs_device) { kfree(cgs_device); }
gpl-3.0
mwm/libsigrok
src/hardware/ftdi-la/api.c
4
11254
/* * This file is part of the libsigrok project. * * Copyright (C) 2015 Sergey Alirzaev <zl29ah@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <config.h> #include <ftdi.h> #include <libusb.h> #include <libsigrok/libsigrok.h> #include "libsigrok-internal.h" #include "protocol.h" static const uint32_t scanopts[] = { SR_CONF_CONN, }; static const uint32_t devopts[] = { SR_CONF_LOGIC_ANALYZER, SR_CONF_CONTINUOUS, SR_CONF_LIMIT_SAMPLES | SR_CONF_SET, SR_CONF_SAMPLERATE | SR_CONF_GET | SR_CONF_SET | SR_CONF_LIST, SR_CONF_CONN | SR_CONF_GET, }; static const uint64_t samplerates[] = { SR_HZ(3600), SR_MHZ(10), SR_HZ(1), }; static const struct ftdi_chip_desc ft2232h_desc = { .vendor = 0x0403, .product = 0x6010, .samplerate_div = 20, .channel_names = { "ADBUS0", "ADBUS1", "ADBUS2", "ADBUS3", "ADBUS4", "ADBUS5", "ADBUS6", "ADBUS7", /* TODO: BDBUS[0..7] channels. */ NULL } }; static const struct ftdi_chip_desc ft232r_desc = { .vendor = 0x0403, .product = 0x6001, .samplerate_div = 30, .channel_names = { "TXD", "RXD", "RTS#", "CTS#", "DTR#", "DSR#", "DCD#", "RI#", NULL } }; static const struct ftdi_chip_desc *chip_descs[] = { &ft2232h_desc, &ft232r_desc, }; static void scan_device(struct ftdi_context *ftdic, struct libusb_device *dev, GSList **devices) { struct libusb_device_descriptor usb_desc; const struct ftdi_chip_desc *desc; struct dev_context *devc; char *vendor, *model, *serial_num; struct sr_dev_inst *sdi; int rv; libusb_get_device_descriptor(dev, &usb_desc); desc = NULL; for (unsigned long i = 0; i < ARRAY_SIZE(chip_descs); i++) { desc = chip_descs[i]; if (desc->vendor == usb_desc.idVendor && desc->product == usb_desc.idProduct) break; } if (!desc) { sr_spew("Unsupported FTDI device 0x%4x:0x%4x.", usb_desc.idVendor, usb_desc.idProduct); return; } /* Allocate memory for our private device context. */ devc = g_malloc0(sizeof(struct dev_context)); /* Allocate memory for the incoming data. */ devc->data_buf = g_malloc0(DATA_BUF_SIZE); devc->desc = desc; vendor = g_malloc(32); model = g_malloc(32); serial_num = g_malloc(32); rv = ftdi_usb_get_strings(ftdic, dev, vendor, 32, model, 32, serial_num, 32); switch (rv) { case 0: break; case -9: sr_dbg("The device lacks a serial number."); g_free(serial_num); serial_num = NULL; break; default: sr_err("Failed to get the FTDI strings: %d", rv); goto err_free_strings; } sr_dbg("Found an FTDI device: %s.", model); /* Register the device with libsigrok. */ sdi = g_malloc0(sizeof(struct sr_dev_inst)); sdi->status = SR_ST_INACTIVE; sdi->vendor = vendor; sdi->model = model; sdi->serial_num = serial_num; sdi->priv = devc; sdi->connection_id = g_strdup_printf("d:%u/%u", libusb_get_bus_number(dev), libusb_get_device_address(dev)); for (char *const *chan = &(desc->channel_names[0]); *chan; chan++) sr_channel_new(sdi, chan - &(desc->channel_names[0]), SR_CHANNEL_LOGIC, TRUE, *chan); *devices = g_slist_append(*devices, sdi); return; err_free_strings: g_free(vendor); g_free(model); g_free(serial_num); g_free(devc->data_buf); g_free(devc); } static GSList *scan_all(struct ftdi_context *ftdic, GSList *options) { GSList *devices; struct ftdi_device_list *devlist = 0; struct ftdi_device_list *curdev; int ret; (void)options; devices = NULL; ret = ftdi_usb_find_all(ftdic, &devlist, 0, 0); if (ret < 0) { sr_err("Failed to list devices (%d): %s", ret, ftdi_get_error_string(ftdic)); return NULL; } sr_dbg("Number of FTDI devices found: %d", ret); curdev = devlist; while (curdev) { scan_device(ftdic, curdev->dev, &devices); curdev = curdev->next; } ftdi_list_free(&devlist); return devices; } static GSList *scan(struct sr_dev_driver *di, GSList *options) { struct ftdi_context *ftdic; struct sr_config *src; struct sr_usb_dev_inst *usb; const char *conn; GSList *l, *conn_devices; GSList *devices; struct drv_context *drvc; libusb_device **devlist; int i; drvc = di->context; conn = NULL; for (l = options; l; l = l->next) { src = l->data; if (src->key == SR_CONF_CONN) { conn = g_variant_get_string(src->data, NULL); break; } } /* Allocate memory for the FTDI context (ftdic) and initialize it. */ ftdic = ftdi_new(); if (!ftdic) { sr_err("Failed to initialize libftdi."); return NULL; } if (conn) { devices = NULL; libusb_get_device_list(drvc->sr_ctx->libusb_ctx, &devlist); for (i = 0; devlist[i]; i++) { conn_devices = sr_usb_find(drvc->sr_ctx->libusb_ctx, conn); for (l = conn_devices; l; l = l->next) { usb = l->data; if (usb->bus == libusb_get_bus_number(devlist[i]) && usb->address == libusb_get_device_address(devlist[i])) { scan_device(ftdic, devlist[i], &devices); } } } libusb_free_device_list(devlist, 1); } else devices = scan_all(ftdic, options); ftdi_free(ftdic); return std_scan_complete(di, devices); } static void clear_helper(void *priv) { struct dev_context *devc; devc = priv; g_free(devc->data_buf); g_free(devc); } static int dev_clear(const struct sr_dev_driver *di) { return std_dev_clear(di, clear_helper); } static int dev_open(struct sr_dev_inst *sdi) { struct dev_context *devc; int ret = SR_OK; devc = sdi->priv; devc->ftdic = ftdi_new(); if (!devc->ftdic) return SR_ERR; ret = ftdi_usb_open_string(devc->ftdic, sdi->connection_id); if (ret < 0) { /* Log errors, except for -3 ("device not found"). */ if (ret != -3) sr_err("Failed to open device (%d): %s", ret, ftdi_get_error_string(devc->ftdic)); goto err_ftdi_free; } /* Purge RX/TX buffers in the FTDI chip. */ ret = ftdi_usb_purge_buffers(devc->ftdic); if (ret < 0) { sr_err("Failed to purge FTDI RX/TX buffers (%d): %s.", ret, ftdi_get_error_string(devc->ftdic)); goto err_dev_open_close_ftdic; } sr_dbg("FTDI chip buffers purged successfully."); /* Reset the FTDI bitmode. */ ret = ftdi_set_bitmode(devc->ftdic, 0x00, BITMODE_RESET); if (ret < 0) { sr_err("Failed to reset the FTDI chip bitmode (%d): %s.", ret, ftdi_get_error_string(devc->ftdic)); goto err_dev_open_close_ftdic; } sr_dbg("FTDI chip bitmode reset successfully."); ret = ftdi_set_bitmode(devc->ftdic, 0x00, BITMODE_BITBANG); if (ret < 0) { sr_err("Failed to put FTDI chip into bitbang mode (%d): %s.", ret, ftdi_get_error_string(devc->ftdic)); goto err_dev_open_close_ftdic; } sr_dbg("FTDI chip bitbang mode entered successfully."); sdi->status = SR_ST_ACTIVE; return SR_OK; err_dev_open_close_ftdic: ftdi_usb_close(devc->ftdic); err_ftdi_free: ftdi_free(devc->ftdic); return SR_ERR; } static int dev_close(struct sr_dev_inst *sdi) { struct dev_context *devc; devc = sdi->priv; if (devc->ftdic) { ftdi_usb_close(devc->ftdic); ftdi_free(devc->ftdic); devc->ftdic = NULL; } sdi->status = SR_ST_INACTIVE; return SR_OK; } static int config_get(uint32_t key, GVariant **data, const struct sr_dev_inst *sdi, const struct sr_channel_group *cg) { int ret; struct dev_context *devc; struct sr_usb_dev_inst *usb; char str[128]; (void)cg; devc = sdi->priv; ret = SR_OK; switch (key) { case SR_CONF_SAMPLERATE: *data = g_variant_new_uint64(devc->cur_samplerate); break; case SR_CONF_CONN: if (!sdi || !sdi->conn) return SR_ERR_ARG; usb = sdi->conn; snprintf(str, 128, "%d.%d", usb->bus, usb->address); *data = g_variant_new_string(str); break; default: return SR_ERR_NA; } return ret; } static int config_set(uint32_t key, GVariant *data, const struct sr_dev_inst *sdi, const struct sr_channel_group *cg) { int ret; struct dev_context *devc; uint64_t value; (void)cg; if (sdi->status != SR_ST_ACTIVE) return SR_ERR_DEV_CLOSED; devc = sdi->priv; ret = SR_OK; switch (key) { case SR_CONF_LIMIT_MSEC: value = g_variant_get_uint64(data); /* TODO: Implement. */ ret = SR_ERR_NA; break; case SR_CONF_LIMIT_SAMPLES: if (g_variant_get_uint64(data) == 0) return SR_ERR_ARG; devc->limit_samples = g_variant_get_uint64(data); break; case SR_CONF_SAMPLERATE: value = g_variant_get_uint64(data); if (value < 3600) return SR_ERR_SAMPLERATE; devc->cur_samplerate = value; return ftdi_la_set_samplerate(devc); default: ret = SR_ERR_NA; } return ret; } static int config_list(uint32_t key, GVariant **data, const struct sr_dev_inst *sdi, const struct sr_channel_group *cg) { int ret; GVariant *gvar; GVariantBuilder gvb; (void)sdi; (void)cg; ret = SR_OK; switch (key) { case SR_CONF_SCAN_OPTIONS: *data = g_variant_new_fixed_array(G_VARIANT_TYPE_UINT32, scanopts, ARRAY_SIZE(scanopts), sizeof(uint32_t)); break; case SR_CONF_DEVICE_OPTIONS: *data = g_variant_new_fixed_array(G_VARIANT_TYPE_UINT32, devopts, ARRAY_SIZE(devopts), sizeof(uint32_t)); break; case SR_CONF_SAMPLERATE: g_variant_builder_init(&gvb, G_VARIANT_TYPE("a{sv}")); gvar = g_variant_new_fixed_array(G_VARIANT_TYPE("t"), samplerates, ARRAY_SIZE(samplerates), sizeof(uint64_t)); g_variant_builder_add(&gvb, "{sv}", "samplerate-steps", gvar); *data = g_variant_builder_end(&gvb); break; default: return SR_ERR_NA; } return ret; } static int dev_acquisition_start(const struct sr_dev_inst *sdi) { struct dev_context *devc; devc = sdi->priv; if (sdi->status != SR_ST_ACTIVE) return SR_ERR_DEV_CLOSED; if (!devc->ftdic) return SR_ERR_BUG; ftdi_set_bitmode(devc->ftdic, 0, BITMODE_BITBANG); /* Properly reset internal variables before every new acquisition. */ devc->samples_sent = 0; devc->bytes_received = 0; std_session_send_df_header(sdi); /* Hook up a dummy handler to receive data from the device. */ sr_session_source_add(sdi->session, -1, G_IO_IN, 0, ftdi_la_receive_data, (void *)sdi); return SR_OK; } static int dev_acquisition_stop(struct sr_dev_inst *sdi) { if (sdi->status != SR_ST_ACTIVE) return SR_ERR_DEV_CLOSED; sr_dbg("Stopping acquisition."); sr_session_source_remove(sdi->session, -1); std_session_send_df_end(sdi); return SR_OK; } static struct sr_dev_driver ftdi_la_driver_info = { .name = "ftdi-la", .longname = "FTDI LA", .api_version = 1, .init = std_init, .cleanup = std_cleanup, .scan = scan, .dev_list = std_dev_list, .dev_clear = dev_clear, .config_get = config_get, .config_set = config_set, .config_list = config_list, .dev_open = dev_open, .dev_close = dev_close, .dev_acquisition_start = dev_acquisition_start, .dev_acquisition_stop = dev_acquisition_stop, .context = NULL, }; SR_REGISTER_DEV_DRIVER(ftdi_la_driver_info);
gpl-3.0
Banchon/openairinterface5g
openair-cn/OPENAIRHSS/db/db_epc_equipment.c
5
3775
/******************************************************************************* OpenAirInterface Copyright(c) 1999 - 2014 Eurecom OpenAirInterface 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. OpenAirInterface 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 OpenAirInterface.The full GNU General Public License is included in this distribution in the file called "COPYING". If not, see <http://www.gnu.org/licenses/>. Contact Information OpenAirInterface Admin: openair_admin@eurecom.fr OpenAirInterface Tech : openair_tech@eurecom.fr OpenAirInterface Dev : openair4g-devel@eurecom.fr Address : Eurecom, Compus SophiaTech 450, route des chappes, 06451 Biot, France. *******************************************************************************/ #include <pthread.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <string.h> #include <errno.h> #include <error.h> #include <mysql/mysql.h> #include "hss_config.h" #include "db_proto.h" int hss_mysql_query_mmeidentity(const int id_mme_identity, mysql_mme_identity_t *mme_identity_p) { MYSQL_RES *res; MYSQL_ROW row; char query[1000]; if ((db_desc->db_conn == NULL) || (mme_identity_p == NULL)) { return EINVAL; } memset(mme_identity_p, 0, sizeof(mysql_mme_identity_t)); sprintf(query, "SELECT mmehost,mmerealm FROM mmeidentity WHERE " "mmeidentity.idmmeidentity='%d' ", id_mme_identity); DB_DEBUG("Query: %s\n", query); pthread_mutex_lock(&db_desc->db_cs_mutex); if (mysql_query(db_desc->db_conn, query)) { pthread_mutex_unlock(&db_desc->db_cs_mutex); DB_ERROR("Query execution failed: %s\n", mysql_error(db_desc->db_conn)); mysql_thread_end(); return EINVAL; } res = mysql_store_result(db_desc->db_conn); pthread_mutex_unlock(&db_desc->db_cs_mutex); if ((row = mysql_fetch_row(res)) != NULL) { if (row[0] != NULL) { memcpy(mme_identity_p->mme_host, row[0], strlen(row[0])); } else { mme_identity_p->mme_host[0] = '\0'; } if (row[1] != NULL) { memcpy(mme_identity_p->mme_realm, row[1], strlen(row[1])); } else { mme_identity_p->mme_realm[0] = '\0'; } mysql_free_result(res); mysql_thread_end(); return 0; } mysql_free_result(res); mysql_thread_end(); return EINVAL; } int hss_mysql_check_epc_equipment(mysql_mme_identity_t *mme_identity_p) { MYSQL_RES *res; MYSQL_ROW row; char query[1000]; if ((db_desc->db_conn == NULL) || (mme_identity_p == NULL)) { return EINVAL; } sprintf(query, "SELECT idmmeidentity FROM mmeidentity WHERE mmeidentity.mmehost='%s' ", mme_identity_p->mme_host); DB_DEBUG("Query: %s\n", query); pthread_mutex_lock(&db_desc->db_cs_mutex); if (mysql_query(db_desc->db_conn, query)) { pthread_mutex_unlock(&db_desc->db_cs_mutex); DB_ERROR("Query execution failed: %s\n", mysql_error(db_desc->db_conn)); mysql_thread_end(); return EINVAL; } res = mysql_store_result(db_desc->db_conn); pthread_mutex_unlock(&db_desc->db_cs_mutex); if ((row = mysql_fetch_row(res)) != NULL) { mysql_free_result(res); mysql_thread_end(); return 0; } mysql_free_result(res); mysql_thread_end(); return EINVAL; }
gpl-3.0
vbraga/qwsqviewer
an2k/src/copy.c
5
13574
/******************************************************************************* License: This software and/or related materials was developed at the National Institute of Standards and Technology (NIST) by employees of the Federal Government in the course of their official duties. Pursuant to title 17 Section 105 of the United States Code, this software is not subject to copyright protection and is in the public domain. This software and/or related materials have been determined to be not subject to the EAR (see Part 734.3 of the EAR for exact details) because it is a publicly available technology and software, and is freely distributed to any interested party with no licensing requirements. Therefore, it is permissible to distribute this software as a free download from the internet. Disclaimer: This software and/or related materials was developed to promote biometric standards and biometric technology testing for the Federal Government in accordance with the USA PATRIOT Act and the Enhanced Border Security and Visa Entry Reform Act. Specific hardware and software products identified in this software were used in order to perform the software development. In no case does such identification imply recommendation or endorsement by the National Institute of Standards and Technology, nor does it imply that the products and equipment identified are necessarily the best available for the purpose. This software and/or related materials are provided "AS-IS" without warranty of any kind including NO WARRANTY OF PERFORMANCE, MERCHANTABILITY, NO WARRANTY OF NON-INFRINGEMENT OF ANY 3RD PARTY INTELLECTUAL PROPERTY or FITNESS FOR A PARTICULAR PURPOSE or for any purpose whatsoever, for the licensed product, however used. In no event shall NIST be liable for any damages and/or costs, including but not limited to incidental or consequential damages of any kind, including economic damage or injury to property and lost profits, regardless of whether NIST shall be advised, have reason to know, or in fact shall know of the possibility. By using this software, you agree to bear all risk relating to quality, use and performance of the software and/or related materials. You agree to hold the Government harmless from any claim arising from your use of the software. *******************************************************************************/ /*********************************************************************** LIBRARY: AN2K - ANSI/NIST 2007 Reference Implementation FILE: COPY.C AUTHOR: Michael D. Garris DATE: 09/22/2000 UPDATED: 03/03/2005 by MDG UPDATE: 01/31/2008 by Kenneth Ko UPDATE: 09/03/2008 by Kenneth Ko UPDATE: 04/01/2008 by Joseph Konczal - fixed memory overrun error in copy_ANSI_NIST, caused by the wrong letter case Contains routines responsible for creating memory copies of ANSI/NIST file structures plus individual logical records, fields, subfields, and information items. These routines are used primarily to support the construction of ANSI/NIST structures. *********************************************************************** ROUTINES: copyANSI_NIST() copyANSI_NIST_field() copyANSI_NIST_subfield() copyANSI_NIST_item() ***********************************************************************/ #include <stdio.h> #include <an2k.h> /*********************************************************************** ************************************************************************ #cat: copy_ANSI_NIST - Takes an ANSI/NIST structure and creates a #cat: memory copy of its contents. Input: ansi_nist - ANSI/NIST file structure to be copied Output: oansi_nist - points to new memory copy Return Code: Zero - successful completion Negative - system error ************************************************************************/ int copy_ANSI_NIST(ANSI_NIST **oansi_nist, ANSI_NIST *ansi_nist) { int i, ret; ANSI_NIST *nansi_nist; RECORD *nrecord; /* Allocate new ANSI/NIST structure. */ nansi_nist = (ANSI_NIST *)malloc(sizeof(ANSI_NIST)); /* upcased - jck */ if(nansi_nist == NULL){ fprintf(stderr, "ERROR : copy_ANSI_NIST : " "malloc : nansi_nist (%lu bytes)\n", (unsigned long)sizeof(ANSI_NIST)); return(-2); } /* Copy ANSI/NIST structure. */ memcpy(nansi_nist, ansi_nist, sizeof(ANSI_NIST)); /* Allocate same size list of RECORD pointers. */ nansi_nist->records = (RECORD **)malloc(ansi_nist->alloc_records * sizeof(RECORD *)); if(nansi_nist->records == NULL){ fprintf(stderr, "ERROR : copy_ANSI_NIST : " "malloc : %d records (%lu bytes)\n", ansi_nist->alloc_records, (unsigned long)(ansi_nist->alloc_records * sizeof(RECORD *))); free(nansi_nist); return(-3); } /* Foreach record in input ANSI/NIST ... */ for(i = 0; i < ansi_nist->num_records; i++){ if((ret = copy_ANSI_NIST_record(&nrecord, ansi_nist->records[i])) != 0){ /* error - clean up and return */ nansi_nist->num_records = i; free_ANSI_NIST(nansi_nist); return(ret); } nansi_nist->records[i] = nrecord; } /* Assign output pointer. */ *oansi_nist = nansi_nist; /* Return normally. */ return(0); } /*********************************************************************** ************************************************************************ #cat: copy_ANSI_NIST_record - Takes a logical record structure and creates a #cat: memory copy of its contents. Input: record - logical record to be copied Output: orecord - points to new memory copy Return Code: Zero - successful completion Negative - system error ************************************************************************/ int copy_ANSI_NIST_record(RECORD **orecord, RECORD *record) { int i, ret; RECORD *nrecord; FIELD *nfield; /* Allocate new RECORD structure. */ nrecord = (RECORD *)malloc(sizeof(RECORD)); if(nrecord == NULL){ fprintf(stderr, "ERROR : copy_ANSI_NIST_record : " "malloc : nrecord (%lu bytes)\n", (unsigned long)sizeof(RECORD)); return(-2); } /* Copy RECORD structure. */ memcpy(nrecord, record, sizeof(RECORD)); /* Allocate same size list of FIELD pointers. */ nrecord->fields = (FIELD **)malloc(record->alloc_fields * sizeof(FIELD *)); if(nrecord->fields == NULL){ fprintf(stderr, "ERROR : copy_ANSI_NIST_record : " "malloc : %d fields (%lu bytes)\n", record->alloc_fields, (unsigned long)(record->alloc_fields * sizeof(FIELD *))); free(nrecord); return(-3); } /* Foreach field in input RECORD ... */ for(i = 0; i < record->num_fields; i++){ if((ret = copy_ANSI_NIST_field(&nfield, record->fields[i])) != 0){ nrecord->num_fields = i; free_ANSI_NIST_record(nrecord); return(ret); } nrecord->fields[i] = nfield; } /* Assign output pointer. */ *orecord = nrecord; /* Return normally. */ return(0); } /*********************************************************************** ************************************************************************ #cat: copy_ANSI_NIST_field - Takes a field structure and creates a #cat: memory copy of its contents. Input: field - field structure to be copied Output: ofield - points to new memory copy Return Code: Zero - successful completion Negative - system error ************************************************************************/ int copy_ANSI_NIST_field(FIELD **ofield, FIELD *field) { int i, ret; FIELD *nfield; SUBFIELD *nsubfield; int field_id_bytes; /* Allocate new FIELD structure. */ nfield = (FIELD *)malloc(sizeof(FIELD)); if(nfield == NULL){ fprintf(stderr, "ERROR : copy_ANSI_NIST_field : " "malloc : nfield (%lu bytes)\n", (unsigned long)sizeof(FIELD)); return(-2); } /* Copy FIELD structure. */ memcpy(nfield, field, sizeof(FIELD)); /* Condition statement added by MDG on 03/03/2005 */ if(field->id != NULL){ /* Create copy of field ID string. */ /* Allocate maximum size field ID as twice the max number of */ /* characters for the field_int + 2 characters for the '.' and ':' */ /* + 1 for the NULL terminator. */ field_id_bytes = (2 * FIELD_NUM_LEN) + 3; /* Use calloc so that ID buffer is set to all zeros (NULL). */ nfield->id = (char *)calloc((size_t)field_id_bytes, 1); if(nfield->id == NULL){ fprintf(stderr, "ERROR : copy_ANSI_NIST_field : " "calloc : nfield->id (%d bytes)\n", field_id_bytes); free(nfield); return(-3); } /* Copy ID string. */ strcpy(nfield->id, field->id); } /* Otherwise, new field ID already set to NULL */ /* Allocate same size list of SUBFIELD pointers. */ nfield->subfields = (SUBFIELD **)malloc(field->alloc_subfields * sizeof(SUBFIELD *)); if(nfield->subfields == NULL){ fprintf(stderr, "ERROR : copy_ANSI_NIST_field : " "malloc : %d subfields (%lu bytes)\n", field->alloc_subfields, (unsigned long)(field->alloc_subfields * sizeof(SUBFIELD *))); free(nfield->id); free(nfield); return(-4); } /* Foreach subfield in input FIELD ... */ for(i = 0; i < field->num_subfields; i++){ if((ret = copy_ANSI_NIST_subfield(&nsubfield, field->subfields[i])) != 0){ nfield->num_subfields = i; free_ANSI_NIST_field(nfield); return(ret); } nfield->subfields[i] = nsubfield; } /* Assign output pointer. */ *ofield = nfield; /* Return normally. */ return(0); } /*********************************************************************** ************************************************************************ #cat: copy_ANSI_NIST_subfield - Takes a subfield structure and creates a #cat: memory copy of its contents. Input: subfield - subfield structure to be copied Output: osubfield - points to new memory copy Return Code: Zero - successful completion Negative - system error ************************************************************************/ int copy_ANSI_NIST_subfield(SUBFIELD **osubfield, SUBFIELD *subfield) { int i, ret; SUBFIELD *nsubfield; ITEM *nitem; /* Allocate new SUBFIELD structure. */ nsubfield = (SUBFIELD *)malloc(sizeof(SUBFIELD)); if(nsubfield == NULL){ fprintf(stderr, "ERROR : copy_ANSI_NIST_subfield : " "malloc : nsubfield (%lu bytes)\n", (unsigned long)sizeof(SUBFIELD)); return(-2); } /* Copy SUBFIELD structure. */ memcpy(nsubfield, subfield, sizeof(SUBFIELD)); /* Allocate same size list of ITEM pointers. */ nsubfield->items = (ITEM **)malloc(subfield->alloc_items * sizeof(ITEM *)); if(nsubfield->items == NULL){ fprintf(stderr, "ERROR : copy_ANSI_NIST_subfield : " "malloc : %d items (%lu bytes)\n", subfield->alloc_items, (unsigned long)(subfield->alloc_items * sizeof(ITEM *))); free(nsubfield); return(-3); } /* Foreach item in input SUBFIELD ... */ for(i = 0; i < subfield->num_items; i++){ if((ret = copy_ANSI_NIST_item(&nitem, subfield->items[i])) != 0){ nsubfield->num_items = i; free_ANSI_NIST_subfield(nsubfield); return(ret); } nsubfield->items[i] = nitem; } /* Assign output pointer. */ *osubfield = nsubfield; /* Return normally. */ return(0); } /*********************************************************************** ************************************************************************ #cat: copy_ANSI_NIST_item - Takes an information item and creates a #cat: memory copy of its contents. Input: item - information item to be copied Output: oitem - points to new memory copy Return Code: Zero - successful completion Negative - system error ************************************************************************/ int copy_ANSI_NIST_item(ITEM **oitem, ITEM *item) { ITEM *nitem; /* Allocate new ITEM structure. */ nitem = (ITEM *)malloc(sizeof(ITEM)); if(nitem == NULL){ fprintf(stderr, "ERROR : copy_ANSI_NIST_item : " "malloc : nitem (%lu bytes)\n", (unsigned long)sizeof(ITEM)); return(-2); } /* Copy ITEM structure. */ memcpy(nitem, item, sizeof(ITEM)); /* Allocate same size value string. */ nitem->value = (unsigned char *)calloc((size_t)item->alloc_chars, sizeof(unsigned char)); if(nitem->value == NULL){ fprintf(stderr, "ERROR : copy_ANSI_NIST_item : " "calloc : value (%lu bytes)\n", (unsigned long)(item->alloc_chars * sizeof(unsigned char))); free(nitem); return(-3); } /* Copy input ITEM's value. */ /* NOTE: Image Data field items will NOT be NULL terminated. */ /* Can't use strcpy(nitem->value, item->value); */ memcpy(nitem->value, item->value, (size_t)item->alloc_chars); /* Assign output pointer. */ *oitem = nitem; /* Return normally. */ return(0); }
gpl-3.0
BackupGGCode/propgcc
gcc/mpfr/tests/tsi_op.c
5
4524
/* Test file for mpfr_add_si, mpfr_sub_si, mpfr_si_sub, mpfr_mul_si, mpfr_div_si, mpfr_si_div Copyright 2004, 2006, 2007, 2008, 2009, 2010, 2011 Free Software Foundation, Inc. Contributed by the Arenaire and Cacao projects, INRIA. This file is part of the GNU MPFR Library. The GNU MPFR Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. The GNU MPFR Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU MPFR Library; see the file COPYING.LESSER. If not, see http://www.gnu.org/licenses/ or write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <stdio.h> #include <stdlib.h> #include "mpfr-test.h" #define ERROR1(s, i, z, exp) \ {\ printf("Error for "s" and i=%d\n", i);\ printf("Expected %s\n", exp);\ printf("Got "); mpfr_out_str (stdout, 16, 0, z, MPFR_RNDN);\ putchar ('\n');\ exit(1);\ } const struct { const char * op1; long int op2; const char * res_add; const char * res_sub; const char * res_mul; const char * res_div; } tab[] = { {"10", 0x1, "11", "0F", "10", "10"}, {"1", -1, "0", "2", "-1", "-1"}, {"17.42", -0x17, "0.42", "2E.42", "-216.ee", "-1.02de9bd37a6f4"}, {"-1024.0", -0x16, "-103A", "-100E", "16318", "bb.d1745d1745d0"} }; static void check_invert (void) { mpfr_t x; mpfr_init2 (x, MPFR_PREC_MIN); mpfr_set_ui (x, 0xC, MPFR_RNDN); mpfr_si_sub (x, -1, x, MPFR_RNDD); /* -0001 - 1100 = - 1101 --> -1 0000 */ if (mpfr_cmp_si (x, -0x10) ) { printf ("Special rounding error\n"); exit (1); } mpfr_clear (x); } #define TEST_FUNCTION mpfr_add_si #define TEST_FUNCTION_NAME "mpfr_add_si" #define INTEGER_TYPE long #define RAND_FUNCTION(x) mpfr_random2(x, MPFR_LIMB_SIZE (x), 1, RANDS) #define test_generic_ui test_generic_add_si #include "tgeneric_ui.c" #define TEST_FUNCTION mpfr_sub_si #define TEST_FUNCTION_NAME "mpfr_sub_si" #define INTEGER_TYPE long #define RAND_FUNCTION(x) mpfr_random2(x, MPFR_LIMB_SIZE (x), 1, RANDS) #define test_generic_ui test_generic_sub_si #include "tgeneric_ui.c" #define TEST_FUNCTION mpfr_mul_si #define TEST_FUNCTION_NAME "mpfr_mul_si" #define INTEGER_TYPE long #define RAND_FUNCTION(x) mpfr_random2(x, MPFR_LIMB_SIZE (x), 1, RANDS) #define test_generic_ui test_generic_mul_si #include "tgeneric_ui.c" #define TEST_FUNCTION mpfr_div_si #define TEST_FUNCTION_NAME "mpfr_div_si" #define INTEGER_TYPE long #define RAND_FUNCTION(x) mpfr_random2(x, MPFR_LIMB_SIZE (x), 1, RANDS) #define test_generic_ui test_generic_div_si #include "tgeneric_ui.c" int main (int argc, char *argv[]) { mpfr_t x, z; int y; int i; tests_start_mpfr (); mpfr_inits2 (53, x, z, (mpfr_ptr) 0); for(i = 0 ; i < numberof (tab) ; i++) { mpfr_set_str (x, tab[i].op1, 16, MPFR_RNDN); y = tab[i].op2; mpfr_add_si (z, x, y, MPFR_RNDZ); if (mpfr_cmp_str (z, tab[i].res_add, 16, MPFR_RNDN)) ERROR1("add_si", i, z, tab[i].res_add); mpfr_sub_si (z, x, y, MPFR_RNDZ); if (mpfr_cmp_str (z, tab[i].res_sub, 16, MPFR_RNDN)) ERROR1("sub_si", i, z, tab[i].res_sub); mpfr_si_sub (z, y, x, MPFR_RNDZ); mpfr_neg (z, z, MPFR_RNDZ); if (mpfr_cmp_str (z, tab[i].res_sub, 16, MPFR_RNDN)) ERROR1("si_sub", i, z, tab[i].res_sub); mpfr_mul_si (z, x, y, MPFR_RNDZ); if (mpfr_cmp_str (z, tab[i].res_mul, 16, MPFR_RNDN)) ERROR1("mul_si", i, z, tab[i].res_mul); mpfr_div_si (z, x, y, MPFR_RNDZ); if (mpfr_cmp_str (z, tab[i].res_div, 16, MPFR_RNDN)) ERROR1("div_si", i, z, tab[i].res_div); } mpfr_set_str1 (x, "1"); mpfr_si_div (z, 1024, x, MPFR_RNDN); if (mpfr_cmp_str1 (z, "1024")) ERROR1("si_div", i, z, "1024"); mpfr_si_div (z, -1024, x, MPFR_RNDN); if (mpfr_cmp_str1 (z, "-1024")) ERROR1("si_div", i, z, "-1024"); mpfr_clears (x, z, (mpfr_ptr) 0); check_invert (); test_generic_add_si (2, 200, 17); test_generic_sub_si (2, 200, 17); test_generic_mul_si (2, 200, 17); test_generic_div_si (2, 200, 17); tests_end_mpfr (); return 0; }
gpl-3.0
abhishekarora12/spl
c/src/graph.c
5
11026
/* * File: graph.c * ------------- * This file implements the graph.h interface using sets to represent the * nodes and arcs. */ /*************************************************************************/ /* Stanford Portable Library */ /* Copyright (C) 2013 by Eric Roberts <eroberts@cs.stanford.edu> */ /* */ /* This program is free software: you can redistribute it and/or modify */ /* it under the terms of the GNU General Public License as published by */ /* the Free Software Foundation, either version 3 of the License, or */ /* (at your option) any later version. */ /* */ /* This program is distributed in the hope that it will be useful, */ /* but WITHOUT ANY WARRANTY; without even the implied warranty of */ /* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */ /* GNU General Public License for more details. */ /* */ /* You should have received a copy of the GNU General Public License */ /* along with this program. If not, see <http://www.gnu.org/licenses/>. */ /*************************************************************************/ #include <stdio.h> #include "foreach.h" #include "cslib.h" #include "generic.h" #include "graph.h" #include "hashmap.h" #include "iterator.h" #include "itertype.h" #include "set.h" #include "strlib.h" #include "unittest.h" /* * Type: GraphCDT * -------------- * This definition provides the concrete type for a Graph, * which is implemented as a set of nodes and a set of arcs. */ struct GraphCDT { IteratorHeader header; /* Header to make graphs iterable */ Set nodes; /* The set of all nodes in the graph */ Set arcs; /* The set of all arcs in the graph */ CompareFn nodeCmpFn; /* Comparison function to order nodes */ CompareFn arcCmpFn; /* Comparison function to order arcs */ HashMap nameMap; /* Map from names to nodes */ }; /* * Type: NodeCDT * ------------- * This type defines the concrete structure of a graph node. All nodes * have a name, which is used to identify the node. */ struct NodeCDT { string name; /* Name identifying the node */ Set arcs; /* Set of arcs leaving this node */ Graph graph; /* The graph containing this node */ }; /* * Type: ArcCDT * ------------ * The concrete type for an arc consists of its endpoints plus a cost. * This cost need not be economic and will often refer to some other * metric, such as distance. */ struct ArcCDT { Node start; /* The starting node for the arc */ Node end; /* The ending node for the arc */ double cost; /* The "cost" of travesing the arc */ Graph graph; /* The graph containing this arc */ }; /* Private function prototypes */ static Iterator newGraphIterator(void *collection); static int defaultNodeOrdering(const void *p1, const void *p2); static int defaultArcOrdering(const void *p1, const void *p2); /* Exported entries */ Graph newGraph(void) { Graph g; g = newBlock(Graph); enableIteration(g, newGraphIterator); g->nodes = newSet(Node); g->arcs = newSet(Arc); g->nodeCmpFn = defaultNodeOrdering; g->arcCmpFn = defaultArcOrdering; setCompareFn(g->nodes, defaultNodeOrdering); setCompareFn(g->arcs, defaultArcOrdering); g->nameMap = newHashMap(); return g; } void freeGraph(Graph g) { Node node; Arc arc; foreach (node in g->nodes) { freeBlock(node); } foreach (arc in g->arcs) { freeBlock(arc); } freeSet(g->nodes); freeSet(g->arcs); freeHashMap(g->nameMap); freeBlock(g); } Node addNode(Graph g, string name) { Node node; node = newBlock(Node); node->name = name; node->arcs = newSet(Arc); node->graph = g; setCompareFn(node->arcs, g->arcCmpFn); addSet(g->nodes, node); if (containsKeyHashMap(g->nameMap, name)) { error("addNode: Duplicate node %s", name); } putHashMap(g->nameMap, name, node); return node; } void removeNode(Graph g, Node node) { Arc arc; foreach (arc in g->arcs) { if (arc->start == node || arc->end == node) removeArc(g, arc); } freeSet(node->arcs); removeSet(g->nodes, node); removeHashMap(g->nameMap, node->name); freeBlock(node); } Node getNode(Graph g, string name) { return getHashMap(g->nameMap, name); } Arc addArc(Graph g, Node n1, Node n2) { Arc arc; arc = newBlock(Arc); arc->start = n1; arc->end = n2; arc->cost = 0; arc->graph = g; addSet(g->arcs, arc); addSet(n1->arcs, arc); return arc; } void removeArc(Graph g, Arc arc) { removeSet(g->arcs, arc); removeSet(arc->start->arcs, arc); freeBlock(arc); } bool isConnected(Node n1, Node n2) { Iterator it; Arc arc; bool result; result = false; it = newIterator(n1->arcs); while (!result && stepIterator(it, &arc)) { if (arc->end == n2) result = true; } freeIterator(it); return result; } Set getNodeSet(Graph g) { return g->nodes; } Set getArcSet(void *arg) { string type; type = getBlockType(arg); if (endsWith(type, "Graph")) { return ((Graph) arg)->arcs; } else if (endsWith(type, "Node")) { return ((Node) arg)->arcs; } else { error("getArcSet: Unsupported type %s", type); } } Set getNeighbors(Node node) { Set result; Arc arc; result = newSet(Node); setCompareFn(result, node->graph->nodeCmpFn); foreach (arc in node->arcs) { addSet(result, arc->end); } return result; } string getName(Node node) { return node->name; } Node startOfArc(Arc arc) { return arc->start; } Node endOfArc(Arc arc) { return arc->end; } double getCost(Arc arc) { return arc->cost; } void setCost(Arc arc, double cost) { arc->cost = cost; } void setNodeOrdering(Graph g, CompareFn cmpFn) { g->nodeCmpFn = cmpFn; setCompareFn(g->nodes, cmpFn); } void setArcOrdering(Graph g, CompareFn cmpFn) { g->arcCmpFn = cmpFn; setCompareFn(g->arcs, cmpFn); } /* Private functions */ /* * Function: newGraphIterator * Usage: iterator = newGraphIterator(graph); * ------------------------------------------ * Creates a new iterator for a graph, which iterates over its nodes. */ static Iterator newGraphIterator(void *collection) { return newIterator(((Graph) collection)->nodes); } static int defaultNodeOrdering(const void *p1, const void *p2) { string s1, s2; s1 = getName(*((Node *) p1)); s2 = getName(*((Node *) p2)); return stringCompare(s1, s2); } static int defaultArcOrdering(const void *p1, const void *p2) { Arc a1, a2; int cmp; a1 = *((Arc *) p1); a2 = *((Arc *) p2); cmp = stringCompare(getName(a1->start), getName(a2->start)); if (cmp != 0) return cmp; cmp = stringCompare(getName(a1->end), getName(a2->end)); if (cmp != 0) return cmp; if (a1->cost < a2->cost) return -1; if (a1->cost > a2->cost) return +1; if (a1 < a2) return -1; if (a1 > a2) return +1; return 0; } /**********************************************************************/ /* Unit test for the graph module */ /**********************************************************************/ #ifndef _NOTEST_ /* Desired output stream */ static string nodeScript[] = { "A", "B", "C", "D", "X" }; static string arcScript[] = { "A -> B", "A -> C", "A -> D", "B -> C", "B -> D", "C -> D", "X" }; static string neighborScript[] = { "B", "C", "D", "X" }; static string arcsFromScript[] = { "A -> B", "A -> C", "A -> D", "X" }; /* Private function prototypes */ static Graph createTestGraph(void); static void createNode(Graph g, string name); static void linkNodesAlphabetically(Graph g); static void testNodeIterator(Graph g); static void testArcIterator(Graph g); static void testArcsFrom(Graph g); static void testNeighbors(Graph g); static string arcString(Arc arc); /* Unit test */ void testGraphModule(void) { Graph g; g = createTestGraph(); testNodeIterator(g); testArcIterator(g); testArcsFrom(g); testNeighbors(g); } /* Private functions */ static Graph createTestGraph(void) { Graph g; reportMessage("createTestGraph();"); g = newGraph(); addNode(g, "A"); addNode(g, "B"); addNode(g, "C"); addNode(g, "D"); linkNodesAlphabetically(g); return g; } static void linkNodesAlphabetically(Graph g) { Node n1, n2; string s1, s2; foreach (n1 in getNodeSet(g)) { s1 = getName(n1); foreach (n2 in getNodeSet(g)) { s2 = getName(n2); if (stringCompare(s1, s2) < 0) { addArc(g, n1, n2); } } } } static void testNodeIterator(Graph g) { Node node; int count; count = 0; reportMessage("foreach (node in getNodes(g)) {"); adjustReportIndentation(+3); foreach (node in getNodeSet(g)) { test(getName(node), (string) nodeScript[count++]); } adjustReportIndentation(-3); reportMessage("}"); if (!stringEqual(nodeScript[count], "X")) { reportError("Node iterator has too few elements"); } } static void testArcIterator(Graph g) { Arc arc; int count; count = 0; reportMessage("foreach (arc in getArcSet(g)) {"); adjustReportIndentation(+3); foreach (arc in getArcSet(g)) { test(arcString(arc), (string) arcScript[count++]); } adjustReportIndentation(-3); reportMessage("}"); if (!stringEqual(arcScript[count], "X")) { reportError("Arc iterator has too few elements"); } } static void testArcsFrom(Graph g) { Arc arc; int count; count = 0; reportMessage("foreach (arc in getArcSet(getNode(g, \"A\"))) {"); adjustReportIndentation(+3); foreach (arc in getArcSet(getNode(g, "A"))) { test(arcString(arc), (string) arcsFromScript[count++]); } adjustReportIndentation(-3); reportMessage("}"); if (!stringEqual(arcsFromScript[count], "X")) { reportError("Arc iterator has too few elements"); } } static void testNeighbors(Graph g) { Node node; int count; count = 0; reportMessage("foreach (node in getNeighbors(getNode(g, \"A\"))) {"); adjustReportIndentation(+3); foreach (node in getNeighbors(getNode(g, "A"))) { test(getName(node), (string) neighborScript[count++]); } adjustReportIndentation(-3); reportMessage("}"); if (!stringEqual(neighborScript[count], "X")) { reportError("Node iterator has too few elements"); } } static string arcString(Arc arc) { return concat(getName(arc->start), concat(" -> ", getName(arc->end))); } #endif
gpl-3.0
8tab/radare2
libr/core/panels.c
5
26632
/* Copyright radare2 2014-2017 - Author: pancake */ // pls move the typedefs into roons and rename it -> RConsPanel #include <r_core.h> typedef struct { int x; int y; int w; int h; int depth; int type; int sx; // scroll-x int sy; // scroll-y ut64 addr; char *cmd; char *text; } Panel; #define PANEL_TYPE_FRAME 0 #define PANEL_TYPE_DIALOG 1 #define PANEL_TYPE_FLOAT 2 static int COLW = 80; static const int layoutCount = 2; static int layout = 0; static RCore *_core; static int n_panels = 0; static void reloadPanels(RCore *core); static int menu_pos = 0; #define LIMIT 256 struct { int panels[LIMIT]; int size; } ostack; static RConsCanvas *can; static Panel *panels = NULL; static int callgraph = 0; static int menu_x = 0; static int menu_y = 0; static const char *menus[] = { "File", "Edit", "View", "Tools", "Search", "Debug", "Analyze", "Help", NULL }; static const char *menus_File[] = { "New", "Open", "Close", ".", "Sections", "Strings", "Symbols", "Imports", "Info", "Database", ".", "Quit", NULL }; static const char *menus_Edit[] = { "Copy", "Paste", "Clipboard", "Write String", "Write Hex", "Write Value", "Assemble", "Fill", "io.cache", NULL }; static const char *menus_View[] = { "Hexdump", "Disassembly", "Graph", "FcnInfo", "Functions", "Comments", "Entropy", "Colors", NULL }; static const char *menus_Tools[] = { "Assembler", "Calculator", "R2 Shell", "System Shell", NULL }; static const char *menus_Search[] = { "String", "ROP", "Code", "Hexpairs", NULL }; static const char *menus_Debug[] = { "Registers", "RegisterRefs", "DRX", "Breakpoints", "Watchpoints", "Maps", "Modules", "Backtrace", ".", "Continue", "Cont until.", "Step", "Step Over", NULL }; static const char *menus_Analyze[] = { "Function", "Program", "Calls", "References", NULL }; static const char *menus_Help[] = { "Fortune", "Commands", "2048", "License", ".", "About", NULL }; static const char **menus_sub[] = { menus_File, menus_Edit, menus_View, menus_Tools, menus_Search, menus_Debug, menus_Analyze, menus_Help, NULL }; // TODO: handle mouse wheel static int curnode = 0; #define G(x, y) r_cons_canvas_gotoxy (can, x, y) #define W(x) r_cons_canvas_write (can, x) #define B(x, y, w, h) r_cons_canvas_box (can, x, y, w, h, NULL) #define B1(x, y, w, h) r_cons_canvas_box (can, x, y, w, h, Color_BLUE) #define B2(x, y, w, h) r_cons_canvas_box (can, x, y, w, h, Color_MAGENTA) #define L(x, y, x2, y2) r_cons_canvas_line (can, x, y, x2, y2, 0) #define L1(x, y, x2, y2) r_cons_canvas_line (can, x, y, x2, y2, 1) #define L2(x, y, x2, y2) r_cons_canvas_line (can, x, y, x2, y2, 2) #define F(x, y, x2, y2, c) r_cons_canvas_fill (can, x, y, x2, y2, c, 0) static void Panel_print(RConsCanvas *can, Panel *n, int cur) { char title[128]; int delta_x, delta_y; if (!n || !can) { return; } delta_x = n->sx; delta_y = n->sy; // clear F (n->x, n->y, n->w, n->h, ' '); if (n->type == PANEL_TYPE_FRAME) { if (cur) { // F (n->x,n->y, n->w, n->h, '.'); snprintf (title, sizeof (title) - 1, Color_BGREEN "[x] %s"Color_RESET, n->text); } else { snprintf (title, sizeof (title) - 1, " %s ", n->text); } if (G (n->x + 1, n->y + 1)) { W (title); // delta_x } } (void) G (n->x + 2, n->y + 2); // if ( // TODO: only refresh if n->refresh is set // TODO: temporary crop depending on out of screen offsets if (n->cmd && *n->cmd) { char *foo = r_core_cmd_str (_core, n->cmd); char *text; if (delta_y < 0) { delta_y = 0; } if (delta_x < 0) { char white[128]; int idx = -delta_x; memset (white, ' ', sizeof(white)); if (idx >= sizeof (white)) { idx = sizeof (white) - 1; } white[idx] = 0; text = r_str_ansi_crop (foo, 0, delta_y, n->w + delta_x - 2, n->h - 2 + delta_y); text = r_str_prefix_all (text, white); } else { text = r_str_ansi_crop (foo, delta_x, delta_y, n->w + delta_x - 2, n->h - 2 + delta_y); } if (text) { W (text); free (text); } else { W (n->text); } free (foo); } else { char *text = r_str_ansi_crop (n->text, delta_x, delta_y, n->w + 5, n->h - delta_y); if (text) { W (text); free (text); } else { W (n->text); } } if (cur) { B1 (n->x, n->y, n->w, n->h); } else { B (n->x, n->y, n->w, n->h); } } static void Layout_run(Panel *panels) { int h, w = r_cons_get_size (&h); int i, j; int colpos = w - COLW; if (colpos < 0) { COLW = w; colpos = 0; } if (layout < 0) { layout = layoutCount - 1; } if (layout >= layoutCount) { layout = 0; } can->sx = 0; can->sy = 0; for (i = j = 0; panels[i].text; i++) { switch (panels[i].type) { case PANEL_TYPE_FLOAT: panels[i].w = r_str_bounds ( panels[i].text, &panels[i].h); panels[i].h += 4; break; case PANEL_TYPE_FRAME: switch (layout) { case 0: if (j == 0) { panels[i].x = 0; panels[i].y = 1; if (panels[j + 1].text) { panels[i].w = colpos + 1; } else { panels[i].w = w; } panels[i].h = h - 1; } else { int ph = ((h - 1) / (n_panels - 2)); panels[i].x = colpos; panels[i].y = 1 + (ph * (j - 1)); panels[i].w = w - colpos; if (panels[i].w < 0) { panels[i].w = 0; } panels[i].h = ph; if (!panels[i + 1].text) { panels[i].h = h - panels[i].y; } if (j != 1) { panels[i].y--; panels[i].h++; } } break; case 1: if (j == 0) { panels[i].x = 0; panels[i].y = 1; if (panels[j + 1].text) { panels[i].w = colpos + 1; } else { panels[i].w = w; } panels[i].h = (h / 2) + 1; } else if (j == 1) { panels[i].x = 0; panels[i].y = (h / 2) + 1; if (panels[j + 1].text) { panels[i].w = colpos + 1; } else { panels[i].w = w; } panels[i].h = (h - 1) / 2; } else { int ph = ((h - 1) / (n_panels - 3)); panels[i].x = colpos; panels[i].y = 1 + (ph * (j - 2)); panels[i].w = w - colpos; if (panels[i].w < 0) { panels[i].w = 0; } panels[i].h = ph; if (!panels[i + 1].text) { panels[i].h = h - panels[i].y; } if (j != 2) { panels[i].y--; panels[i].h++; } } break; break; } j++; } } } static void delcurpanel() { int i; if (curnode > 0 && n_panels > 3) { for (i = curnode; i < (n_panels - 1); i++) { panels[i] = panels[i + 1]; } panels[i].text = 0; n_panels--; if (curnode >= n_panels) { curnode = n_panels - 1; } } } static void zoom() { if (n_panels > 2) { if (curnode < 2) { curnode = 2; } Panel ocurnode = panels[curnode]; panels[curnode] = panels[1]; panels[1] = ocurnode; curnode = 1; } } static void addPanelFrame(const char *title, const char *cmd, ut64 addr) { int i = n_panels; if (!panels) { panels = calloc (sizeof (Panel), LIMIT); if (!panels) { return; } panels[0].text = strdup (""); panels[0].addr = addr; panels[0].type = PANEL_TYPE_FLOAT; i = n_panels = 1; menu_pos = 0; } panels[i].text = strdup (title); panels[i].cmd = r_str_newf (cmd); panels[i].addr = addr; panels[i].type = PANEL_TYPE_FRAME; panels[i + 1].text = NULL; n_panels++; curnode = n_panels - 1; zoom (); menu_y = 0; } static int bbPanels(RCore *core, Panel **n) { // panels = NULL; addPanelFrame ("Symbols", "isq", 0); addPanelFrame ("Stack", "px 256@r:SP", 0); addPanelFrame ("Registers", "dr=", 0); addPanelFrame ("RegisterRefs", "drr", 0); addPanelFrame ("Disassembly", "pd 128", 0); curnode = 1; Layout_run (panels); return n_panels; } // damn singletons.. there should be only one screen and therefor // only one visual instance of the graph view. refactoring this // into a struct makes the code to reference pointers unnecesarily // we can look for a non-global solution here in the future if // necessary static void r_core_panels_refresh(RCore *core) { char title[1024]; const char *color = curnode? Color_BLUE: Color_BGREEN; char str[1024]; int i, j, h, w = r_cons_get_size (&h); r_cons_clear00 (); if (!can) { return; } r_cons_canvas_resize (can, w, h); #if 0 /* avoid flickering */ r_cons_canvas_clear (can); r_cons_flush (); #endif if (panels) { if (menu_y > 0) { panels[menu_pos].x = menu_x * 6; } else { panels[menu_pos].x = w; } panels[menu_pos].y = 1; free (panels[menu_pos].text); panels[menu_pos].text = calloc (1, 1024); // r_str_newf ("%d", menu_y); int maxsub = 0; for (i = 0; menus_sub[i]; i++) { maxsub = i; } if (menu_x >= 0 && menu_x <= maxsub && menus_sub[menu_x]) { for (j = 0; menus_sub[menu_x][j]; j++) { if (menu_y - 1 == j) { strcat (panels[menu_pos].text, "> "); } else { strcat (panels[menu_pos].text, " "); } strcat (panels[menu_pos].text, menus_sub[menu_x][j]); strcat (panels[menu_pos].text, " \n"); } } for (i = 0; panels[i].text; i++) { if (i != curnode) { Panel_print (can, &panels[i], i == curnode); } } } if (menu_y) { curnode = menu_pos; } // redraw current node to make it appear on top if (panels) { if (curnode >= 0) { Panel_print (can, &panels[curnode], 1); } Panel_print (can, &panels[menu_pos], menu_y); } (void) G (-can->sx, -can->sy); title[0] = 0; if (curnode == 0) { strcpy (title, "> "); } for (i = 0; menus[i]; i++) { if (menu_x == i) { snprintf (str, sizeof (title) - 1, "%s[%s]"Color_RESET, color, menus[i]); } else { snprintf (str, sizeof (title) - 1, "%s %s "Color_RESET, color, menus[i]); } strcat (title, str); } if (curnode == 0) { W (Color_BLUE); W (title); W (Color_RESET); } else { W (Color_RESET); W (title); } snprintf (title, sizeof (title) - 1, "[0x%08"PFMT64x "]", core->offset); (void) G (-can->sx + w - strlen (title), -can->sy); W (title); r_cons_canvas_print (can); r_cons_flush (); } static void reloadPanels(RCore *core) { // W("HELLO WORLD"); Layout_run (panels); } static int havePanel(const char *s) { int i; if (!panels || !panels[0].text) { return 0; } // add new panel for testing for (i = 1; panels[i].text; i++) { if (!strcmp (panels[i].text, s)) { return 1; } } return 0; } static void panel_single_step_in(RCore *core) { if (r_config_get_i (core->config, "cfg.debug")) { if (core->print->cur_enabled) { // dcu 0xaddr r_core_cmdf (core, "dcu 0x%08"PFMT64x, core->offset + core->print->cur); core->print->cur_enabled = 0; } else { r_core_cmd (core, "ds", 0); r_core_cmd (core, ".dr*", 0); } } else { r_core_cmd (core, "aes", 0); r_core_cmd (core, ".ar*", 0); } } static void panel_single_step_over(RCore *core) { if (r_config_get_i (core->config, "cfg.debug")) { if (core->print->cur_enabled) { r_core_cmd (core, "dcr", 0); core->print->cur_enabled = 0; } else { r_core_cmd (core, "dso", 0); r_core_cmd (core, ".dr*", 0); } } else { r_core_cmd (core, "aeso", 0); r_core_cmd (core, ".ar*", 0); } } static void panel_breakpoint(RCore *core) { r_core_cmd (core, "dbs $$", 0); } static void panel_continue(RCore *core) { r_core_cmd (core, "dc", 0); } R_API int r_core_visual_panels(RCore *core) { #define OS_INIT() ostack.size = 0; ostack.panels[0] = 0; #define OS_PUSH(x) if (ostack.size < LIMIT) { ostack.panels[++ostack.size] = x; } #define OS_POP() ((ostack.size > 0)? ostack.panels[--ostack.size]: 0) int okey, key, wheel; int w, h; int asm_comments = 0; int asm_bytes = 0; int have_utf8 = 0; n_panels = 0; panels = NULL; callgraph = 0; _core = core; OS_INIT (); w = r_cons_get_size (&h); can = r_cons_canvas_new (w, h); if (!can) { return false; } can->linemode = r_config_get_i (core->config, "graph.linemode"); can->color = r_config_get_i (core->config, "scr.color"); if (!can) { eprintf ("Cannot create RCons.canvas context\n"); return false; } n_panels = bbPanels (core, NULL); if (!panels) { r_config_set_i (core->config, "scr.color", can->color); free (can); return false; } if (w < 140) { COLW = w / 3; } reloadPanels (core); asm_comments = r_config_get_i (core->config, "asm.comments"); have_utf8 = r_config_get_i (core->config, "scr.utf8"); r_config_set_i (core->config, "asm.comments", 0); asm_bytes = r_config_get_i (core->config, "asm.bytes"); r_config_set_i (core->config, "asm.bytes", 0); r_config_set_i (core->config, "scr.utf8", 0); repeat: core->cons->event_data = core; core->cons->event_resize =\ (RConsEvent) r_core_panels_refresh; w = r_cons_get_size (&h); Layout_run (panels); r_core_panels_refresh (core); wheel = r_config_get_i (core->config, "scr.wheel"); if (wheel) { r_cons_enable_mouse (true); } // r_core_graph_inputhandle() okey = r_cons_readchar (); key = r_cons_arrow_to_hjkl (okey); const char *cmd; switch (key) { case 'u': r_core_cmd0 (core, "s-"); break; case 'U': r_core_cmd0 (core, "s+"); break; case 'n': r_core_cmd0 (core, "sn"); break; case 'p': r_core_cmd0 (core, "sp"); break; case '.': if (r_config_get_i (core->config, "cfg.debug")) { r_core_cmd0 (core, "sr PC"); // r_core_seek (core, r_num_math (core->num, "entry0"), 1); } else { r_core_cmd0 (core, "s entry0; px"); } break; case ' ': case '\r': case '\n': if (curnode == 0 && menu_y) { const char *action = menus_sub[menu_x][menu_y - 1]; if (strstr (action, "New")) { addPanelFrame ("New files", "o", 0); } else if (strstr (action, "Open")) { /* XXX doesnt autocompletes filenames */ r_cons_enable_mouse (false); char *res = r_cons_input ("open file: "); if (res) { if (*res) { r_core_cmdf (core, "o %s", res); } free (res); } r_cons_enable_mouse (true); } else if (strstr (action, "Info")) { addPanelFrame ("Info", "i", 0); } else if (strstr (action, "Database")) { addPanelFrame ("Database", "k ***", 0); } else if (strstr (action, "Registers")) { if (!havePanel ("Registers")) { addPanelFrame ("Registers", "dr=", core->offset); } } else if (strstr (action, "About")) { char *s = r_core_cmd_str (core, "?V"); r_cons_message (s); free (s); } else if (strstr (action, "Hexdump")) { addPanelFrame ("Hexdump", "px 512", core->offset); } else if (strstr (action, "Disassembly")) { addPanelFrame ("Disassembly", "pd 128", core->offset); } else if (strstr (action, "Functions")) { addPanelFrame ("Functions", "afl", core->offset); } else if (strstr (action, "Comments")) { addPanelFrame ("Comments", "CC", core->offset); } else if (strstr (action, "Entropy")) { addPanelFrame ("Entropy", "p=e", core->offset); } else if (strstr (action, "Function")) { r_core_cmdf (core, "af"); } else if (strstr (action, "DRX")) { addPanelFrame ("DRX", "drx", core->offset); } else if (strstr (action, "Program")) { r_core_cmdf (core, "aaa"); } else if (strstr (action, "Calls")) { r_core_cmdf (core, "aac"); } else if (strstr (action, "ROP")) { r_cons_enable_mouse (false); char *res = r_cons_input ("rop grep: "); if (res) { r_core_cmdf (core, "\"/R %s\"", res); free (res); } r_cons_enable_mouse (true); } else if (strstr (action, "String")) { r_cons_enable_mouse (false); char *res = r_cons_input ("search string: "); if (res) { r_core_cmdf (core, "\"/ %s\"", res); free (res); } r_cons_enable_mouse (true); } else if (strstr (action, "Hexpairs")) { r_cons_enable_mouse (false); char *res = r_cons_input ("search hexpairs: "); if (res) { r_core_cmdf (core, "\"/x %s\"", res); free (res); } r_cons_enable_mouse (true); } else if (strstr (action, "Code")) { r_cons_enable_mouse (false); char *res = r_cons_input ("search code: "); if (res) { r_core_cmdf (core, "\"/c %s\"", res); free (res); } r_cons_enable_mouse (true); } else if (strstr (action, "Copy")) { r_cons_enable_mouse (false); char *res = r_cons_input ("How many bytes? "); if (res) { r_core_cmdf (core, "\"y %s\"", res); free (res); } r_cons_enable_mouse (true); } else if (strstr (action, "Write String")) { r_cons_enable_mouse (false); char *res = r_cons_input ("insert string: "); if (res) { r_core_cmdf (core, "\"w %s\"", res); free (res); } r_cons_enable_mouse (true); } else if (strstr (action, "Write Value")) { r_cons_enable_mouse (false); char *res = r_cons_input ("insert number: "); if (res) { r_core_cmdf (core, "\"wv %s\"", res); free (res); } r_cons_enable_mouse (true); } else if (strstr (action, "Write Hex")) { r_cons_enable_mouse (false); char *res = r_cons_input ("insert hexpairs: "); if (res) { r_core_cmdf (core, "\"wx %s\"", res); free (res); } r_cons_enable_mouse (true); } else if (strstr (action, "Calculator")) { r_cons_enable_mouse (false); for (;;) { char *s = r_cons_input ("> "); if (!s || !*s) { free (s); break; } r_core_cmdf (core, "? %s", s); r_cons_flush (); free (s); } r_cons_enable_mouse (true); } else if (strstr (action, "Assemble")) { r_core_visual_asm (core, core->offset); } else if (strstr (action, "Sections")) { addPanelFrame ("Sections", "iSq", 0); } else if (strstr (action, "Close")) { r_core_cmd0 (core, "o-*"); } else if (strstr (action, "Strings")) { addPanelFrame ("Strings", "izq", 0); } else if (strstr (action, "Maps")) { addPanelFrame ("Maps", "dm", 0); } else if (strstr (action, "Modules")) { addPanelFrame ("Modules", "dmm", 0); } else if (strstr (action, "Backtrace")) { addPanelFrame ("Backtrace", "dbt", 0); } else if (strstr (action, "Step")) { r_core_cmd (core, "ds", 0); r_cons_flush (); } else if (strstr (action, "Step Over")) { r_core_cmd (core, "dso", 0); r_cons_flush (); } else if (strstr (action, "Breakpoints")) { addPanelFrame ("Breakpoints", "db", 0); } else if (strstr (action, "Symbols")) { addPanelFrame ("Symbols", "isq", 0); } else if (strstr (action, "Imports")) { addPanelFrame ("Imports", "iiq", 0); } else if (strstr (action, "Paste")) { r_core_cmd0 (core, "yy"); } else if (strstr (action, "Clipboard")) { addPanelFrame ("Clipboard", "yx", 0); } else if (strstr (action, "io.cache")) { r_core_cmd0 (core, "e!io.cache"); } else if (strstr (action, "Fill")) { r_cons_enable_mouse (false); char *s = r_cons_input ("Fill with: "); r_core_cmdf (core, "wow %s", s); free (s); r_cons_enable_mouse (true); } else if (strstr (action, "References")) { r_core_cmdf (core, "aar"); } else if (strstr (action, "FcnInfo")) { addPanelFrame ("FcnInfo", "afi", 0); } else if (strstr (action, "Graph")) { r_core_visual_graph (core, NULL, NULL, true); // addPanelFrame ("Graph", "agf", 0); } else if (strstr (action, "System Shell")) { r_cons_set_raw (0); r_cons_flush (); r_sys_cmd ("$SHELL"); } else if (strstr (action, "R2 Shell")) { core->vmode = false; r_core_visual_prompt_input (core); core->vmode = true; } else if (!strcmp (action, "2048")) { r_cons_2048 (can->color); } else if (strstr (action, "License")) { r_cons_message ("Copyright 2006-2016 - pancake - LGPL"); } else if (strstr (action, "Fortune")) { char *s = r_core_cmd_str (core, "fo"); r_cons_message (s); free (s); } else if (strstr (action, "Commands")) { r_core_cmd0 (core, "?;?@?;?$?;???"); r_cons_any_key (NULL); } else if (strstr (action, "Colors")) { r_core_cmd0 (core, "e!scr.color"); } else if (strstr (action, "Quit")) { goto beach; } } else { if (curnode > 0) { zoom (); } else { menu_y = 1; } } break; case '?': r_cons_clear00 (); r_cons_printf ("Visual Ascii Art Panels:\n" " ! - run r2048 game\n" " . - seek to PC or entrypoint\n" ": - run r2 command in prompt\n" " _ - start the hud input mode\n" "? - show this help\n" " x - close current panel\n" " m - open menubar\n" " V - view graph\n" " C - toggle color\n" " M - open new custom frame\n" " hl - toggle scr.color\n" " HL - move vertical column split\n" " jk - scroll/select menu\n" " JK - select prev/next panels (same as TAB)\n" " sS - step in / step over\n" " uU - undo / redo seek\n" " np - seek to next or previous scr.nkey\n" " q - quit, back to visual mode\n" ); r_cons_flush (); r_cons_any_key (NULL); break; case 's': if (r_config_get_i (core->config, "cfg.debug")) { r_core_cmd0 (core, "ds;.dr*"); // ;sr PC"); } else { panel_single_step_in (core); } break; case 'S': if (r_config_get_i (core->config, "cfg.debug")) { r_core_cmd0 (core, "dso;.dr*"); // ;sr PC"); } else { panel_single_step_over (core); } break; case ':': core->vmode = false; r_core_visual_prompt_input (core); core->vmode = true; break; case 'C': can->color = !can->color; // WTF // r_config_toggle (core->config, "scr.color"); // refresh graph // reloadPanels (core); break; case 'R': if (r_config_get_i (core->config, "scr.randpal")) { r_core_cmd0 (core, "ecr"); } else { r_core_cmd0 (core, "ecn"); } break; case 'j': if (curnode == 0) { if (panels[curnode].type == PANEL_TYPE_FLOAT) { if (menus_sub[menu_x][menu_y]) { menu_y++; } } } else { if (curnode == 1) { r_core_cmd0 (core, "s+$l"); } else { panels[curnode].sy++; } } break; case 'k': if (curnode == 0) { if (panels[curnode].type == PANEL_TYPE_FLOAT) { menu_y--; if (menu_y < 0) { menu_y = 0; } } } else { if (curnode == 1) { r_core_cmd0 (core, "s-8"); } else { panels[curnode].sy--; } } break; case '_': r_core_visual_hud (core); break; case 'x': delcurpanel (); break; case 9: // TAB case 'J': menu_y = 0; menu_x = -1; curnode++; if (!panels[curnode].text) { curnode = 0; menu_x = 0; } break; case 'Z': // SHIFT-TAB case 'K': menu_y = 0; menu_x = -1; curnode--; if (curnode < 0) { curnode = n_panels - 1; } if (!curnode) { menu_x = 0; } break; case 'M': { r_cons_enable_mouse (false); char *name = r_cons_input ("Name: "); char *cmd = r_cons_input ("Command: "); if (name && *name && cmd && *cmd) { addPanelFrame (name, cmd, 0); } free (name); free (cmd); r_cons_enable_mouse (true); } break; case 'm': curnode = 0; if (menu_x < 0) { menu_x = 0; r_core_panels_refresh (core); } menu_y = 1; break; case 'H': COLW += 4; break; case 'L': COLW -= 4; if (COLW < 0) { COLW = 0; } break; case 'h': if (curnode == 0) { if (menu_x) { menu_x--; menu_y = menu_y? 1: 0; r_core_panels_refresh (core); } } else { panels[curnode].sx--; } break; case 'l': if (curnode == 0) { if (menus[menu_x + 1]) { menu_x++; menu_y = menu_y? 1: 0; r_core_panels_refresh (core); } } else { panels[curnode].sx++; } break; case 'V': /* copypasta from visual.c */ if (r_config_get_i (core->config, "graph.web")) { r_core_cmd0 (core, "agv $$"); } else { RAnalFunction *fun = r_anal_get_fcn_in (core->anal, core->offset, R_ANAL_FCN_TYPE_NULL); int ocolor; if (!fun) { r_cons_message ("Not in a function. Type 'df' to define it here"); break; } else if (r_list_empty (fun->bbs)) { r_cons_message ("No basic blocks in this function. You may want to use 'afb+'."); break; } ocolor = r_config_get_i (core->config, "scr.color"); r_core_visual_graph (core, NULL, NULL, true); r_config_set_i (core->config, "scr.color", ocolor); } break; case ']': r_config_set_i (core->config, "hex.cols", r_config_get_i (core->config, "hex.cols") + 1); break; case '[': r_config_set_i (core->config, "hex.cols", r_config_get_i (core->config, "hex.cols") - 1); break; case 'w': layout++; Layout_run (panels); r_core_panels_refresh (core); r_cons_canvas_print (can); r_cons_flush (); break; case R_CONS_KEY_F1: cmd = r_config_get (core->config, "key.f1"); if (cmd && *cmd) { key = r_core_cmd0 (core, cmd); } break; case R_CONS_KEY_F2: cmd = r_config_get (core->config, "key.f2"); if (cmd && *cmd) { key = r_core_cmd0 (core, cmd); } else { panel_breakpoint (core); } break; case R_CONS_KEY_F3: cmd = r_config_get (core->config, "key.f3"); if (cmd && *cmd) { key = r_core_cmd0 (core, cmd); } break; case R_CONS_KEY_F4: cmd = r_config_get (core->config, "key.f4"); if (cmd && *cmd) { key = r_core_cmd0 (core, cmd); } break; case R_CONS_KEY_F5: cmd = r_config_get (core->config, "key.f5"); if (cmd && *cmd) { key = r_core_cmd0 (core, cmd); } break; case R_CONS_KEY_F6: cmd = r_config_get (core->config, "key.f6"); if (cmd && *cmd) { key = r_core_cmd0 (core, cmd); } break; case R_CONS_KEY_F7: cmd = r_config_get (core->config, "key.f7"); if (cmd && *cmd) { key = r_core_cmd0 (core, cmd); } else { panel_single_step_in (core); } break; case R_CONS_KEY_F8: cmd = r_config_get (core->config, "key.f8"); if (cmd && *cmd) { key = r_core_cmd0 (core, cmd); } else { panel_single_step_over (core); } break; case R_CONS_KEY_F9: cmd = r_config_get (core->config, "key.f9"); if (cmd && *cmd) { key = r_core_cmd0 (core, cmd); } else { panel_continue (core); } break; case R_CONS_KEY_F10: cmd = r_config_get (core->config, "key.f10"); if (cmd && *cmd) { key = r_core_cmd0 (core, cmd); } break; case R_CONS_KEY_F11: cmd = r_config_get (core->config, "key.f11"); if (cmd && *cmd) { key = r_core_cmd0 (core, cmd); } break; case R_CONS_KEY_F12: cmd = r_config_get (core->config, "key.f12"); if (cmd && *cmd) { key = r_core_cmd0 (core, cmd); } break; case '!': case 'q': case -1: // EOF if (menu_y > 0) { menu_y = 0; } else { goto beach; } break; #if 0 case 27: // ESC if (r_cons_readchar () == 91) { if (r_cons_readchar () == 90) {} } break; #endif default: // eprintf ("Key %d\n", key); // sleep (1); break; } goto repeat; beach: free (panels); r_config_set_i (core->config, "scr.color", can->color); free (can); r_config_set_i (core->config, "asm.comments", asm_comments); r_config_set_i (core->config, "asm.bytes", asm_bytes); r_config_set_i (core->config, "scr.utf8", have_utf8); return true; }
gpl-3.0
Xracer/shoes-diary
src/Battlescape/AliensCrashState.cpp
5
2470
/* * Copyright 2010-2015 OpenXcom Developers. * * This file is part of OpenXcom. * * OpenXcom 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. * * OpenXcom 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 OpenXcom. If not, see <http://www.gnu.org/licenses/>. */ #include "AliensCrashState.h" #include "DebriefingState.h" #include "../Engine/Game.h" #include "../Mod/Mod.h" #include "../Engine/LocalizedText.h" #include "../Interface/TextButton.h" #include "../Interface/Window.h" #include "../Interface/Text.h" #include "../Engine/Options.h" namespace OpenXcom { /** * Initializes all the elements in the Aliens Crash screen. * @param game Pointer to the core game. */ AliensCrashState::AliensCrashState() { // Create objects _window = new Window(this, 256, 160, 32, 20); _btnOk = new TextButton(120, 18, 100, 154); _txtTitle = new Text(246, 80, 37, 50); // Set palette setPalette("PAL_BATTLESCAPE"); add(_window, "messageWindowBorder", "battlescape"); add(_btnOk, "messageWindowButtons", "battlescape"); add(_txtTitle, "messageWindows", "battlescape"); centerAllSurfaces(); // Set up objects _window->setHighContrast(true); _window->setBackground(_game->getMod()->getSurface("TAC00.SCR")); _btnOk->setHighContrast(true); _btnOk->setText(tr("STR_OK")); _btnOk->onMouseClick((ActionHandler)&AliensCrashState::btnOkClick); _btnOk->onKeyboardPress((ActionHandler)&AliensCrashState::btnOkClick, Options::keyOk); _btnOk->onKeyboardPress((ActionHandler)&AliensCrashState::btnOkClick, Options::keyCancel); _txtTitle->setHighContrast(true); _txtTitle->setText(tr("STR_ALL_ALIENS_KILLED_IN_CRASH")); _txtTitle->setAlign(ALIGN_CENTER); _txtTitle->setVerticalAlign(ALIGN_MIDDLE); _txtTitle->setBig(); _txtTitle->setWordWrap(true); } /** * */ AliensCrashState::~AliensCrashState() { } /** * Returns to the previous screen. * @param action Pointer to an action. */ void AliensCrashState::btnOkClick(Action *) { _game->popState(); _game->pushState(new DebriefingState); } }
gpl-3.0
lopezloo/mtasa-blue
vendor/cegui-0.4.0-custom/src/tinyxml/tinyxml.cpp
6
30157
/* www.sourceforge.net/projects/tinyxml Original code (2.0 and earlier )copyright (c) 2000-2002 Lee Thomason (www.grinninglizard.com) This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include <ctype.h> #include "tinyxml.h" #ifdef TIXML_USE_STL #include <sstream> #endif bool TiXmlBase::condenseWhiteSpace = true; void TiXmlBase::PutString( const TIXML_STRING& str, TIXML_OSTREAM* stream ) { TIXML_STRING buffer; PutString( str, &buffer ); (*stream) << buffer; } void TiXmlBase::PutString( const TIXML_STRING& str, TIXML_STRING* outString ) { int i=0; while( i<(int)str.length() ) { unsigned char c = (unsigned char) str[i]; if ( c == '&' && i < ( (int)str.length() - 2 ) && str[i+1] == '#' && str[i+2] == 'x' ) { // Hexadecimal character reference. // Pass through unchanged. // &#xA9; -- copyright symbol, for example. // // The -1 is a bug fix from Rob Laveaux. It keeps // an overflow from happening if there is no ';'. // There are actually 2 ways to exit this loop - // while fails (error case) and break (semicolon found). // However, there is no mechanism (currently) for // this function to return an error. while ( i<(int)str.length()-1 ) { outString->append( str.c_str() + i, 1 ); ++i; if ( str[i] == ';' ) break; } } else if ( c == '&' ) { outString->append( entity[0].str, entity[0].strLength ); ++i; } else if ( c == '<' ) { outString->append( entity[1].str, entity[1].strLength ); ++i; } else if ( c == '>' ) { outString->append( entity[2].str, entity[2].strLength ); ++i; } else if ( c == '\"' ) { outString->append( entity[3].str, entity[3].strLength ); ++i; } else if ( c == '\'' ) { outString->append( entity[4].str, entity[4].strLength ); ++i; } else if ( c < 32 ) { // Easy pass at non-alpha/numeric/symbol // Below 32 is symbolic. char buf[ 32 ]; sprintf( buf, "&#x%02X;", (unsigned) ( c & 0xff ) ); //*ME: warning C4267: convert 'size_t' to 'int' //*ME: Int-Cast to make compiler happy ... outString->append( buf, (int)strlen( buf ) ); ++i; } else { //char realc = (char) c; //outString->append( &realc, 1 ); *outString += (char) c; // somewhat more efficient function call. ++i; } } } // <-- Strange class for a bug fix. Search for STL_STRING_BUG TiXmlBase::StringToBuffer::StringToBuffer( const TIXML_STRING& str ) { buffer = new char[ str.length()+1 ]; if ( buffer ) { strcpy( buffer, str.c_str() ); } } TiXmlBase::StringToBuffer::~StringToBuffer() { delete [] buffer; } // End strange bug fix. --> TiXmlNode::TiXmlNode( NodeType _type ) : TiXmlBase() { parent = 0; type = _type; firstChild = 0; lastChild = 0; prev = 0; next = 0; } TiXmlNode::~TiXmlNode() { TiXmlNode* node = firstChild; TiXmlNode* temp = 0; while ( node ) { temp = node; node = node->next; delete temp; } } void TiXmlNode::CopyTo( TiXmlNode* target ) const { target->SetValue (value.c_str() ); target->userData = userData; } void TiXmlNode::Clear() { TiXmlNode* node = firstChild; TiXmlNode* temp = 0; while ( node ) { temp = node; node = node->next; delete temp; } firstChild = 0; lastChild = 0; } TiXmlNode* TiXmlNode::LinkEndChild( TiXmlNode* node ) { node->parent = this; node->prev = lastChild; node->next = 0; if ( lastChild ) lastChild->next = node; else firstChild = node; // it was an empty list. lastChild = node; return node; } TiXmlNode* TiXmlNode::InsertEndChild( const TiXmlNode& addThis ) { TiXmlNode* node = addThis.Clone(); if ( !node ) return 0; return LinkEndChild( node ); } TiXmlNode* TiXmlNode::InsertBeforeChild( TiXmlNode* beforeThis, const TiXmlNode& addThis ) { if ( !beforeThis || beforeThis->parent != this ) return 0; TiXmlNode* node = addThis.Clone(); if ( !node ) return 0; node->parent = this; node->next = beforeThis; node->prev = beforeThis->prev; if ( beforeThis->prev ) { beforeThis->prev->next = node; } else { assert( firstChild == beforeThis ); firstChild = node; } beforeThis->prev = node; return node; } TiXmlNode* TiXmlNode::InsertAfterChild( TiXmlNode* afterThis, const TiXmlNode& addThis ) { if ( !afterThis || afterThis->parent != this ) return 0; TiXmlNode* node = addThis.Clone(); if ( !node ) return 0; node->parent = this; node->prev = afterThis; node->next = afterThis->next; if ( afterThis->next ) { afterThis->next->prev = node; } else { assert( lastChild == afterThis ); lastChild = node; } afterThis->next = node; return node; } TiXmlNode* TiXmlNode::ReplaceChild( TiXmlNode* replaceThis, const TiXmlNode& withThis ) { if ( replaceThis->parent != this ) return 0; TiXmlNode* node = withThis.Clone(); if ( !node ) return 0; node->next = replaceThis->next; node->prev = replaceThis->prev; if ( replaceThis->next ) replaceThis->next->prev = node; else lastChild = node; if ( replaceThis->prev ) replaceThis->prev->next = node; else firstChild = node; delete replaceThis; node->parent = this; return node; } bool TiXmlNode::RemoveChild( TiXmlNode* removeThis ) { if ( removeThis->parent != this ) { assert( 0 ); return false; } if ( removeThis->next ) removeThis->next->prev = removeThis->prev; else lastChild = removeThis->prev; if ( removeThis->prev ) removeThis->prev->next = removeThis->next; else firstChild = removeThis->next; delete removeThis; return true; } const TiXmlNode* TiXmlNode::FirstChild( const char * _value ) const { const TiXmlNode* node; for ( node = firstChild; node; node = node->next ) { if ( node->SValue() == TIXML_CAST_STRING( _value )) return node; } return 0; } TiXmlNode* TiXmlNode::FirstChild( const char * _value ) { TiXmlNode* node; for ( node = firstChild; node; node = node->next ) { if ( node->SValue() == TIXML_CAST_STRING( _value )) return node; } return 0; } const TiXmlNode* TiXmlNode::LastChild( const char * _value ) const { const TiXmlNode* node; for ( node = lastChild; node; node = node->prev ) { if ( node->SValue() == TIXML_CAST_STRING(_value)) return node; } return 0; } TiXmlNode* TiXmlNode::LastChild( const char * _value ) { TiXmlNode* node; for ( node = lastChild; node; node = node->prev ) { if ( node->SValue() == TIXML_CAST_STRING(_value)) return node; } return 0; } const TiXmlNode* TiXmlNode::IterateChildren( TiXmlNode* previous ) const { if ( !previous ) { return FirstChild(); } else { assert( previous->parent == this ); return previous->NextSibling(); } } TiXmlNode* TiXmlNode::IterateChildren( TiXmlNode* previous ) { if ( !previous ) { return FirstChild(); } else { assert( previous->parent == this ); return previous->NextSibling(); } } const TiXmlNode* TiXmlNode::IterateChildren( const char * val, TiXmlNode* previous ) const { if ( !previous ) { return FirstChild( val ); } else { assert( previous->parent == this ); return previous->NextSibling( val ); } } TiXmlNode* TiXmlNode::IterateChildren( const char * val, TiXmlNode* previous ) { if ( !previous ) { return FirstChild( val ); } else { assert( previous->parent == this ); return previous->NextSibling( val ); } } const TiXmlNode* TiXmlNode::NextSibling( const char * _value ) const { const TiXmlNode* node; for ( node = next; node; node = node->next ) { if ( node->SValue() == TIXML_CAST_STRING(_value)) return node; } return 0; } TiXmlNode* TiXmlNode::NextSibling( const char * _value ) { TiXmlNode* node; for ( node = next; node; node = node->next ) { if ( node->SValue() == TIXML_CAST_STRING(_value)) return node; } return 0; } const TiXmlNode* TiXmlNode::PreviousSibling( const char * _value ) const { const TiXmlNode* node; for ( node = prev; node; node = node->prev ) { if ( node->SValue() == TIXML_CAST_STRING(_value)) return node; } return 0; } TiXmlNode* TiXmlNode::PreviousSibling( const char * _value ) { TiXmlNode* node; for ( node = prev; node; node = node->prev ) { if ( node->SValue() == TIXML_CAST_STRING(_value)) return node; } return 0; } void TiXmlElement::RemoveAttribute( const char * name ) { TiXmlAttribute* node = attributeSet.Find( name ); if ( node ) { attributeSet.Remove( node ); delete node; } } const TiXmlElement* TiXmlNode::FirstChildElement() const { const TiXmlNode* node; for ( node = FirstChild(); node; node = node->NextSibling() ) { if ( node->ToElement() ) return node->ToElement(); } return 0; } TiXmlElement* TiXmlNode::FirstChildElement() { TiXmlNode* node; for ( node = FirstChild(); node; node = node->NextSibling() ) { if ( node->ToElement() ) return node->ToElement(); } return 0; } const TiXmlElement* TiXmlNode::FirstChildElement( const char * _value ) const { const TiXmlNode* node; for ( node = FirstChild( _value ); node; node = node->NextSibling( _value ) ) { if ( node->ToElement() ) return node->ToElement(); } return 0; } TiXmlElement* TiXmlNode::FirstChildElement( const char * _value ) { TiXmlNode* node; for ( node = FirstChild( _value ); node; node = node->NextSibling( _value ) ) { if ( node->ToElement() ) return node->ToElement(); } return 0; } const TiXmlElement* TiXmlNode::NextSiblingElement() const { const TiXmlNode* node; for ( node = NextSibling(); node; node = node->NextSibling() ) { if ( node->ToElement() ) return node->ToElement(); } return 0; } TiXmlElement* TiXmlNode::NextSiblingElement() { TiXmlNode* node; for ( node = NextSibling(); node; node = node->NextSibling() ) { if ( node->ToElement() ) return node->ToElement(); } return 0; } const TiXmlElement* TiXmlNode::NextSiblingElement( const char * _value ) const { const TiXmlNode* node; for ( node = NextSibling( _value ); node; node = node->NextSibling( _value ) ) { if ( node->ToElement() ) return node->ToElement(); } return 0; } TiXmlElement* TiXmlNode::NextSiblingElement( const char * _value ) { TiXmlNode* node; for ( node = NextSibling( _value ); node; node = node->NextSibling( _value ) ) { if ( node->ToElement() ) return node->ToElement(); } return 0; } const TiXmlDocument* TiXmlNode::GetDocument() const { const TiXmlNode* node; for( node = this; node; node = node->parent ) { if ( node->ToDocument() ) return node->ToDocument(); } return 0; } TiXmlDocument* TiXmlNode::GetDocument() { TiXmlNode* node; for( node = this; node; node = node->parent ) { if ( node->ToDocument() ) return node->ToDocument(); } return 0; } TiXmlElement::TiXmlElement (const char * _value) : TiXmlNode( TiXmlNode::ELEMENT ) { firstChild = lastChild = 0; value = _value; } #ifdef TIXML_USE_STL TiXmlElement::TiXmlElement( const std::string& _value ) : TiXmlNode( TiXmlNode::ELEMENT ) { firstChild = lastChild = 0; value = _value; } #endif TiXmlElement::TiXmlElement( const TiXmlElement& copy) : TiXmlNode( TiXmlNode::ELEMENT ) { firstChild = lastChild = 0; copy.CopyTo( this ); } void TiXmlElement::operator=( const TiXmlElement& base ) { ClearThis(); base.CopyTo( this ); } TiXmlElement::~TiXmlElement() { ClearThis(); } void TiXmlElement::ClearThis() { Clear(); while( attributeSet.First() ) { TiXmlAttribute* node = attributeSet.First(); attributeSet.Remove( node ); delete node; } } const char * TiXmlElement::Attribute( const char * name ) const { const TiXmlAttribute* node = attributeSet.Find( name ); if ( node ) return node->Value(); return 0; } const char * TiXmlElement::Attribute( const char * name, int* i ) const { const char * s = Attribute( name ); if ( i ) { if ( s ) *i = atoi( s ); else *i = 0; } return s; } const char * TiXmlElement::Attribute( const char * name, double* d ) const { const char * s = Attribute( name ); if ( d ) { if ( s ) *d = atof( s ); else *d = 0; } return s; } int TiXmlElement::QueryIntAttribute( const char* name, int* ival ) const { const TiXmlAttribute* node = attributeSet.Find( name ); if ( !node ) return TIXML_NO_ATTRIBUTE; return node->QueryIntValue( ival ); } int TiXmlElement::QueryDoubleAttribute( const char* name, double* dval ) const { const TiXmlAttribute* node = attributeSet.Find( name ); if ( !node ) return TIXML_NO_ATTRIBUTE; return node->QueryDoubleValue( dval ); } void TiXmlElement::SetAttribute( const char * name, int val ) { char buf[64]; sprintf( buf, "%d", val ); SetAttribute( name, buf ); } void TiXmlElement::SetDoubleAttribute( const char * name, double val ) { char buf[128]; sprintf( buf, "%f", val ); SetAttribute( name, buf ); } void TiXmlElement::SetAttribute( const char * name, const char * _value ) { TiXmlAttribute* node = attributeSet.Find( name ); if ( node ) { node->SetValue( _value ); return; } TiXmlAttribute* attrib = new TiXmlAttribute( name, _value ); if ( attrib ) { attributeSet.Add( attrib ); } else { TiXmlDocument* document = GetDocument(); if ( document ) document->SetError( TIXML_ERROR_OUT_OF_MEMORY, 0, 0, TIXML_ENCODING_UNKNOWN ); } } void TiXmlElement::Print( FILE* cfile, int depth ) const { int i; for ( i=0; i<depth; i++ ) { fprintf( cfile, " " ); } fprintf( cfile, "<%s", value.c_str() ); const TiXmlAttribute* attrib; for ( attrib = attributeSet.First(); attrib; attrib = attrib->Next() ) { fprintf( cfile, " " ); attrib->Print( cfile, depth ); } // There are 3 different formatting approaches: // 1) An element without children is printed as a <foo /> node // 2) An element with only a text child is printed as <foo> text </foo> // 3) An element with children is printed on multiple lines. TiXmlNode* node; if ( !firstChild ) { fprintf( cfile, " />" ); } else if ( firstChild == lastChild && firstChild->ToText() ) { fprintf( cfile, ">" ); firstChild->Print( cfile, depth + 1 ); fprintf( cfile, "</%s>", value.c_str() ); } else { fprintf( cfile, ">" ); for ( node = firstChild; node; node=node->NextSibling() ) { if ( !node->ToText() ) { fprintf( cfile, "\n" ); } node->Print( cfile, depth+1 ); } fprintf( cfile, "\n" ); for( i=0; i<depth; ++i ) fprintf( cfile, " " ); fprintf( cfile, "</%s>", value.c_str() ); } } void TiXmlElement::StreamOut( TIXML_OSTREAM * stream ) const { (*stream) << "<" << value; const TiXmlAttribute* attrib; for ( attrib = attributeSet.First(); attrib; attrib = attrib->Next() ) { (*stream) << " "; attrib->StreamOut( stream ); } // If this node has children, give it a closing tag. Else // make it an empty tag. TiXmlNode* node; if ( firstChild ) { (*stream) << ">"; for ( node = firstChild; node; node=node->NextSibling() ) { node->StreamOut( stream ); } (*stream) << "</" << value << ">"; } else { (*stream) << " />"; } } void TiXmlElement::CopyTo( TiXmlElement* target ) const { // superclass: TiXmlNode::CopyTo( target ); // Element class: // Clone the attributes, then clone the children. const TiXmlAttribute* attribute = 0; for( attribute = attributeSet.First(); attribute; attribute = attribute->Next() ) { target->SetAttribute( attribute->Name(), attribute->Value() ); } TiXmlNode* node = 0; for ( node = firstChild; node; node = node->NextSibling() ) { target->LinkEndChild( node->Clone() ); } } TiXmlNode* TiXmlElement::Clone() const { TiXmlElement* clone = new TiXmlElement( Value() ); if ( !clone ) return 0; CopyTo( clone ); return clone; } TiXmlDocument::TiXmlDocument() : TiXmlNode( TiXmlNode::DOCUMENT ) { tabsize = 4; ClearError(); } TiXmlDocument::TiXmlDocument( const char * documentName ) : TiXmlNode( TiXmlNode::DOCUMENT ) { tabsize = 4; value = documentName; ClearError(); } #ifdef TIXML_USE_STL TiXmlDocument::TiXmlDocument( const std::string& documentName ) : TiXmlNode( TiXmlNode::DOCUMENT ) { tabsize = 4; value = documentName; ClearError(); } #endif TiXmlDocument::TiXmlDocument( const TiXmlDocument& copy ) : TiXmlNode( TiXmlNode::DOCUMENT ) { copy.CopyTo( this ); } void TiXmlDocument::operator=( const TiXmlDocument& copy ) { Clear(); copy.CopyTo( this ); } bool TiXmlDocument::LoadFile( TiXmlEncoding encoding ) { // See STL_STRING_BUG below. StringToBuffer buf( value ); if ( buf.buffer && LoadFile( buf.buffer, encoding ) ) return true; return false; } bool TiXmlDocument::SaveFile() const { // See STL_STRING_BUG below. StringToBuffer buf( value ); if ( buf.buffer && SaveFile( buf.buffer ) ) return true; return false; } bool TiXmlDocument::LoadFile( const char* filename, TiXmlEncoding encoding ) { // Delete the existing data: Clear(); location.Clear(); // There was a really terrifying little bug here. The code: // value = filename // in the STL case, cause the assignment method of the std::string to // be called. What is strange, is that the std::string had the same // address as it's c_str() method, and so bad things happen. Looks // like a bug in the Microsoft STL implementation. // See STL_STRING_BUG above. // Fixed with the StringToBuffer class. value = filename; FILE* file = fopen( value.c_str (), "r" ); if ( file ) { // Get the file size, so we can pre-allocate the string. HUGE speed impact. long length = 0; fseek( file, 0, SEEK_END ); length = ftell( file ); fseek( file, 0, SEEK_SET ); // Strange case, but good to handle up front. if ( length == 0 ) { fclose( file ); return false; } // If we have a file, assume it is all one big XML file, and read it in. // The document parser may decide the document ends sooner than the entire file, however. TIXML_STRING data; data.reserve( length ); const int BUF_SIZE = 2048; char buf[BUF_SIZE]; while( fgets( buf, BUF_SIZE, file ) ) { data += buf; } fclose( file ); Parse( data.c_str(), 0, encoding ); if ( Error() ) return false; else return true; } SetError( TIXML_ERROR_OPENING_FILE, 0, 0, TIXML_ENCODING_UNKNOWN ); return false; } bool TiXmlDocument::SaveFile( const char * filename ) const { // The old c stuff lives on... FILE* fp = fopen( filename, "w" ); if ( fp ) { Print( fp, 0 ); fclose( fp ); return true; } return false; } void TiXmlDocument::CopyTo( TiXmlDocument* target ) const { TiXmlNode::CopyTo( target ); target->error = error; target->errorDesc = errorDesc.c_str (); TiXmlNode* node = 0; for ( node = firstChild; node; node = node->NextSibling() ) { target->LinkEndChild( node->Clone() ); } } TiXmlNode* TiXmlDocument::Clone() const { TiXmlDocument* clone = new TiXmlDocument(); if ( !clone ) return 0; CopyTo( clone ); return clone; } void TiXmlDocument::Print( FILE* cfile, int depth ) const { const TiXmlNode* node; for ( node=FirstChild(); node; node=node->NextSibling() ) { node->Print( cfile, depth ); fprintf( cfile, "\n" ); } } void TiXmlDocument::StreamOut( TIXML_OSTREAM * out ) const { const TiXmlNode* node; for ( node=FirstChild(); node; node=node->NextSibling() ) { node->StreamOut( out ); // Special rule for streams: stop after the root element. // The stream in code will only read one element, so don't // write more than one. if ( node->ToElement() ) break; } } const TiXmlAttribute* TiXmlAttribute::Next() const { // We are using knowledge of the sentinel. The sentinel // have a value or name. if ( next->value.empty() && next->name.empty() ) return 0; return next; } TiXmlAttribute* TiXmlAttribute::Next() { // We are using knowledge of the sentinel. The sentinel // have a value or name. if ( next->value.empty() && next->name.empty() ) return 0; return next; } const TiXmlAttribute* TiXmlAttribute::Previous() const { // We are using knowledge of the sentinel. The sentinel // have a value or name. if ( prev->value.empty() && prev->name.empty() ) return 0; return prev; } TiXmlAttribute* TiXmlAttribute::Previous() { // We are using knowledge of the sentinel. The sentinel // have a value or name. if ( prev->value.empty() && prev->name.empty() ) return 0; return prev; } void TiXmlAttribute::Print( FILE* cfile, int /*depth*/ ) const { TIXML_STRING n, v; PutString( name, &n ); PutString( value, &v ); if (value.find ('\"') == TIXML_STRING::npos) fprintf (cfile, "%s=\"%s\"", n.c_str(), v.c_str() ); else fprintf (cfile, "%s='%s'", n.c_str(), v.c_str() ); } void TiXmlAttribute::StreamOut( TIXML_OSTREAM * stream ) const { if (value.find( '\"' ) != TIXML_STRING::npos) { PutString( name, stream ); (*stream) << "=" << "'"; PutString( value, stream ); (*stream) << "'"; } else { PutString( name, stream ); (*stream) << "=" << "\""; PutString( value, stream ); (*stream) << "\""; } } int TiXmlAttribute::QueryIntValue( int* ival ) const { if ( sscanf( value.c_str(), "%d", ival ) == 1 ) return TIXML_SUCCESS; return TIXML_WRONG_TYPE; } int TiXmlAttribute::QueryDoubleValue( double* dval ) const { if ( sscanf( value.c_str(), "%lf", dval ) == 1 ) return TIXML_SUCCESS; return TIXML_WRONG_TYPE; } void TiXmlAttribute::SetIntValue( int _value ) { char buf [64]; sprintf (buf, "%d", _value); SetValue (buf); } void TiXmlAttribute::SetDoubleValue( double _value ) { char buf [64]; sprintf (buf, "%lf", _value); SetValue (buf); } const int TiXmlAttribute::IntValue() const { return atoi (value.c_str ()); } const double TiXmlAttribute::DoubleValue() const { return atof (value.c_str ()); } TiXmlComment::TiXmlComment( const TiXmlComment& copy ) : TiXmlNode( TiXmlNode::COMMENT ) { copy.CopyTo( this ); } void TiXmlComment::operator=( const TiXmlComment& base ) { Clear(); base.CopyTo( this ); } void TiXmlComment::Print( FILE* cfile, int depth ) const { for ( int i=0; i<depth; i++ ) { fputs( " ", cfile ); } fprintf( cfile, "<!--%s-->", value.c_str() ); } void TiXmlComment::StreamOut( TIXML_OSTREAM * stream ) const { (*stream) << "<!--"; //PutString( value, stream ); (*stream) << value; (*stream) << "-->"; } void TiXmlComment::CopyTo( TiXmlComment* target ) const { TiXmlNode::CopyTo( target ); } TiXmlNode* TiXmlComment::Clone() const { TiXmlComment* clone = new TiXmlComment(); if ( !clone ) return 0; CopyTo( clone ); return clone; } void TiXmlText::Print( FILE* cfile, int /*depth*/ ) const { TIXML_STRING buffer; PutString( value, &buffer ); fprintf( cfile, "%s", buffer.c_str() ); } void TiXmlText::StreamOut( TIXML_OSTREAM * stream ) const { PutString( value, stream ); } void TiXmlText::CopyTo( TiXmlText* target ) const { TiXmlNode::CopyTo( target ); } TiXmlNode* TiXmlText::Clone() const { TiXmlText* clone = 0; clone = new TiXmlText( "" ); if ( !clone ) return 0; CopyTo( clone ); return clone; } TiXmlDeclaration::TiXmlDeclaration( const char * _version, const char * _encoding, const char * _standalone ) : TiXmlNode( TiXmlNode::DECLARATION ) { version = _version; encoding = _encoding; standalone = _standalone; } #ifdef TIXML_USE_STL TiXmlDeclaration::TiXmlDeclaration( const std::string& _version, const std::string& _encoding, const std::string& _standalone ) : TiXmlNode( TiXmlNode::DECLARATION ) { version = _version; encoding = _encoding; standalone = _standalone; } #endif TiXmlDeclaration::TiXmlDeclaration( const TiXmlDeclaration& copy ) : TiXmlNode( TiXmlNode::DECLARATION ) { copy.CopyTo( this ); } void TiXmlDeclaration::operator=( const TiXmlDeclaration& copy ) { Clear(); copy.CopyTo( this ); } void TiXmlDeclaration::Print( FILE* cfile, int /*depth*/ ) const { fprintf (cfile, "<?xml "); if ( !version.empty() ) fprintf (cfile, "version=\"%s\" ", version.c_str ()); if ( !encoding.empty() ) fprintf (cfile, "encoding=\"%s\" ", encoding.c_str ()); if ( !standalone.empty() ) fprintf (cfile, "standalone=\"%s\" ", standalone.c_str ()); fprintf (cfile, "?>"); } void TiXmlDeclaration::StreamOut( TIXML_OSTREAM * stream ) const { (*stream) << "<?xml "; if ( !version.empty() ) { (*stream) << "version=\""; PutString( version, stream ); (*stream) << "\" "; } if ( !encoding.empty() ) { (*stream) << "encoding=\""; PutString( encoding, stream ); (*stream ) << "\" "; } if ( !standalone.empty() ) { (*stream) << "standalone=\""; PutString( standalone, stream ); (*stream) << "\" "; } (*stream) << "?>"; } void TiXmlDeclaration::CopyTo( TiXmlDeclaration* target ) const { TiXmlNode::CopyTo( target ); target->version = version; target->encoding = encoding; target->standalone = standalone; } TiXmlNode* TiXmlDeclaration::Clone() const { TiXmlDeclaration* clone = new TiXmlDeclaration(); if ( !clone ) return 0; CopyTo( clone ); return clone; } void TiXmlUnknown::Print( FILE* cfile, int depth ) const { for ( int i=0; i<depth; i++ ) fprintf( cfile, " " ); fprintf( cfile, "<%s>", value.c_str() ); } void TiXmlUnknown::StreamOut( TIXML_OSTREAM * stream ) const { (*stream) << "<" << value << ">"; // Don't use entities here! It is unknown. } void TiXmlUnknown::CopyTo( TiXmlUnknown* target ) const { TiXmlNode::CopyTo( target ); } TiXmlNode* TiXmlUnknown::Clone() const { TiXmlUnknown* clone = new TiXmlUnknown(); if ( !clone ) return 0; CopyTo( clone ); return clone; } TiXmlAttributeSet::TiXmlAttributeSet() { sentinel.next = &sentinel; sentinel.prev = &sentinel; } TiXmlAttributeSet::~TiXmlAttributeSet() { assert( sentinel.next == &sentinel ); assert( sentinel.prev == &sentinel ); } void TiXmlAttributeSet::Add( TiXmlAttribute* addMe ) { assert( !Find( addMe->Name() ) ); // Shouldn't be multiply adding to the set. addMe->next = &sentinel; addMe->prev = sentinel.prev; sentinel.prev->next = addMe; sentinel.prev = addMe; } void TiXmlAttributeSet::Remove( TiXmlAttribute* removeMe ) { TiXmlAttribute* node; for( node = sentinel.next; node != &sentinel; node = node->next ) { if ( node == removeMe ) { node->prev->next = node->next; node->next->prev = node->prev; node->next = 0; node->prev = 0; return; } } assert( 0 ); // we tried to remove a non-linked attribute. } const TiXmlAttribute* TiXmlAttributeSet::Find( const char * name ) const { const TiXmlAttribute* node; for( node = sentinel.next; node != &sentinel; node = node->next ) { if ( node->name == name ) return node; } return 0; } TiXmlAttribute* TiXmlAttributeSet::Find( const char * name ) { TiXmlAttribute* node; for( node = sentinel.next; node != &sentinel; node = node->next ) { if ( node->name == name ) return node; } return 0; } #ifdef TIXML_USE_STL TIXML_ISTREAM & operator >> (TIXML_ISTREAM & in, TiXmlNode & base) { TIXML_STRING tag; tag.reserve( 8 * 1000 ); base.StreamIn( &in, &tag ); base.Parse( tag.c_str(), 0, TIXML_DEFAULT_ENCODING ); return in; } #endif TIXML_OSTREAM & operator<< (TIXML_OSTREAM & out, const TiXmlNode & base) { base.StreamOut (& out); return out; } #ifdef TIXML_USE_STL std::string & operator<< (std::string& out, const TiXmlNode& base ) { std::ostringstream os_stream( std::ostringstream::out ); base.StreamOut( &os_stream ); out.append( os_stream.str() ); return out; } #endif TiXmlHandle TiXmlHandle::FirstChild() const { if ( node ) { TiXmlNode* child = node->FirstChild(); if ( child ) return TiXmlHandle( child ); } return TiXmlHandle( 0 ); } TiXmlHandle TiXmlHandle::FirstChild( const char * value ) const { if ( node ) { TiXmlNode* child = node->FirstChild( value ); if ( child ) return TiXmlHandle( child ); } return TiXmlHandle( 0 ); } TiXmlHandle TiXmlHandle::FirstChildElement() const { if ( node ) { TiXmlElement* child = node->FirstChildElement(); if ( child ) return TiXmlHandle( child ); } return TiXmlHandle( 0 ); } TiXmlHandle TiXmlHandle::FirstChildElement( const char * value ) const { if ( node ) { TiXmlElement* child = node->FirstChildElement( value ); if ( child ) return TiXmlHandle( child ); } return TiXmlHandle( 0 ); } TiXmlHandle TiXmlHandle::Child( int count ) const { if ( node ) { int i; TiXmlNode* child = node->FirstChild(); for ( i=0; child && i<count; child = child->NextSibling(), ++i ) { // nothing } if ( child ) return TiXmlHandle( child ); } return TiXmlHandle( 0 ); } TiXmlHandle TiXmlHandle::Child( const char* value, int count ) const { if ( node ) { int i; TiXmlNode* child = node->FirstChild( value ); for ( i=0; child && i<count; child = child->NextSibling( value ), ++i ) { // nothing } if ( child ) return TiXmlHandle( child ); } return TiXmlHandle( 0 ); } TiXmlHandle TiXmlHandle::ChildElement( int count ) const { if ( node ) { int i; TiXmlElement* child = node->FirstChildElement(); for ( i=0; child && i<count; child = child->NextSiblingElement(), ++i ) { // nothing } if ( child ) return TiXmlHandle( child ); } return TiXmlHandle( 0 ); } TiXmlHandle TiXmlHandle::ChildElement( const char* value, int count ) const { if ( node ) { int i; TiXmlElement* child = node->FirstChildElement( value ); for ( i=0; child && i<count; child = child->NextSiblingElement( value ), ++i ) { // nothing } if ( child ) return TiXmlHandle( child ); } return TiXmlHandle( 0 ); }
gpl-3.0
zero-ui/miniblink49
third_party/skia/src/effects/SkXfermodeImageFilter.cpp
6
7318
/* * Copyright 2013 The Android Open Source Project * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkXfermodeImageFilter.h" #include "SkCanvas.h" #include "SkDevice.h" #include "SkColorPriv.h" #include "SkReadBuffer.h" #include "SkWriteBuffer.h" #include "SkXfermode.h" #if SK_SUPPORT_GPU #include "GrContext.h" #include "GrDrawContext.h" #include "effects/GrTextureDomain.h" #include "SkGr.h" #endif /////////////////////////////////////////////////////////////////////////////// SkXfermodeImageFilter::SkXfermodeImageFilter(SkXfermode* mode, SkImageFilter* inputs[2], const CropRect* cropRect) : INHERITED(2, inputs, cropRect), fMode(mode) { SkSafeRef(fMode); } SkXfermodeImageFilter::~SkXfermodeImageFilter() { SkSafeUnref(fMode); } SkFlattenable* SkXfermodeImageFilter::CreateProc(SkReadBuffer& buffer) { SK_IMAGEFILTER_UNFLATTEN_COMMON(common, 2); SkAutoTUnref<SkXfermode> mode(buffer.readXfermode()); return Create(mode, common.getInput(0), common.getInput(1), &common.cropRect()); } void SkXfermodeImageFilter::flatten(SkWriteBuffer& buffer) const { this->INHERITED::flatten(buffer); buffer.writeFlattenable(fMode); } bool SkXfermodeImageFilter::onFilterImage(Proxy* proxy, const SkBitmap& src, const Context& ctx, SkBitmap* dst, SkIPoint* offset) const { SkBitmap background = src, foreground = src; SkImageFilter* backgroundInput = getInput(0); SkImageFilter* foregroundInput = getInput(1); SkIPoint backgroundOffset = SkIPoint::Make(0, 0); if (backgroundInput && !backgroundInput->filterImage(proxy, src, ctx, &background, &backgroundOffset)) { background.reset(); } SkIPoint foregroundOffset = SkIPoint::Make(0, 0); if (foregroundInput && !foregroundInput->filterImage(proxy, src, ctx, &foreground, &foregroundOffset)) { foreground.reset(); } SkIRect bounds, foregroundBounds; if (!applyCropRect(ctx, foreground, foregroundOffset, &foregroundBounds)) { foregroundBounds.setEmpty(); foreground.reset(); } if (!applyCropRect(ctx, background, backgroundOffset, &bounds)) { bounds.setEmpty(); background.reset(); } bounds.join(foregroundBounds); if (bounds.isEmpty()) { return false; } SkAutoTUnref<SkBaseDevice> device(proxy->createDevice(bounds.width(), bounds.height())); if (NULL == device.get()) { return false; } SkCanvas canvas(device); canvas.translate(SkIntToScalar(-bounds.left()), SkIntToScalar(-bounds.top())); SkPaint paint; paint.setXfermodeMode(SkXfermode::kSrc_Mode); canvas.drawBitmap(background, SkIntToScalar(backgroundOffset.fX), SkIntToScalar(backgroundOffset.fY), &paint); paint.setXfermode(fMode); canvas.drawBitmap(foreground, SkIntToScalar(foregroundOffset.fX), SkIntToScalar(foregroundOffset.fY), &paint); canvas.clipRect(SkRect::Make(foregroundBounds), SkRegion::kDifference_Op); paint.setColor(SK_ColorTRANSPARENT); canvas.drawPaint(paint); *dst = device->accessBitmap(false); offset->fX = bounds.left(); offset->fY = bounds.top(); return true; } #ifndef SK_IGNORE_TO_STRING void SkXfermodeImageFilter::toString(SkString* str) const { str->appendf("SkXfermodeImageFilter: ("); str->appendf("xfermode: ("); if (fMode) { fMode->toString(str); } str->append(")"); if (this->getInput(0)) { str->appendf("foreground: ("); this->getInput(0)->toString(str); str->appendf(")"); } if (this->getInput(1)) { str->appendf("background: ("); this->getInput(1)->toString(str); str->appendf(")"); } str->append(")"); } #endif #if SK_SUPPORT_GPU bool SkXfermodeImageFilter::canFilterImageGPU() const { return fMode && fMode->asFragmentProcessor(NULL, NULL, NULL) && !cropRectIsSet(); } bool SkXfermodeImageFilter::filterImageGPU(Proxy* proxy, const SkBitmap& src, const Context& ctx, SkBitmap* result, SkIPoint* offset) const { SkBitmap background = src; SkIPoint backgroundOffset = SkIPoint::Make(0, 0); if (getInput(0) && !getInput(0)->getInputResultGPU(proxy, src, ctx, &background, &backgroundOffset)) { return onFilterImage(proxy, src, ctx, result, offset); } GrTexture* backgroundTex = background.getTexture(); if (NULL == backgroundTex) { SkASSERT(false); return false; } SkBitmap foreground = src; SkIPoint foregroundOffset = SkIPoint::Make(0, 0); if (getInput(1) && !getInput(1)->getInputResultGPU(proxy, src, ctx, &foreground, &foregroundOffset)) { return onFilterImage(proxy, src, ctx, result, offset); } GrTexture* foregroundTex = foreground.getTexture(); GrContext* context = foregroundTex->getContext(); GrFragmentProcessor* xferProcessor = NULL; GrSurfaceDesc desc; desc.fFlags = kRenderTarget_GrSurfaceFlag; desc.fWidth = src.width(); desc.fHeight = src.height(); desc.fConfig = kSkia8888_GrPixelConfig; SkAutoTUnref<GrTexture> dst(context->textureProvider()->refScratchTexture( desc, GrTextureProvider::kApprox_ScratchTexMatch)); if (!dst) { return false; } GrPaint paint; if (!fMode || !fMode->asFragmentProcessor(&xferProcessor, paint.getProcessorDataManager(), backgroundTex)) { // canFilterImageGPU() should've taken care of this SkASSERT(false); return false; } SkMatrix foregroundMatrix = GrCoordTransform::MakeDivByTextureWHMatrix(foregroundTex); foregroundMatrix.preTranslate(SkIntToScalar(backgroundOffset.fX-foregroundOffset.fX), SkIntToScalar(backgroundOffset.fY-foregroundOffset.fY)); SkRect srcRect; src.getBounds(&srcRect); SkAutoTUnref<GrFragmentProcessor> foregroundDomain(GrTextureDomainEffect::Create( paint.getProcessorDataManager(), foregroundTex, foregroundMatrix, GrTextureDomain::MakeTexelDomain(foregroundTex, foreground.bounds()), GrTextureDomain::kDecal_Mode, GrTextureParams::kNone_FilterMode) ); paint.addColorProcessor(foregroundDomain.get()); paint.addColorProcessor(xferProcessor)->unref(); GrDrawContext* drawContext = context->drawContext(); if (!drawContext) { return false; } drawContext->drawRect(dst->asRenderTarget(), GrClip::WideOpen(), paint, SkMatrix::I(), srcRect); offset->fX = backgroundOffset.fX; offset->fY = backgroundOffset.fY; WrapTexture(dst, src.width(), src.height(), result); return true; } #endif
gpl-3.0
ChrisAndre/pykep
src/third_party/cspice/shiftr.c
7
6746
/* shiftr.f -- translated by f2c (version 19980913). You must link the resulting object file with the libraries: -lf2c -lm (in that order) */ #include "f2c.h" /* $Procedure SHIFTR ( Shift right ) */ /* Subroutine */ int shiftr_(char *in, integer *nshift, char *fillc, char * out, ftnlen in_len, ftnlen fillc_len, ftnlen out_len) { /* System generated locals */ integer i__1, i__2; /* Builtin functions */ integer i_len(char *, ftnlen); /* Subroutine */ int s_copy(char *, char *, ftnlen, ftnlen); /* Local variables */ integer i__, n, s, nfill, inlen, nsave, outlen; /* $ Abstract */ /* Shift the contents of a character string to the right. */ /* Characters moved past the end of the input string are */ /* lost. Vacant spaces are filled with a specified character. */ /* $ Disclaimer */ /* THIS SOFTWARE AND ANY RELATED MATERIALS WERE CREATED BY THE */ /* CALIFORNIA INSTITUTE OF TECHNOLOGY (CALTECH) UNDER A U.S. */ /* GOVERNMENT CONTRACT WITH THE NATIONAL AERONAUTICS AND SPACE */ /* ADMINISTRATION (NASA). THE SOFTWARE IS TECHNOLOGY AND SOFTWARE */ /* PUBLICLY AVAILABLE UNDER U.S. EXPORT LAWS AND IS PROVIDED "AS-IS" */ /* TO THE RECIPIENT WITHOUT WARRANTY OF ANY KIND, INCLUDING ANY */ /* WARRANTIES OF PERFORMANCE OR MERCHANTABILITY OR FITNESS FOR A */ /* PARTICULAR USE OR PURPOSE (AS SET FORTH IN UNITED STATES UCC */ /* SECTIONS 2312-2313) OR FOR ANY PURPOSE WHATSOEVER, FOR THE */ /* SOFTWARE AND RELATED MATERIALS, HOWEVER USED. */ /* IN NO EVENT SHALL CALTECH, ITS JET PROPULSION LABORATORY, OR NASA */ /* BE LIABLE FOR ANY DAMAGES AND/OR COSTS, INCLUDING, BUT NOT */ /* LIMITED TO, INCIDENTAL OR CONSEQUENTIAL DAMAGES OF ANY KIND, */ /* INCLUDING ECONOMIC DAMAGE OR INJURY TO PROPERTY AND LOST PROFITS, */ /* REGARDLESS OF WHETHER CALTECH, JPL, OR NASA BE ADVISED, HAVE */ /* REASON TO KNOW, OR, IN FACT, SHALL KNOW OF THE POSSIBILITY. */ /* RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF */ /* THE SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY */ /* CALTECH AND NASA FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE */ /* ACTIONS OF RECIPIENT IN THE USE OF THE SOFTWARE. */ /* $ Required_Reading */ /* None. */ /* $ Keywords */ /* CHARACTER, UTILITY */ /* $ Declarations */ /* $ Brief_I/O */ /* VARIABLE I/O DESCRIPTION */ /* -------- --- -------------------------------------------------- */ /* IN I Input string. */ /* NSHIFT I Number of times to shift. */ /* FILLC I Character to fill spaces left vacant. */ /* OUT O Shifted string. */ /* $ Detailed_Input */ /* IN is the input character string. */ /* NSHIFT is the number of times the string is to be */ /* shifted. If NSHIFT is negative, OUT will be */ /* identical to IN. */ /* FILLC is the character with which spaces left vacant by */ /* the shift are to be filled. */ /* $ Detailed_Output */ /* OUT is the output string. This is the input string, */ /* shifted N times, filled with FILLC. */ /* OUT may overwrite IN. */ /* $ Parameters */ /* None. */ /* $ Particulars */ /* As a string is shifted left or right, the leftmost or */ /* rightmost characters of the string disappear (as if pushed */ /* off the end of the string). This is true regardless of */ /* the length of the output string. */ /* The remaining characters are shifted simultaneously, and */ /* the spaces vacated by those characters are filled with a */ /* replacement character. */ /* $ Examples */ /* If FILLC = ' ' */ /* 'abcde' shifted left twice becomes 'cde ' */ /* 'abcde' shifted right once becomes ' abcd' */ /* If FILLC = '.' */ /* '12345 ' shifted right once becomes '.12345' */ /* 'Apple ' shifted left ten times becomes '......' */ /* Given the declarations */ /* CHARACTER*3 SHORT */ /* CHARACTER*10 LONG */ /* The calls */ /* CALL SHIFTR ( 'abcde ', 2, '-', SHORT ) */ /* CALL SHIFTR ( 'abcde ', 2, '-', LONG ) */ /* yield the strings */ /* SHORT = '--a' */ /* LONG = '--abcd ' */ /* while the calls */ /* CALL SHIFTL ( 'abcde ', 2, '-', SHORT ) */ /* CALL SHIFTL ( 'abcde ', 2, '-', LONG ) */ /* yield the strings */ /* SHORT = 'cde' */ /* LONG = 'cde .. ' */ /* $ Restrictions */ /* None. */ /* $ Exceptions */ /* Error free. */ /* $ Files */ /* None. */ /* $ Author_and_Institution */ /* M.J. Spencer (JPL) */ /* I.M. Underwood (JPL) */ /* $ Literature_References */ /* None. */ /* $ Version */ /* - SPICELIB Version 2.0.1, 22-AUG-2001 (EDW) */ /* Corrected ENDDO to END DO. */ /* - SPICELIB Version 2.0.0, 01-SEP-1994 (MJS) */ /* This version correctly handles negative shifts. */ /* - SPICELIB Version 1.0.1, 10-MAR-1992 (WLT) */ /* Comment section for permuted index source lines was added */ /* following the header. */ /* - SPICELIB Version 1.0.0, 31-JAN-1990 (IMU) */ /* -& */ /* $ Index_Entries */ /* shift right */ /* -& */ /* Local variables */ /* Get the length of the input, output strings. */ inlen = i_len(in, in_len); outlen = i_len(out, out_len); /* If the shift is zero or negative, the string is not changed. */ /* If longer than the input string, the entire string is shifted. */ s = max(*nshift,0); n = min(inlen,s); /* Figure out how many characters in the input string will */ /* be saved (will not be shifted off the end of the string, */ /* and will fit in the output string), and how many fill */ /* characters will be needed (no more than NSHIFT, no fewer */ /* than zero). */ /* Computing MAX */ i__1 = 0, i__2 = inlen - outlen; nsave = inlen - n - max(i__1,i__2); nfill = min(n,outlen); /* Move the saved characters to output. */ for (i__ = nsave; i__ >= 1; --i__) { i__1 = i__ + s - 1; s_copy(out + i__1, in + (i__ - 1), i__ + s - i__1, (ftnlen)1); } /* Add as many fill characters as appropriate. */ i__1 = nfill; for (i__ = 1; i__ <= i__1; ++i__) { *(unsigned char *)&out[i__ - 1] = *(unsigned char *)fillc; } /* Pad the output string with blanks (to cover any previous */ /* ugliness there). */ if (outlen > inlen) { i__1 = inlen; s_copy(out + i__1, " ", out_len - i__1, (ftnlen)1); } return 0; } /* shiftr_ */
gpl-3.0
aoighost/radare2
libr/bin/pdb/stream_file.c
7
4089
#include "stream_file.h" /////////////////////////////////////////////////////////////////////////////// /// size = -1 (default value) /// pages_size = 0x1000 (default value) //////////////////////////////////////////////////////////////////////////////// int init_r_stream_file(R_STREAM_FILE *stream_file, RBuffer *buf, int *pages, int pages_amount, int size, int page_size) { stream_file->error = 0; stream_file->buf = buf; stream_file->pages = pages; stream_file->pages_amount = pages_amount; stream_file->page_size = page_size; if (size == -1) { stream_file->end = pages_amount * page_size; } else { stream_file->end = size; } stream_file->pos = 0; return 1; } /////////////////////////////////////////////////////////////////////////////// static void stream_file_read_pages(R_STREAM_FILE *stream_file, int start_indx, int end_indx, char *res) { int i; int page_offset; // int tmp; // char buffer[1024]; if ((end_indx - start_indx) > stream_file->end) { stream_file->error = READ_PAGE_FAIL; return; } end_indx = R_MIN (end_indx, stream_file->pages_amount); for (i = start_indx; i < end_indx; i++) { // tmp = stream_file->pages[i]; page_offset = stream_file->pages[i] * stream_file->page_size; if (page_offset<1) return; stream_file->buf->cur = page_offset; r_buf_read_at (stream_file->buf, page_offset, (ut8*)res, stream_file->page_size); // fseek(stream_file->fp, page_offset, SEEK_SET); // curr_pos = ftell(stream_file->fp); // fread(res, stream_file->page_size, 1, stream_file->fp); res += stream_file->page_size; } } // size by default = -1 /////////////////////////////////////////////////////////////////////////////// void stream_file_read(R_STREAM_FILE *stream_file, int size, char *res) { int pn_start, off_start, pn_end, off_end; char *pdata = 0; char *tmp; if (size == -1) { pdata = (char *) malloc(stream_file->pages_amount * stream_file->page_size); GET_PAGE(pn_start, off_start, stream_file->pos, stream_file->page_size); (void)off_end; // hack for remove unused warning tmp = pdata; stream_file_read_pages(stream_file, 0, stream_file->pages_amount, tmp); stream_file->pos = stream_file->end; memcpy(res, pdata + off_start, stream_file->end - off_start); free(pdata); } else { GET_PAGE(pn_start, off_start, stream_file->pos, stream_file->page_size); GET_PAGE(pn_end, off_end, stream_file->pos + size, stream_file->page_size); (void)off_end; // hack for remove unused warning pdata = (char *) malloc(stream_file->page_size * (pn_end + 1 - pn_start)); if (!pdata) return; tmp = pdata; stream_file_read_pages(stream_file, pn_start, pn_end + 1, tmp); stream_file->pos += size; memcpy(res, pdata + off_start, size); free (pdata); } } /////////////////////////////////////////////////////////////////////////////// void stream_file_seek(R_STREAM_FILE *stream_file, int offset, int whence) { switch (whence) { case 0: stream_file->pos = offset; break; case 1: stream_file->pos += offset; break; case 2: stream_file->pos = stream_file->end + offset; break; default: break; } if (stream_file->pos < 0) stream_file->pos = 0; if (stream_file->pos > stream_file->end) stream_file->pos = stream_file->end; } /////////////////////////////////////////////////////////////////////////////// int stream_file_tell(R_STREAM_FILE *stream_file) { return stream_file->pos; } /////////////////////////////////////////////////////////////////////////////// void stream_file_get_data(R_STREAM_FILE *stream_file, char *data) { int pos = 0; pos = stream_file_tell(stream_file); stream_file_seek(stream_file, 0, 0); stream_file_read(stream_file, -1, data); stream_file_seek(stream_file, pos, 0); } /////////////////////////////////////////////////////////////////////////////// void stream_file_get_size(R_STREAM_FILE *stream_file, int *data_size) { int pn_start = 0, off_start = 0; GET_PAGE(pn_start, off_start, stream_file->pos, stream_file->page_size); (void)pn_start; // hack for remove unused warning *data_size = stream_file->end - off_start; }
gpl-3.0
chriskmanx/qmole
QMOLEDEV/clang-3.1.src/test/SemaCXX/warn-unused-variables.cpp
8
2418
// RUN: %clang_cc1 -fsyntax-only -Wunused-variable -verify %s template<typename T> void f() { T t; t = 17; } // PR5407 struct A { A(); }; struct B { ~B(); }; void f() { A a; B b; } // PR5531 namespace PR5531 { struct A { }; struct B { B(int); }; struct C { ~C(); }; void test() { A(); B(17); C(); } } template<typename T> struct X0 { }; template<typename T> void test_dependent_init(T *p) { X0<int> i(p); (void)i; } namespace PR6948 { template<typename T> class X; void f() { X<char> str (read_from_file()); // expected-error{{use of undeclared identifier 'read_from_file'}} } } void unused_local_static() { static int x = 0; static int y = 0; // expected-warning{{unused variable 'y'}} #pragma unused(x) } // PR10168 namespace PR10168 { // We expect a warning in the definition only for non-dependent variables, and // a warning in the instantiation only for dependent variables. template<typename T> struct S { void f() { int a; // expected-warning {{unused variable 'a'}} T b; // expected-warning 2{{unused variable 'b'}} } }; template<typename T> void f() { int a; // expected-warning {{unused variable 'a'}} T b; // expected-warning 2{{unused variable 'b'}} } void g() { S<int>().f(); // expected-note {{here}} S<char>().f(); // expected-note {{here}} f<int>(); // expected-note {{here}} f<char>(); // expected-note {{here}} } } namespace PR11550 { struct S1 { S1(); }; S1 makeS1(); void testS1(S1 a) { // This constructor call can be elided. S1 x = makeS1(); // expected-warning {{unused variable 'x'}} // This one cannot, so no warning. S1 y; // This call cannot, but the constructor is trivial. S1 z = a; // expected-warning {{unused variable 'z'}} } // The same is true even when we know thet constructor has side effects. void foo(); struct S2 { S2() { foo(); } }; S2 makeS2(); void testS2(S2 a) { S2 x = makeS2(); // expected-warning {{unused variable 'x'}} S2 y; S2 z = a; // expected-warning {{unused variable 'z'}} } // Or when the constructor is not declared by the user. struct S3 { S1 m; }; S3 makeS3(); void testS3(S3 a) { S3 x = makeS3(); // expected-warning {{unused variable 'x'}} S3 y; S3 z = a; // expected-warning {{unused variable 'z'}} } }
gpl-3.0
BioWu/variationtoolkit
src/fastareader.cpp
8
2071
#include <cstdio> #include <cctype> #include "throw.h" #include "fastareader.h" using namespace std; const int32_t FastaSequence::DEFAULT_LINE_LENGTH=60; FastaSequence::FastaSequence() {} FastaSequence::FastaSequence(const FastaSequence& cp):_name(cp._name),_seq(cp._seq) { } FastaSequence::~FastaSequence() { } char FastaSequence::at(int32_t index) const { return _seq.at(index); } int32_t FastaSequence::size() const { return (int32_t)_seq.size(); } const char* FastaSequence::name() const { return _name.c_str(); } const char* FastaSequence::c_str() const { return _seq.c_str(); } FastaSequence& FastaSequence::operator=(const FastaSequence& cp) { if(this!=&cp) { _name.assign(cp._name); _seq.assign(cp._seq); } return *this; } void FastaSequence::printFasta(std::ostream& out,int32_t lineLength) const { out << ">" << _name; for(int32_t i=0;i< size();++i) { if(i%lineLength==0) out << std::endl; out << at(i); } out << std::endl; } void FastaSequence::printFasta(std::ostream& out) { printFasta(out,DEFAULT_LINE_LENGTH); } FastaReader::FastaReader():_reserve(BUFSIZ),to_upper(false) { } FastaReader::~FastaReader() { } FastaReader& FastaReader::reserve(int32_t len) { this->_reserve=(len<=0?BUFSIZ:len); return *this; } FastaReader& FastaReader::toupper(bool choice) { this->to_upper=choice; return *this; } std::auto_ptr<FastaSequence> FastaReader::next(std::istream& in) { std::auto_ptr<FastaSequence> ret(0); if(!in.good() || in.eof()) return ret; int c; while((c=in.get())!=EOF) { if(c=='>') { if(ret.get()!=0) { in.unget(); return ret; } ret.reset(new FastaSequence); ret->_seq.reserve(_reserve); while((c=in.get())!=EOF && c!='\n') { if(c=='\r') continue; ret->_name+=(char)c; } continue; } if(std::isspace(c)) continue; if(!std::isalpha(c)) THROW("Bad char in sequence " << (char)c ) ; if(ret.get()==0) THROW("header missing"); if(to_upper) c=std::toupper(c); ret->_seq+=(char)c; } return ret; }
gpl-3.0
10045125/xuggle-xuggler
captive/spandsp/csrc/src/awgn.c
8
4730
/* * SpanDSP - a series of DSP components for telephony * * awgn.c - An additive Gaussian white noise generator * * Written by Steve Underwood <steveu@coppice.org> * * Copyright (C) 2001 Steve Underwood * * All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 2.1, * 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /*! \file */ /* This code is based on some demonstration code in a research paper somewhere. I can't track down where I got the original from, so that due recognition can be given. The original had no explicit copyright notice, and I hope nobody objects to its use here. Having a reasonable Gaussian noise generator is pretty important for telephony testing (in fact, pretty much any DSP testing), and this one seems to have served me OK. Since the generation of Gaussian noise is only for test purposes, and not a core system component, I don't intend to worry excessively about copyright issues, unless someone worries me. The non-core nature of this code also explains why it is unlikely to ever be optimised. */ #if defined(HAVE_CONFIG_H) #include "config.h" #endif #include <stdlib.h> #include <inttypes.h> #if defined(HAVE_TGMATH_H) #include <tgmath.h> #endif #if defined(HAVE_MATH_H) #include <math.h> #endif #include "floating_fudge.h" #include "spandsp/telephony.h" #include "spandsp/fast_convert.h" #include "spandsp/saturated.h" #include "spandsp/awgn.h" #include "spandsp/private/awgn.h" /* Gaussian noise generator constants */ #define M1 259200 #define IA1 7141 #define IC1 54773 #define RM1 (1.0/M1) #define M2 134456 #define IA2 8121 #define IC2 28411 #define RM2 (1.0/M2) #define M3 243000 #define IA3 4561 #define IC3 51349 static double ran1(awgn_state_t *s) { double temp; int j; s->ix1 = (IA1*s->ix1 + IC1)%M1; s->ix2 = (IA2*s->ix2 + IC2)%M2; s->ix3 = (IA3*s->ix3 + IC3)%M3; j = 1 + ((97*s->ix3)/M3); if (j > 97 || j < 1) { /* Error */ return -1; } temp = s->r[j]; s->r[j] = (s->ix1 + s->ix2*RM2)*RM1; return temp; } /*- End of function --------------------------------------------------------*/ SPAN_DECLARE(awgn_state_t *) awgn_init_dbov(awgn_state_t *s, int idum, float level) { int j; if (s == NULL) { if ((s = (awgn_state_t *) malloc(sizeof(*s))) == NULL) return NULL; } if (idum < 0) idum = -idum; s->rms = pow(10.0, level/20.0)*32768.0; s->ix1 = (IC1 + idum)%M1; s->ix1 = (IA1*s->ix1 + IC1)%M1; s->ix2 = s->ix1%M2; s->ix1 = (IA1*s->ix1 + IC1)%M1; s->ix3 = s->ix1%M3; s->r[0] = 0.0; for (j = 1; j <= 97; j++) { s->ix1 = (IA1*s->ix1 + IC1)%M1; s->ix2 = (IA2*s->ix2 + IC2)%M2; s->r[j] = (s->ix1 + s->ix2*RM2)*RM1; } s->gset = 0.0; s->iset = 0; return s; } /*- End of function --------------------------------------------------------*/ SPAN_DECLARE(awgn_state_t *) awgn_init_dbm0(awgn_state_t *s, int idum, float level) { return awgn_init_dbov(s, idum, level - DBM0_MAX_POWER); } /*- End of function --------------------------------------------------------*/ SPAN_DECLARE(int) awgn_release(awgn_state_t *s) { return 0; } /*- End of function --------------------------------------------------------*/ SPAN_DECLARE(int) awgn_free(awgn_state_t *s) { free(s); return 0; } /*- End of function --------------------------------------------------------*/ SPAN_DECLARE(int16_t) awgn(awgn_state_t *s) { double fac; double r; double v1; double v2; double amp; if (s->iset == 0) { do { v1 = 2.0*ran1(s) - 1.0; v2 = 2.0*ran1(s) - 1.0; r = v1*v1 + v2*v2; } while (r >= 1.0); fac = sqrt(-2.0*log(r)/r); s->gset = v1*fac; s->iset = 1; amp = v2*fac*s->rms; } else { s->iset = 0; amp = s->gset*s->rms; } return fsaturate(amp); } /*- End of function --------------------------------------------------------*/ /*- End of file ------------------------------------------------------------*/
gpl-3.0
jeffreytinkess/OS_A2
src/extern/acpica/source/components/resources/rsxface.c
8
26933
/******************************************************************************* * * Module Name: rsxface - Public interfaces to the resource manager * ******************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2015, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * *****************************************************************************/ #define EXPORT_ACPI_INTERFACES #include "acpi.h" #include "accommon.h" #include "acresrc.h" #include "acnamesp.h" #define _COMPONENT ACPI_RESOURCES ACPI_MODULE_NAME ("rsxface") /* Local macros for 16,32-bit to 64-bit conversion */ #define ACPI_COPY_FIELD(Out, In, Field) ((Out)->Field = (In)->Field) #define ACPI_COPY_ADDRESS(Out, In) \ ACPI_COPY_FIELD(Out, In, ResourceType); \ ACPI_COPY_FIELD(Out, In, ProducerConsumer); \ ACPI_COPY_FIELD(Out, In, Decode); \ ACPI_COPY_FIELD(Out, In, MinAddressFixed); \ ACPI_COPY_FIELD(Out, In, MaxAddressFixed); \ ACPI_COPY_FIELD(Out, In, Info); \ ACPI_COPY_FIELD(Out, In, Address.Granularity); \ ACPI_COPY_FIELD(Out, In, Address.Minimum); \ ACPI_COPY_FIELD(Out, In, Address.Maximum); \ ACPI_COPY_FIELD(Out, In, Address.TranslationOffset); \ ACPI_COPY_FIELD(Out, In, Address.AddressLength); \ ACPI_COPY_FIELD(Out, In, ResourceSource); /* Local prototypes */ static ACPI_STATUS AcpiRsMatchVendorResource ( ACPI_RESOURCE *Resource, void *Context); static ACPI_STATUS AcpiRsValidateParameters ( ACPI_HANDLE DeviceHandle, ACPI_BUFFER *Buffer, ACPI_NAMESPACE_NODE **ReturnNode); /******************************************************************************* * * FUNCTION: AcpiRsValidateParameters * * PARAMETERS: DeviceHandle - Handle to a device * Buffer - Pointer to a data buffer * ReturnNode - Pointer to where the device node is returned * * RETURN: Status * * DESCRIPTION: Common parameter validation for resource interfaces * ******************************************************************************/ static ACPI_STATUS AcpiRsValidateParameters ( ACPI_HANDLE DeviceHandle, ACPI_BUFFER *Buffer, ACPI_NAMESPACE_NODE **ReturnNode) { ACPI_STATUS Status; ACPI_NAMESPACE_NODE *Node; ACPI_FUNCTION_TRACE (RsValidateParameters); /* * Must have a valid handle to an ACPI device */ if (!DeviceHandle) { return_ACPI_STATUS (AE_BAD_PARAMETER); } Node = AcpiNsValidateHandle (DeviceHandle); if (!Node) { return_ACPI_STATUS (AE_BAD_PARAMETER); } if (Node->Type != ACPI_TYPE_DEVICE) { return_ACPI_STATUS (AE_TYPE); } /* * Validate the user buffer object * * if there is a non-zero buffer length we also need a valid pointer in * the buffer. If it's a zero buffer length, we'll be returning the * needed buffer size (later), so keep going. */ Status = AcpiUtValidateBuffer (Buffer); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } *ReturnNode = Node; return_ACPI_STATUS (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiGetIrqRoutingTable * * PARAMETERS: DeviceHandle - Handle to the Bus device we are querying * RetBuffer - Pointer to a buffer to receive the * current resources for the device * * RETURN: Status * * DESCRIPTION: This function is called to get the IRQ routing table for a * specific bus. The caller must first acquire a handle for the * desired bus. The routine table is placed in the buffer pointed * to by the RetBuffer variable parameter. * * If the function fails an appropriate status will be returned * and the value of RetBuffer is undefined. * * This function attempts to execute the _PRT method contained in * the object indicated by the passed DeviceHandle. * ******************************************************************************/ ACPI_STATUS AcpiGetIrqRoutingTable ( ACPI_HANDLE DeviceHandle, ACPI_BUFFER *RetBuffer) { ACPI_STATUS Status; ACPI_NAMESPACE_NODE *Node; ACPI_FUNCTION_TRACE (AcpiGetIrqRoutingTable); /* Validate parameters then dispatch to internal routine */ Status = AcpiRsValidateParameters (DeviceHandle, RetBuffer, &Node); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } Status = AcpiRsGetPrtMethodData (Node, RetBuffer); return_ACPI_STATUS (Status); } ACPI_EXPORT_SYMBOL (AcpiGetIrqRoutingTable) /******************************************************************************* * * FUNCTION: AcpiGetCurrentResources * * PARAMETERS: DeviceHandle - Handle to the device object for the * device we are querying * RetBuffer - Pointer to a buffer to receive the * current resources for the device * * RETURN: Status * * DESCRIPTION: This function is called to get the current resources for a * specific device. The caller must first acquire a handle for * the desired device. The resource data is placed in the buffer * pointed to by the RetBuffer variable parameter. * * If the function fails an appropriate status will be returned * and the value of RetBuffer is undefined. * * This function attempts to execute the _CRS method contained in * the object indicated by the passed DeviceHandle. * ******************************************************************************/ ACPI_STATUS AcpiGetCurrentResources ( ACPI_HANDLE DeviceHandle, ACPI_BUFFER *RetBuffer) { ACPI_STATUS Status; ACPI_NAMESPACE_NODE *Node; ACPI_FUNCTION_TRACE (AcpiGetCurrentResources); /* Validate parameters then dispatch to internal routine */ Status = AcpiRsValidateParameters (DeviceHandle, RetBuffer, &Node); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } Status = AcpiRsGetCrsMethodData (Node, RetBuffer); return_ACPI_STATUS (Status); } ACPI_EXPORT_SYMBOL (AcpiGetCurrentResources) /******************************************************************************* * * FUNCTION: AcpiGetPossibleResources * * PARAMETERS: DeviceHandle - Handle to the device object for the * device we are querying * RetBuffer - Pointer to a buffer to receive the * resources for the device * * RETURN: Status * * DESCRIPTION: This function is called to get a list of the possible resources * for a specific device. The caller must first acquire a handle * for the desired device. The resource data is placed in the * buffer pointed to by the RetBuffer variable. * * If the function fails an appropriate status will be returned * and the value of RetBuffer is undefined. * ******************************************************************************/ ACPI_STATUS AcpiGetPossibleResources ( ACPI_HANDLE DeviceHandle, ACPI_BUFFER *RetBuffer) { ACPI_STATUS Status; ACPI_NAMESPACE_NODE *Node; ACPI_FUNCTION_TRACE (AcpiGetPossibleResources); /* Validate parameters then dispatch to internal routine */ Status = AcpiRsValidateParameters (DeviceHandle, RetBuffer, &Node); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } Status = AcpiRsGetPrsMethodData (Node, RetBuffer); return_ACPI_STATUS (Status); } ACPI_EXPORT_SYMBOL (AcpiGetPossibleResources) /******************************************************************************* * * FUNCTION: AcpiSetCurrentResources * * PARAMETERS: DeviceHandle - Handle to the device object for the * device we are setting resources * InBuffer - Pointer to a buffer containing the * resources to be set for the device * * RETURN: Status * * DESCRIPTION: This function is called to set the current resources for a * specific device. The caller must first acquire a handle for * the desired device. The resource data is passed to the routine * the buffer pointed to by the InBuffer variable. * ******************************************************************************/ ACPI_STATUS AcpiSetCurrentResources ( ACPI_HANDLE DeviceHandle, ACPI_BUFFER *InBuffer) { ACPI_STATUS Status; ACPI_NAMESPACE_NODE *Node; ACPI_FUNCTION_TRACE (AcpiSetCurrentResources); /* Validate the buffer, don't allow zero length */ if ((!InBuffer) || (!InBuffer->Pointer) || (!InBuffer->Length)) { return_ACPI_STATUS (AE_BAD_PARAMETER); } /* Validate parameters then dispatch to internal routine */ Status = AcpiRsValidateParameters (DeviceHandle, InBuffer, &Node); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } Status = AcpiRsSetSrsMethodData (Node, InBuffer); return_ACPI_STATUS (Status); } ACPI_EXPORT_SYMBOL (AcpiSetCurrentResources) /******************************************************************************* * * FUNCTION: AcpiGetEventResources * * PARAMETERS: DeviceHandle - Handle to the device object for the * device we are getting resources * InBuffer - Pointer to a buffer containing the * resources to be set for the device * * RETURN: Status * * DESCRIPTION: This function is called to get the event resources for a * specific device. The caller must first acquire a handle for * the desired device. The resource data is passed to the routine * the buffer pointed to by the InBuffer variable. Uses the * _AEI method. * ******************************************************************************/ ACPI_STATUS AcpiGetEventResources ( ACPI_HANDLE DeviceHandle, ACPI_BUFFER *RetBuffer) { ACPI_STATUS Status; ACPI_NAMESPACE_NODE *Node; ACPI_FUNCTION_TRACE (AcpiGetEventResources); /* Validate parameters then dispatch to internal routine */ Status = AcpiRsValidateParameters (DeviceHandle, RetBuffer, &Node); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } Status = AcpiRsGetAeiMethodData (Node, RetBuffer); return_ACPI_STATUS (Status); } ACPI_EXPORT_SYMBOL (AcpiGetEventResources) /****************************************************************************** * * FUNCTION: AcpiResourceToAddress64 * * PARAMETERS: Resource - Pointer to a resource * Out - Pointer to the users's return buffer * (a struct acpi_resource_address64) * * RETURN: Status * * DESCRIPTION: If the resource is an address16, address32, or address64, * copy it to the address64 return buffer. This saves the * caller from having to duplicate code for different-sized * addresses. * ******************************************************************************/ ACPI_STATUS AcpiResourceToAddress64 ( ACPI_RESOURCE *Resource, ACPI_RESOURCE_ADDRESS64 *Out) { ACPI_RESOURCE_ADDRESS16 *Address16; ACPI_RESOURCE_ADDRESS32 *Address32; if (!Resource || !Out) { return (AE_BAD_PARAMETER); } /* Convert 16 or 32 address descriptor to 64 */ switch (Resource->Type) { case ACPI_RESOURCE_TYPE_ADDRESS16: Address16 = ACPI_CAST_PTR (ACPI_RESOURCE_ADDRESS16, &Resource->Data); ACPI_COPY_ADDRESS (Out, Address16); break; case ACPI_RESOURCE_TYPE_ADDRESS32: Address32 = ACPI_CAST_PTR (ACPI_RESOURCE_ADDRESS32, &Resource->Data); ACPI_COPY_ADDRESS (Out, Address32); break; case ACPI_RESOURCE_TYPE_ADDRESS64: /* Simple copy for 64 bit source */ ACPI_MEMCPY (Out, &Resource->Data, sizeof (ACPI_RESOURCE_ADDRESS64)); break; default: return (AE_BAD_PARAMETER); } return (AE_OK); } ACPI_EXPORT_SYMBOL (AcpiResourceToAddress64) /******************************************************************************* * * FUNCTION: AcpiGetVendorResource * * PARAMETERS: DeviceHandle - Handle for the parent device object * Name - Method name for the parent resource * (METHOD_NAME__CRS or METHOD_NAME__PRS) * Uuid - Pointer to the UUID to be matched. * includes both subtype and 16-byte UUID * RetBuffer - Where the vendor resource is returned * * RETURN: Status * * DESCRIPTION: Walk a resource template for the specified device to find a * vendor-defined resource that matches the supplied UUID and * UUID subtype. Returns a ACPI_RESOURCE of type Vendor. * ******************************************************************************/ ACPI_STATUS AcpiGetVendorResource ( ACPI_HANDLE DeviceHandle, char *Name, ACPI_VENDOR_UUID *Uuid, ACPI_BUFFER *RetBuffer) { ACPI_VENDOR_WALK_INFO Info; ACPI_STATUS Status; /* Other parameters are validated by AcpiWalkResources */ if (!Uuid || !RetBuffer) { return (AE_BAD_PARAMETER); } Info.Uuid = Uuid; Info.Buffer = RetBuffer; Info.Status = AE_NOT_EXIST; /* Walk the _CRS or _PRS resource list for this device */ Status = AcpiWalkResources (DeviceHandle, Name, AcpiRsMatchVendorResource, &Info); if (ACPI_FAILURE (Status)) { return (Status); } return (Info.Status); } ACPI_EXPORT_SYMBOL (AcpiGetVendorResource) /******************************************************************************* * * FUNCTION: AcpiRsMatchVendorResource * * PARAMETERS: ACPI_WALK_RESOURCE_CALLBACK * * RETURN: Status * * DESCRIPTION: Match a vendor resource via the ACPI 3.0 UUID * ******************************************************************************/ static ACPI_STATUS AcpiRsMatchVendorResource ( ACPI_RESOURCE *Resource, void *Context) { ACPI_VENDOR_WALK_INFO *Info = Context; ACPI_RESOURCE_VENDOR_TYPED *Vendor; ACPI_BUFFER *Buffer; ACPI_STATUS Status; /* Ignore all descriptors except Vendor */ if (Resource->Type != ACPI_RESOURCE_TYPE_VENDOR) { return (AE_OK); } Vendor = &Resource->Data.VendorTyped; /* * For a valid match, these conditions must hold: * * 1) Length of descriptor data must be at least as long as a UUID struct * 2) The UUID subtypes must match * 3) The UUID data must match */ if ((Vendor->ByteLength < (ACPI_UUID_LENGTH + 1)) || (Vendor->UuidSubtype != Info->Uuid->Subtype) || (ACPI_MEMCMP (Vendor->Uuid, Info->Uuid->Data, ACPI_UUID_LENGTH))) { return (AE_OK); } /* Validate/Allocate/Clear caller buffer */ Buffer = Info->Buffer; Status = AcpiUtInitializeBuffer (Buffer, Resource->Length); if (ACPI_FAILURE (Status)) { return (Status); } /* Found the correct resource, copy and return it */ ACPI_MEMCPY (Buffer->Pointer, Resource, Resource->Length); Buffer->Length = Resource->Length; /* Found the desired descriptor, terminate resource walk */ Info->Status = AE_OK; return (AE_CTRL_TERMINATE); } /******************************************************************************* * * FUNCTION: AcpiWalkResourceBuffer * * PARAMETERS: Buffer - Formatted buffer returned by one of the * various Get*Resource functions * UserFunction - Called for each resource * Context - Passed to UserFunction * * RETURN: Status * * DESCRIPTION: Walks the input resource template. The UserFunction is called * once for each resource in the list. * ******************************************************************************/ ACPI_STATUS AcpiWalkResourceBuffer ( ACPI_BUFFER *Buffer, ACPI_WALK_RESOURCE_CALLBACK UserFunction, void *Context) { ACPI_STATUS Status = AE_OK; ACPI_RESOURCE *Resource; ACPI_RESOURCE *ResourceEnd; ACPI_FUNCTION_TRACE (AcpiWalkResourceBuffer); /* Parameter validation */ if (!Buffer || !Buffer->Pointer || !UserFunction) { return_ACPI_STATUS (AE_BAD_PARAMETER); } /* Buffer contains the resource list and length */ Resource = ACPI_CAST_PTR (ACPI_RESOURCE, Buffer->Pointer); ResourceEnd = ACPI_ADD_PTR (ACPI_RESOURCE, Buffer->Pointer, Buffer->Length); /* Walk the resource list until the EndTag is found (or buffer end) */ while (Resource < ResourceEnd) { /* Sanity check the resource type */ if (Resource->Type > ACPI_RESOURCE_TYPE_MAX) { Status = AE_AML_INVALID_RESOURCE_TYPE; break; } /* Sanity check the length. It must not be zero, or we loop forever */ if (!Resource->Length) { return_ACPI_STATUS (AE_AML_BAD_RESOURCE_LENGTH); } /* Invoke the user function, abort on any error returned */ Status = UserFunction (Resource, Context); if (ACPI_FAILURE (Status)) { if (Status == AE_CTRL_TERMINATE) { /* This is an OK termination by the user function */ Status = AE_OK; } break; } /* EndTag indicates end-of-list */ if (Resource->Type == ACPI_RESOURCE_TYPE_END_TAG) { break; } /* Get the next resource descriptor */ Resource = ACPI_NEXT_RESOURCE (Resource); } return_ACPI_STATUS (Status); } ACPI_EXPORT_SYMBOL (AcpiWalkResourceBuffer) /******************************************************************************* * * FUNCTION: AcpiWalkResources * * PARAMETERS: DeviceHandle - Handle to the device object for the * device we are querying * Name - Method name of the resources we want. * (METHOD_NAME__CRS, METHOD_NAME__PRS, or * METHOD_NAME__AEI) * UserFunction - Called for each resource * Context - Passed to UserFunction * * RETURN: Status * * DESCRIPTION: Retrieves the current or possible resource list for the * specified device. The UserFunction is called once for * each resource in the list. * ******************************************************************************/ ACPI_STATUS AcpiWalkResources ( ACPI_HANDLE DeviceHandle, char *Name, ACPI_WALK_RESOURCE_CALLBACK UserFunction, void *Context) { ACPI_STATUS Status; ACPI_BUFFER Buffer; ACPI_FUNCTION_TRACE (AcpiWalkResources); /* Parameter validation */ if (!DeviceHandle || !UserFunction || !Name || (!ACPI_COMPARE_NAME (Name, METHOD_NAME__CRS) && !ACPI_COMPARE_NAME (Name, METHOD_NAME__PRS) && !ACPI_COMPARE_NAME (Name, METHOD_NAME__AEI))) { return_ACPI_STATUS (AE_BAD_PARAMETER); } /* Get the _CRS/_PRS/_AEI resource list */ Buffer.Length = ACPI_ALLOCATE_LOCAL_BUFFER; Status = AcpiRsGetMethodData (DeviceHandle, Name, &Buffer); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } /* Walk the resource list and cleanup */ Status = AcpiWalkResourceBuffer (&Buffer, UserFunction, Context); ACPI_FREE (Buffer.Pointer); return_ACPI_STATUS (Status); } ACPI_EXPORT_SYMBOL (AcpiWalkResources)
gpl-3.0
evancich/apm_min_arm
modules/PX4NuttX/nuttx/arch/arm/src/lpc17xx/lpc17_usbdev.c
8
104004
/******************************************************************************* * arch/arm/src/lpc17xx/lpc17_usbdev.c * * Copyright (C) 2010, 2012 Gregory Nutt. All rights reserved. * Author: Gregory Nutt <gnutt@nuttx.org> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name NuttX nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * *******************************************************************************/ /******************************************************************************* * Included Files *******************************************************************************/ #include <nuttx/config.h> #include <sys/types.h> #include <stdint.h> #include <stdbool.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <debug.h> #include <nuttx/arch.h> #include <nuttx/kmalloc.h> #include <nuttx/usb/usb.h> #include <nuttx/usb/usbdev.h> #include <nuttx/usb/usbdev_trace.h> #include <arch/irq.h> #include <arch/board/board.h> #include "up_arch.h" #include "up_internal.h" #include "chip.h" #include "chip/lpc17_usb.h" #include "chip/lpc17_syscon.h" #include "lpc17_gpio.h" #include "lpc17_gpdma.h" /******************************************************************************* * Definitions *******************************************************************************/ /* Configuration ***************************************************************/ #ifndef CONFIG_LPC17_USBDEV_EP0_MAXSIZE # define CONFIG_LPC17_USBDEV_EP0_MAXSIZE 64 #endif #ifndef CONFIG_USBDEV_MAXPOWER # define CONFIG_USBDEV_MAXPOWER 100 /* mA */ #endif #define USB_SLOW_INT USBDEV_INT_EPSLOW #define USB_DEVSTATUS_INT USBDEV_INT_DEVSTAT #ifdef CONFIG_LPC17_USBDEV_EPFAST_INTERRUPT # define USB_FAST_INT USBDEV_INT_EPFAST #else # define USB_FAST_INT 0 #endif /* Enable reading SOF from interrupt handler vs. simply reading on demand. Probably * a bad idea... Unless there is some issue with sampling the SOF from hardware * asynchronously. */ #ifdef CONFIG_LPC17_USBDEV_FRAME_INTERRUPT # define USB_FRAME_INT USBDEV_INT_FRAME #else # define USB_FRAME_INT 0 #endif #ifdef CONFIG_DEBUG # define USB_ERROR_INT USBDEV_INT_ERRINT #else # undef CONFIG_LPC17_USBDEV_REGDEBUG # define USB_ERROR_INT 0 #endif /* CLKCTRL enable bits */ #define LPC17_CLKCTRL_ENABLES (USBDEV_CLK_DEVCLK|USBDEV_CLK_AHBCLK) /* Dump GPIO registers */ #if defined(CONFIG_LPC17_USBDEV_REGDEBUG) && defined(CONFIG_DEBUG_GPIO) # define usbdev_dumpgpio() \ do { \ lpc17_dumpgpio(GPIO_USB_DP, "D+ P0.29; D- P0.30"); \ lpc17_dumpgpio(GPIO_USB_VBUS, "LED P1:18; VBUS P1:30"); \ lpc17_dumpgpio(GPIO_USB_CONNECT, "CONNECT P2:9"); \ } while (0); #else # define usbdev_dumpgpio() #endif /* Number of DMA descriptors */ #ifdef CONFIG_LPC17_USBDEV_DMA # error DMA SUPPORT NOT YET FULLY IMPLEMENTED # ifndef CONFIG_LPC17_USBDEV_NDMADESCRIPTORS # define CONFIG_LPC17_USBDEV_NDMADESCRIPTORS 8 # elif CONFIG_LPC17_USBDEV_NDMADESCRIPTORS > 30 # define CONFIG_LPC17_USBDEV_NDMADESCRIPTORS 30 # endif #endif /* Debug ***********************************************************************/ /* Trace error codes */ #define LPC17_TRACEERR_ALLOCFAIL 0x0001 #define LPC17_TRACEERR_BADCLEARFEATURE 0x0002 #define LPC17_TRACEERR_BADDEVGETSTATUS 0x0003 #define LPC17_TRACEERR_BADEPNO 0x0004 #define LPC17_TRACEERR_BADEPGETSTATUS 0x0005 #define LPC17_TRACEERR_BADEPTYPE 0x0006 #define LPC17_TRACEERR_BADGETCONFIG 0x0007 #define LPC17_TRACEERR_BADGETSETDESC 0x0008 #define LPC17_TRACEERR_BADGETSTATUS 0x0009 #define LPC17_TRACEERR_BADSETADDRESS 0x000a #define LPC17_TRACEERR_BADSETCONFIG 0x000b #define LPC17_TRACEERR_BADSETFEATURE 0x000c #define LPC17_TRACEERR_BINDFAILED 0x000d #define LPC17_TRACEERR_DISPATCHSTALL 0x000e #define LPC17_TRACEERR_DMABUSY 0x000f #define LPC17_TRACEERR_DRIVER 0x0010 #define LPC17_TRACEERR_DRIVERREGISTERED 0x0011 #define LPC17_TRACEERR_EP0INSTALLED 0x0012 #define LPC17_TRACEERR_EP0OUTSTALLED 0x0013 #define LPC17_TRACEERR_EP0SETUPSTALLED 0x0014 #define LPC17_TRACEERR_EPINNULLPACKET 0x0015 #define LPC17_TRACEERR_EPOUTNULLPACKET 0x0016 #define LPC17_TRACEERR_EPREAD 0x0017 #define LPC17_TRACEERR_INVALIDCMD 0x0018 #define LPC17_TRACEERR_INVALIDCTRLREQ 0x0019 #define LPC17_TRACEERR_INVALIDPARMS 0x001a #define LPC17_TRACEERR_IRQREGISTRATION 0x001b #define LPC17_TRACEERR_NODMADESC 0x001c #define LPC17_TRACEERR_NOEP 0x001d #define LPC17_TRACEERR_NOTCONFIGURED 0x001e #define LPC17_TRACEERR_REQABORTED 0x001f /* Trace interrupt codes */ #define LPC17_TRACEINTID_USB 0x0001 #define LPC17_TRACEINTID_CLEARFEATURE 0x0002 #define LPC17_TRACEINTID_CONNECTCHG 0x0003 #define LPC17_TRACEINTID_CONNECTED 0x0004 #define LPC17_TRACEINTID_DEVGETSTATUS 0x0005 #define LPC17_TRACEINTID_DEVRESET 0x0006 #define LPC17_TRACEINTID_DEVSTAT 0x0007 #define LPC17_TRACEINTID_DISCONNECTED 0x0008 #define LPC17_TRACEINTID_DISPATCH 0x0009 #define LPC17_TRACEINTID_EP0IN 0x000a #define LPC17_TRACEINTID_EP0OUT 0x000b #define LPC17_TRACEINTID_EP0SETUP 0x000c #define LPC17_TRACEINTID_EPDMA 0x000d #define LPC17_TRACEINTID_EPFAST 0x000e #define LPC17_TRACEINTID_EPGETSTATUS 0x000f #define LPC17_TRACEINTID_EPIN 0x0010 #define LPC17_TRACEINTID_EPINQEMPTY 0x0011 #define LPC17_TRACEINTID_EP0INSETADDRESS 0x0012 #define LPC17_TRACEINTID_EPOUT 0x0013 #define LPC17_TRACEINTID_EPOUTQEMPTY 0x0014 #define LPC17_TRACEINTID_EP0SETUPSETADDRESS 0x0015 #define LPC17_TRACEINTID_ERRINT 0x0016 #define LPC17_TRACEINTID_EPSLOW 0x0017 #define LPC17_TRACEINTID_FRAME 0x0018 #define LPC17_TRACEINTID_GETCONFIG 0x0019 #define LPC17_TRACEINTID_GETSETDESC 0x001a #define LPC17_TRACEINTID_GETSETIF 0x001b #define LPC17_TRACEINTID_GETSTATUS 0x001c #define LPC17_TRACEINTID_IFGETSTATUS 0x001d #define LPC17_TRACEINTID_SETCONFIG 0x001e #define LPC17_TRACEINTID_SETFEATURE 0x001f #define LPC17_TRACEINTID_SUSPENDCHG 0x0020 #define LPC17_TRACEINTID_SYNCHFRAME 0x0021 /* Hardware interface **********************************************************/ /* Macros for testing the device status response */ #define DEVSTATUS_CONNECT(s) (((s)&CMD_STATUS_CONNECT)!=0) #define DEVSTATUS_CONNCHG(s) (((s)&CMD_STATUS_CONNCHG)!=0) #define DEVSTATUS_SUSPEND(s) (((s)&CMD_STATUS_SUSPEND)!=0) #define DEVSTATUS_SUSPCHG(s) (((s)&CMD_STATUS_SUSPCHG)!=0) #define DEVSTATUS_RESET(s) (((s)&CMD_STATUS_RESET)!=0) /* If this bit is set in the lpc17_epread response, it means that the * recevied packet was overwritten by a later setup packet (ep0 only). */ #define LPC17_READOVERRUN_BIT (0x80000000) #define LPC17_READOVERRUN(s) (((s) & LPC17_READOVERRUN_BIT) != 0) /* Endpoints ******************************************************************/ /* Number of endpoints */ #define LPC17_NLOGENDPOINTS (16) /* ep0-15 */ #define LPC17_NPHYSENDPOINTS (32) /* x2 for IN and OUT */ /* Odd physical endpoint numbers are IN; even are out */ #define LPC17_EPPHYIN(epphy) (((epphy)&1)!=0) #define LPC17_EPPHYOUT(epphy) (((epphy)&1)==0) #define LPC17_EPPHYIN2LOG(epphy) (((uint8_t)(epphy)>>1)|USB_DIR_IN) #define LPC17_EPPHYOUT2LOG(epphy) (((uint8_t)(epphy)>>1)|USB_DIR_OUT) /* Each endpoint has somewhat different characteristics */ #define LPC17_EPALLSET (0xffffffff) /* All endpoints */ #define LPC17_EPOUTSET (0x55555555) /* Even phy endpoint numbers are OUT EPs */ #define LPC17_EPINSET (0xaaaaaaaa) /* Odd endpoint numbers are IN EPs */ #define LPC17_EPCTRLSET (0x00000003) /* EP0 IN/OUT are control endpoints */ #define LPC17_EPINTRSET (0x0c30c30c) /* Interrupt endpoints */ #define LPC17_EPBULKSET (0xf0c30c30) /* Bulk endpoints */ #define LPC17_EPISOCSET (0x030c30c0) /* Isochronous endpoints */ #define LPC17_EPDBLBUFFER (0xf3cf3cf0) /* Double buffered endpoints */ #define LPC17_EP0MAXPACKET (64) /* EP0 max packet size (1-64) */ #define LPC17_BULKMAXPACKET (64) /* Bulk endpoint max packet (8/16/32/64) */ #define LPC17_INTRMAXPACKET (64) /* Interrupt endpoint max packet (1 to 64) */ #define LPC17_ISOCMAXPACKET (512) /* Acutally 1..1023 */ /* EP0 status. EP0 transfers occur in a number of different contexts. A * simple state machine is required to handle the various transfer complete * interrupt responses. The following values are the various states: */ /*** INTERRUPT CAUSE ***/ #define LPC17_EP0REQUEST (0) /* Normal request handling */ #define LPC17_EP0STATUSIN (1) /* Status sent */ #define LPC17_EP0STATUSOUT (2) /* Status received */ #define LPC17_EP0SHORTWRITE (3) /* Short data sent with no request */ #define LPC17_EP0SHORTWRSENT (4) /* Short data write complete */ #define LPC17_EP0SETADDRESS (5) /* Set address received */ #define LPC17_EP0WRITEREQUEST (6) /* EP0 write request sent */ /* Request queue operations ****************************************************/ #define lpc17_rqempty(ep) ((ep)->head == NULL) #define lpc17_rqpeek(ep) ((ep)->head) /******************************************************************************* * Private Types *******************************************************************************/ /* A container for a request so that the request make be retained in a list */ struct lpc17_req_s { struct usbdev_req_s req; /* Standard USB request */ struct lpc17_req_s *flink; /* Supports a singly linked list */ }; /* This is the internal representation of an endpoint */ struct lpc17_ep_s { /* Common endpoint fields. This must be the first thing defined in the * structure so that it is possible to simply cast from struct usbdev_ep_s * to struct lpc17_ep_s. */ struct usbdev_ep_s ep; /* Standard endpoint structure */ /* LPC17xx-specific fields */ struct lpc17_usbdev_s *dev; /* Reference to private driver data */ struct lpc17_req_s *head; /* Request list for this endpoint */ struct lpc17_req_s *tail; uint8_t epphy; /* Physical EP address */ uint8_t stalled:1; /* 1: Endpoint is stalled */ uint8_t halted:1; /* 1: Endpoint feature halted */ uint8_t txbusy:1; /* 1: TX endpoint FIFO full */ uint8_t txnullpkt:1; /* Null packet needed at end of transfer */ }; /* This represents a DMA descriptor */ #ifdef CONFIG_LPC17_USBDEV_DMA struct lpc17_dmadesc_s { uint32_t nextdesc; /* Address of the next DMA descriptor in RAM */ uint32_t config; /* Misc. bit encoded configuration information */ uint32_t start; /* DMA start address */ uint32_t status; /* Misc. bit encoded status inforamation */ #ifdef CONFIG_USBDEV_ISOCHRONOUS uint32_t size; /* Isochronous packet size address */ #endif }; #endif /* This structure retains the state of the USB device controller */ struct lpc17_usbdev_s { /* Common device fields. This must be the first thing defined in the * structure so that it is possible to simply cast from struct usbdev_s * to structlpc17_usbdev_s. */ struct usbdev_s usbdev; /* The bound device class driver */ struct usbdevclass_driver_s *driver; /* LPC17xx-specific fields */ uint8_t devstatus; /* Last response to device status command */ uint8_t ep0state; /* State of certain EP0 operations */ uint8_t paddr; /* Address assigned by SETADDRESS */ uint8_t stalled:1; /* 1: Protocol stalled */ uint8_t selfpowered:1; /* 1: Device is self powered */ uint8_t paddrset:1; /* 1: Peripheral addr has been set */ uint8_t attached:1; /* 1: Host attached */ uint8_t rxpending:1; /* 1: RX pending */ uint32_t softprio; /* Bitset of high priority interrupts */ uint32_t epavail; /* Bitset of available endpoints */ #ifdef CONFIG_LPC17_USBDEV_FRAME_INTERRUPT uint32_t sof; /* Last start-of-frame */ #endif /* Allocated DMA descriptor */ #ifdef CONFIG_LPC17_USBDEV_DMA struct lpc17_dmadesc_s *dmadesc; #endif /* The endpoint list */ struct lpc17_ep_s eplist[LPC17_NPHYSENDPOINTS]; }; /******************************************************************************* * Private Function Prototypes *******************************************************************************/ /* Register operations ********************************************************/ #ifdef CONFIG_LPC17_USBDEV_REGDEBUG static void lpc17_printreg(uint32_t addr, uint32_t val, bool iswrite); static void lpc17_checkreg(uint32_t addr, uint32_t val, bool iswrite); static uint32_t lpc17_getreg(uint32_t addr); static void lpc17_putreg(uint32_t val, uint32_t addr); #else # define lpc17_getreg(addr) getreg32(addr) # define lpc17_putreg(val,addr) putreg32(val,addr) #endif /* Command operations **********************************************************/ static uint32_t lpc17_usbcmd(uint16_t cmd, uint8_t data); /* Request queue operations ****************************************************/ static FAR struct lpc17_req_s *lpc17_rqdequeue(FAR struct lpc17_ep_s *privep); static void lpc17_rqenqueue(FAR struct lpc17_ep_s *privep, FAR struct lpc17_req_s *req); /* Low level data transfers and request operations *****************************/ static void lpc17_epwrite(uint8_t epphy, const uint8_t *data, uint32_t nbytes); static int lpc17_epread(uint8_t epphy, uint8_t *data, uint32_t nbytes); static inline void lpc17_abortrequest(struct lpc17_ep_s *privep, struct lpc17_req_s *privreq, int16_t result); static void lpc17_reqcomplete(struct lpc17_ep_s *privep, int16_t result); static int lpc17_wrrequest(struct lpc17_ep_s *privep); static int lpc17_rdrequest(struct lpc17_ep_s *privep); static void lpc17_cancelrequests(struct lpc17_ep_s *privep); /* Interrupt handling **********************************************************/ static struct lpc17_ep_s *lpc17_epfindbyaddr(struct lpc17_usbdev_s *priv, uint16_t eplog); static void lpc17_eprealize(struct lpc17_ep_s *privep, bool prio, uint32_t packetsize); static uint8_t lpc17_epclrinterrupt(uint8_t epphy); static inline void lpc17_ep0configure(struct lpc17_usbdev_s *priv); #ifdef CONFIG_LPC17_USBDEV_DMA static inline void lpc17_dmareset(uint32_t enable); #endif static void lpc17_usbreset(struct lpc17_usbdev_s *priv); static void lpc17_dispatchrequest(struct lpc17_usbdev_s *priv, const struct usb_ctrlreq_s *ctrl); static inline void lpc17_ep0setup(struct lpc17_usbdev_s *priv); static inline void lpc17_ep0dataoutinterrupt(struct lpc17_usbdev_s *priv); static inline void lpc17_ep0dataininterrupt(struct lpc17_usbdev_s *priv); static int lpc17_usbinterrupt(int irq, FAR void *context); #ifdef CONFIG_LPC17_USBDEV_DMA static int lpc17_dmasetup(struct lpc17_usbdev_s *priv, uint8_t epphy, uint32_t epmaxsize, uint32_t nbytes, uint32_t *isocpacket, bool isochronous); static void lpc17_dmarestart(uint8_t epphy, uint32_t descndx); static void lpc17_dmadisable(uint8_t epphy); #endif /* CONFIG_LPC17_USBDEV_DMA */ /* Endpoint operations *********************************************************/ static int lpc17_epconfigure(FAR struct usbdev_ep_s *ep, const struct usb_epdesc_s *desc, bool last); static int lpc17_epdisable(FAR struct usbdev_ep_s *ep); static FAR struct usbdev_req_s *lpc17_epallocreq(FAR struct usbdev_ep_s *ep); static void lpc17_epfreereq(FAR struct usbdev_ep_s *ep, FAR struct usbdev_req_s *); #ifdef CONFIG_USBDEV_DMA static FAR void *lpc17_epallocbuffer(FAR struct usbdev_ep_s *ep, uint16_t nbytes); static void lpc17_epfreebuffer(FAR struct usbdev_ep_s *ep, void *buf); #endif static int lpc17_epsubmit(FAR struct usbdev_ep_s *ep, struct usbdev_req_s *req); static int lpc17_epcancel(FAR struct usbdev_ep_s *ep, struct usbdev_req_s *req); static int lpc17_epstall(FAR struct usbdev_ep_s *ep, bool resume); /* USB device controller operations ********************************************/ static FAR struct usbdev_ep_s *lpc17_allocep(FAR struct usbdev_s *dev, uint8_t epno, bool in, uint8_t eptype); static void lpc17_freeep(FAR struct usbdev_s *dev, FAR struct usbdev_ep_s *ep); static int lpc17_getframe(struct usbdev_s *dev); static int lpc17_wakeup(struct usbdev_s *dev); static int lpc17_selfpowered(struct usbdev_s *dev, bool selfpowered); static int lpc17_pullup(struct usbdev_s *dev, bool enable); /******************************************************************************* * Private Data *******************************************************************************/ /* Since there is only a single USB interface, all status information can be * be simply retained in a single global instance. */ static struct lpc17_usbdev_s g_usbdev; static const struct usbdev_epops_s g_epops = { .configure = lpc17_epconfigure, .disable = lpc17_epdisable, .allocreq = lpc17_epallocreq, .freereq = lpc17_epfreereq, #ifdef CONFIG_USBDEV_DMA .allocbuffer = lpc17_epallocbuffer, .freebuffer = lpc17_epfreebuffer, #endif .submit = lpc17_epsubmit, .cancel = lpc17_epcancel, .stall = lpc17_epstall, }; static const struct usbdev_ops_s g_devops = { .allocep = lpc17_allocep, .freeep = lpc17_freeep, .getframe = lpc17_getframe, .wakeup = lpc17_wakeup, .selfpowered = lpc17_selfpowered, .pullup = lpc17_pullup, }; /* USB Device Communication Area *********************************************** * * The CPU and DMA controller communicate through a common area of memory, called * the USB Device Communication Area, or UDCA. The UDCA is a 32-word array of DMA * Descriptor Pointers (DDPs), each of which corresponds to a physical endpoint. * Each DDP points to the start address of a DMA Descriptor, if one is defined for * the endpoint. DDPs for unrealized endpoints and endpoints disabled for DMA * operation are ignored and can be set to a NULL (0x0) value. * * The start address of the UDCA is stored in the USBUDCAH register. The UDCA can * reside at any 128-byte boundary of RAM that is accessible to both the CPU and DMA * controller (on other MCU's like the LPC2148, the UDCA lies in a specialized * 8Kb memory region). */ #ifdef CONFIG_LPC17_USBDEV_DMA static uint32_t g_udca[LPC17_NPHYSENDPOINTS] __attribute__ ((aligned (128))); static struct lpc17_dmadesc_s g_usbddesc[CONFIG_LPC17_USBDEV_NDMADESCRIPTORS]; #endif /******************************************************************************* * Public Data *******************************************************************************/ /******************************************************************************* * Private Functions *******************************************************************************/ /******************************************************************************* * Name: lpc17_printreg * * Description: * Print the contents of an LPC17xx register operation * *******************************************************************************/ #ifdef CONFIG_LPC17_USBDEV_REGDEBUG static void lpc17_printreg(uint32_t addr, uint32_t val, bool iswrite) { lldbg("%08x%s%08x\n", addr, iswrite ? "<-" : "->", val); } #endif /******************************************************************************* * Name: lpc17_checkreg * * Description: * Get the contents of an LPC17xx register * *******************************************************************************/ #ifdef CONFIG_LPC17_USBDEV_REGDEBUG static void lpc17_checkreg(uint32_t addr, uint32_t val, bool iswrite) { static uint32_t prevaddr = 0; static uint32_t preval = 0; static uint32_t count = 0; static bool prevwrite = false; /* Is this the same value that we read from/wrote to the same register last time? * Are we polling the register? If so, suppress the output. */ if (addr == prevaddr && val == preval && prevwrite == iswrite) { /* Yes.. Just increment the count */ count++; } else { /* No this is a new address or value or operation. Were there any * duplicate accesses before this one? */ if (count > 0) { /* Yes.. Just one? */ if (count == 1) { /* Yes.. Just one */ lpc17_printreg(prevaddr, preval, prevwrite); } else { /* No.. More than one. */ lldbg("[repeats %d more times]\n", count); } } /* Save the new address, value, count, and operation for next time */ prevaddr = addr; preval = val; count = 0; prevwrite = iswrite; /* Show the new regisgter access */ lpc17_printreg(addr, val, iswrite); } } #endif /******************************************************************************* * Name: lpc17_getreg * * Description: * Get the contents of an LPC17xx register * *******************************************************************************/ #ifdef CONFIG_LPC17_USBDEV_REGDEBUG static uint32_t lpc17_getreg(uint32_t addr) { /* Read the value from the register */ uint32_t val = getreg32(addr); /* Check if we need to print this value */ lpc17_checkreg(addr, val, false); return val; } #endif /******************************************************************************* * Name: lpc17_putreg * * Description: * Set the contents of an LPC17xx register to a value * *******************************************************************************/ #ifdef CONFIG_LPC17_USBDEV_REGDEBUG static void lpc17_putreg(uint32_t val, uint32_t addr) { /* Check if we need to print this value */ lpc17_checkreg(addr, val, true); /* Write the value */ putreg32(val, addr); } #endif /******************************************************************************* * Name: lpc17_usbcmd * * Description: * Transmit commands to the USB engine * *******************************************************************************/ static uint32_t lpc17_usbcmd(uint16_t cmd, uint8_t data) { irqstate_t flags; uint32_t cmd32; uint32_t data32; uint32_t tmp = 0; /* Disable interrupt and clear CDFULL and CCEMPTY interrupt status */ flags = irqsave(); lpc17_putreg(USBDEV_INT_CDFULL|USBDEV_INT_CCEMPTY, LPC17_USBDEV_INTCLR); /* Shift the command in position and mask out extra bits */ cmd32 = ((uint32_t)cmd << CMD_USBDEV_CMDSHIFT) & CMD_USBDEV_CMDMASK; /* Load command + WR in command code register */ lpc17_putreg(cmd32 | CMD_USBDEV_CMDWR, LPC17_USBDEV_CMDCODE); /* Wait until the command register is empty (CCEMPTY != 0, command is accepted) */ while ((lpc17_getreg(LPC17_USBDEV_INTST) & USBDEV_INT_CCEMPTY) == 0); /* Clear command register empty (CCEMPTY) interrupt */ lpc17_putreg(USBDEV_INT_CCEMPTY, LPC17_USBDEV_INTCLR); /* Determine next phase of the command */ switch (cmd) { /* Write operations (1 byte of data) */ case CMD_USBDEV_SETADDRESS: case CMD_USBDEV_CONFIG: case CMD_USBDEV_SETMODE: case CMD_USBDEV_SETSTATUS: { /* Send data + WR and wait for CCEMPTY */ data32 = (uint32_t)data << CMD_USBDEV_WDATASHIFT; lpc17_putreg(data32 | CMD_USBDEV_DATAWR, LPC17_USBDEV_CMDCODE); while ((lpc17_getreg(LPC17_USBDEV_INTST) & USBDEV_INT_CCEMPTY) == 0); } break; /* 16 bit read operations */ case CMD_USBDEV_READFRAMENO: case CMD_USBDEV_READTESTREG: { /* Send command code + RD and wait for CDFULL */ lpc17_putreg(cmd32 | CMD_USBDEV_DATARD, LPC17_USBDEV_CMDCODE); while ((lpc17_getreg(LPC17_USBDEV_INTST) & USBDEV_INT_CDFULL) == 0); /* Clear CDFULL and read LS data */ lpc17_putreg(USBDEV_INT_CDFULL, LPC17_USBDEV_INTCLR); tmp = lpc17_getreg(LPC17_USBDEV_CMDDATA); /* Send command code + RD and wait for CDFULL */ lpc17_putreg(cmd32 | CMD_USBDEV_DATARD, LPC17_USBDEV_CMDCODE); while ((lpc17_getreg(LPC17_USBDEV_INTST) & USBDEV_INT_CDFULL) == 0); /* Read MS data */ tmp |= lpc17_getreg(LPC17_USBDEV_CMDDATA) << 8; } break; /* 8-bit read operations */ case CMD_USBDEV_GETSTATUS: case CMD_USBDEV_GETERRORCODE: case CMD_USBDEV_READERRORSTATUS: case CMD_USBDEV_EPCLRBUFFER: { /* Send command code + RD and wait for CDFULL */ lpc17_putreg(cmd32 | CMD_USBDEV_DATARD, LPC17_USBDEV_CMDCODE); while ((lpc17_getreg(LPC17_USBDEV_INTST) & USBDEV_INT_CDFULL) == 0); /* Read data */ tmp = lpc17_getreg(LPC17_USBDEV_CMDDATA); } break; /* No data transfer */ case CMD_USBDEV_EPVALIDATEBUFFER: break; default: switch (cmd & 0x1e0) { case CMD_USBDEV_EPSELECT: case CMD_USBDEV_EPSELECTCLEAR: { /* Send command code + RD and wait for CDFULL */ lpc17_putreg(cmd32 | CMD_USBDEV_DATARD, LPC17_USBDEV_CMDCODE); while ((lpc17_getreg(LPC17_USBDEV_INTST) & USBDEV_INT_CDFULL) == 0); /* Read data */ tmp = lpc17_getreg(LPC17_USBDEV_CMDDATA); } break; case CMD_USBDEV_EPSETSTATUS: { /* Send data + RD and wait for CCEMPTY */ data32 = (uint32_t)data << CMD_USBDEV_WDATASHIFT; lpc17_putreg(data32 | CMD_USBDEV_DATAWR, LPC17_USBDEV_CMDCODE); while ((lpc17_getreg(LPC17_USBDEV_INTST) & USBDEV_INT_CCEMPTY) == 0); } break; default: usbtrace(TRACE_DEVERROR(LPC17_TRACEERR_INVALIDCMD), 0); break; } break; } /* Restore the interrupt flags */ irqrestore(flags); return tmp; } /******************************************************************************* * Name: lpc17_rqdequeue * * Description: * Remove a request from an endpoint request queue * *******************************************************************************/ static FAR struct lpc17_req_s *lpc17_rqdequeue(FAR struct lpc17_ep_s *privep) { FAR struct lpc17_req_s *ret = privep->head; if (ret) { privep->head = ret->flink; if (!privep->head) { privep->tail = NULL; } ret->flink = NULL; } return ret; } /******************************************************************************* * Name: lpc17_rqenqueue * * Description: * Add a request from an endpoint request queue * *******************************************************************************/ static void lpc17_rqenqueue(FAR struct lpc17_ep_s *privep, FAR struct lpc17_req_s *req) { req->flink = NULL; if (!privep->head) { privep->head = req; privep->tail = req; } else { privep->tail->flink = req; privep->tail = req; } } /******************************************************************************* * Name: lpc17_epwrite * * Description: * Endpoint write (IN) * *******************************************************************************/ static void lpc17_epwrite(uint8_t epphy, const uint8_t *data, uint32_t nbytes) { uint32_t value; bool aligned = (((uint32_t)data & 3) == 0); /* Set the write enable bit for this physical EP address. Bits 2-5 are * the logical endpoint number (0-15) */ lpc17_putreg(((epphy << 1) & USBDEV_CTRL_LOGEP_MASK) | USBDEV_CTRL_WREN, LPC17_USBDEV_CTRL); /* Set the transmit packet length (nbytes must be less than 2048) */ lpc17_putreg(nbytes, LPC17_USBDEV_TXPLEN); /* Transfer the packet data */ do { /* Zero length packets are a special case */ if (nbytes) { if (aligned) { value = *(uint32_t*)data; } else { value = (uint32_t)data[0] | ((uint32_t)data[1] << 8) | ((uint32_t)data[2] << 16) | ((uint32_t)data[3] << 24); } lpc17_putreg(value, LPC17_USBDEV_TXDATA); data += 4; } else { /* Zero length packet */ lpc17_putreg(0, LPC17_USBDEV_TXDATA); } } while ((lpc17_getreg(LPC17_USBDEV_CTRL) & USBDEV_CTRL_WREN) != 0); /* Done */ lpc17_putreg(0, LPC17_USBDEV_CTRL); (void)lpc17_usbcmd(CMD_USBDEV_EPSELECT | epphy, 0); (void)lpc17_usbcmd(CMD_USBDEV_EPVALIDATEBUFFER, 0); } /******************************************************************************* * Name: lpc17_epread * * Description: * Endpoint read (OUT) * *******************************************************************************/ static int lpc17_epread(uint8_t epphy, uint8_t *data, uint32_t nbytes) { uint32_t pktlen; uint32_t result; uint32_t value; uint8_t aligned = 0; /* If data is NULL, then we are being asked to read but discard the data. * For most cases, the resulting buffer will be aligned and we will be * able to do faster 32-bit transfers. */ if (data) { if (((uint32_t)data & 3) == 0) { aligned = 1; } else { aligned = 2; } } /* Set the read enable bit for this physical EP address. Bits 2-5 are * the logical endpoint number (0-15). */ lpc17_putreg(((epphy << 1) & USBDEV_CTRL_LOGEP_MASK) | USBDEV_CTRL_RDEN, LPC17_USBDEV_CTRL); /* Wait for packet buffer ready for reading */ while ((lpc17_getreg(LPC17_USBDEV_RXPLEN) & USBDEV_RXPLEN_PKTRDY) == 0); /* Get the number of bytes of data to be read */ pktlen = lpc17_getreg(LPC17_USBDEV_RXPLEN) & USBDEV_RXPLEN_MASK; /* Read data from input buffer while read data is valid (DV) */ while ((lpc17_getreg(LPC17_USBDEV_RXPLEN) & USBDEV_RXPLEN_DV) != 0) { value = lpc17_getreg(LPC17_USBDEV_RXDATA); if (aligned == 1) { *(uint32_t*)data = value; data += 4; } else if (aligned == 2) { *data++ = (uint8_t)value; *data++ = (uint8_t)(value >> 8); *data++ = (uint8_t)(value >> 16); *data++ = (uint8_t)(value >> 24); } } /* Done */ lpc17_putreg(0, LPC17_USBDEV_CTRL); (void)lpc17_usbcmd(CMD_USBDEV_EPSELECT | epphy, 0); result = lpc17_usbcmd(CMD_USBDEV_EPCLRBUFFER, 0); /* The packet overrun bit in the clear buffer response is applicable only * on EP0 transfers. If set it means that the recevied packet was overwritten * by a later setup packet. */ if (epphy == LPC17_EP0_OUT && (result & CMD_USBDEV_CLRBUFFER_PO) != 0) { /* Pass this information in bit 31 */ pktlen |= LPC17_READOVERRUN_BIT; } return pktlen; } /******************************************************************************* * Name: lpc17_abortrequest * * Description: * Discard a request * *******************************************************************************/ static inline void lpc17_abortrequest(struct lpc17_ep_s *privep, struct lpc17_req_s *privreq, int16_t result) { usbtrace(TRACE_DEVERROR(LPC17_TRACEERR_REQABORTED), (uint16_t)privep->epphy); /* Save the result in the request structure */ privreq->req.result = result; /* Callback to the request completion handler */ privreq->req.callback(&privep->ep, &privreq->req); } /******************************************************************************* * Name: lpc17_reqcomplete * * Description: * Handle termination of the request at the head of the endpoint request queue. * *******************************************************************************/ static void lpc17_reqcomplete(struct lpc17_ep_s *privep, int16_t result) { struct lpc17_req_s *privreq; int stalled = privep->stalled; irqstate_t flags; /* Remove the completed request at the head of the endpoint request list */ flags = irqsave(); privreq = lpc17_rqdequeue(privep); irqrestore(flags); if (privreq) { /* If endpoint 0, temporarily reflect the state of protocol stalled * in the callback. */ if (privep->epphy == LPC17_EP0_IN) { privep->stalled = privep->dev->stalled; } /* Save the result in the request structure */ privreq->req.result = result; /* Callback to the request completion handler */ privreq->flink = NULL; privreq->req.callback(&privep->ep, &privreq->req); /* Restore the stalled indication */ privep->stalled = stalled; } } /******************************************************************************* * Name: lpc17_wrrequest * * Description: * Send from the next queued write request * *******************************************************************************/ static int lpc17_wrrequest(struct lpc17_ep_s *privep) { struct lpc17_req_s *privreq; uint8_t *buf; int nbytes; int bytesleft; /* Check the request from the head of the endpoint request queue */ privreq = lpc17_rqpeek(privep); if (!privreq) { usbtrace(TRACE_INTDECODE(LPC17_TRACEINTID_EPINQEMPTY), 0); return OK; } ullvdbg("epphy=%d req=%p: len=%d xfrd=%d nullpkt=%d\n", privep->epphy, privreq, privreq->req.len, privreq->req.xfrd, privep->txnullpkt); /* Ignore any attempt to send a zero length packet on anything but EP0IN */ if (privreq->req.len == 0) { if (privep->epphy == LPC17_EP0_IN) { lpc17_epwrite(LPC17_EP0_IN, NULL, 0); } else { usbtrace(TRACE_DEVERROR(LPC17_TRACEERR_EPINNULLPACKET), 0); } /* In any event, the request is complete */ lpc17_reqcomplete(privep, OK); return OK; } /* Otherwise send the data in the packet (in the DMA on case, we * may be resuming transfer already in progress. */ #warning REVISIT... If the EP supports double buffering, then we can do better /* Get the number of bytes left to be sent in the packet */ bytesleft = privreq->req.len - privreq->req.xfrd; /* Send the next packet if (1) there are more bytes to be sent, or * (2) the last packet sent was exactly maxpacketsize (bytesleft == 0) */ usbtrace(TRACE_WRITE(privep->epphy), privreq->req.xfrd); if (bytesleft > 0 || privep->txnullpkt) { /* Indicate that there is data in the TX FIFO. This will be cleared * when the EPIN interrupt is received */ privep->txbusy = 1; /* Try to send maxpacketsize -- unless we don't have that many * bytes to send. */ privep->txnullpkt = 0; if (bytesleft > privep->ep.maxpacket) { nbytes = privep->ep.maxpacket; } else { nbytes = bytesleft; if ((privreq->req.flags & USBDEV_REQFLAGS_NULLPKT) != 0) { privep->txnullpkt = (bytesleft == privep->ep.maxpacket); } } /* Send the largest number of bytes that we can in this packet */ buf = privreq->req.buf + privreq->req.xfrd; lpc17_epwrite(privep->epphy, buf, nbytes); /* Update for the next time through the loop */ privreq->req.xfrd += nbytes; } /* If all of the bytes were sent (including any final null packet) * then we are finished with the transfer */ if (privreq->req.xfrd >= privreq->req.len && !privep->txnullpkt) { usbtrace(TRACE_COMPLETE(privep->epphy), privreq->req.xfrd); privep->txnullpkt = 0; lpc17_reqcomplete(privep, OK); } return OK; } /******************************************************************************* * Name: lpc17_rdrequest * * Description: * Receive to the next queued read request * *******************************************************************************/ static int lpc17_rdrequest(struct lpc17_ep_s *privep) { struct lpc17_req_s *privreq; uint8_t *buf; int nbytesread; /* Check the request from the head of the endpoint request queue */ privreq = lpc17_rqpeek(privep); if (!privreq) { usbtrace(TRACE_INTDECODE(LPC17_TRACEINTID_EPOUTQEMPTY), 0); return OK; } ullvdbg("len=%d xfrd=%d nullpkt=%d\n", privreq->req.len, privreq->req.xfrd, privep->txnullpkt); /* Ignore any attempt to receive a zero length packet */ if (privreq->req.len == 0) { usbtrace(TRACE_DEVERROR(LPC17_TRACEERR_EPOUTNULLPACKET), 0); lpc17_reqcomplete(privep, OK); return OK; } usbtrace(TRACE_READ(privep->epphy), privreq->req.xfrd); /* Receive the next packet */ buf = privreq->req.buf + privreq->req.xfrd; nbytesread = lpc17_epread(privep->epphy, buf, privep->ep.maxpacket); if (nbytesread < 0) { usbtrace(TRACE_DEVERROR(LPC17_TRACEERR_EPREAD), nbytesread); return ERROR; } /* If the receive buffer is full or if the last packet was not full * then we are finished with the transfer. */ privreq->req.xfrd += nbytesread; if (privreq->req.xfrd >= privreq->req.len || nbytesread < privep->ep.maxpacket) { usbtrace(TRACE_COMPLETE(privep->epphy), privreq->req.xfrd); lpc17_reqcomplete(privep, OK); } return OK; } /******************************************************************************* * Name: lpc17_cancelrequests * * Description: * Cancel all pending requests for an endpoint * *******************************************************************************/ static void lpc17_cancelrequests(struct lpc17_ep_s *privep) { while (!lpc17_rqempty(privep)) { usbtrace(TRACE_COMPLETE(privep->epphy), (lpc17_rqpeek(privep))->req.xfrd); lpc17_reqcomplete(privep, -ESHUTDOWN); } } /******************************************************************************* * Name: lpc17_epfindbyaddr * * Description: * Find the physical endpoint structure corresponding to a logic endpoint * address * *******************************************************************************/ static struct lpc17_ep_s *lpc17_epfindbyaddr(struct lpc17_usbdev_s *priv, uint16_t eplog) { struct lpc17_ep_s *privep; int i; /* Endpoint zero is a special case */ if (USB_EPNO(eplog) == 0) { return &priv->eplist[0]; } /* Handle the remaining */ for (i = 1; i < LPC17_NPHYSENDPOINTS; i++) { privep = &priv->eplist[i]; /* Same logical endpoint number? (includes direction bit) */ if (eplog == privep->ep.eplog) { /* Return endpoint found */ return privep; } } /* Return endpoint not found */ return NULL; } /******************************************************************************* * Name: lpc17_eprealize * * Description: * Enable or disable an endpoint * *******************************************************************************/ static void lpc17_eprealize(struct lpc17_ep_s *privep, bool prio, uint32_t packetsize) { struct lpc17_usbdev_s *priv = privep->dev; uint32_t mask; uint32_t regval; /* Initialize endpoint software priority */ mask = 1 << privep->epphy; if (prio) { priv->softprio = priv->softprio | mask; } else { priv->softprio = priv->softprio & ~mask; } /* Clear realize interrupt bit */ lpc17_putreg(USBDEV_INT_EPRLZED, LPC17_USBDEV_INTCLR); /* Realize the endpoint */ regval = lpc17_getreg(LPC17_USBDEV_REEP); regval |= (1 << privep->epphy); lpc17_putreg(regval, LPC17_USBDEV_REEP); /* Set endpoint maximum packet size */ lpc17_putreg(privep->epphy, LPC17_USBDEV_EPIND); lpc17_putreg(packetsize, LPC17_USBDEV_MAXPSIZE); /* Wait for Realize complete */ while ((lpc17_getreg(LPC17_USBDEV_INTST) & USBDEV_INT_EPRLZED) == 0); /* Clear realize interrupt bit */ lpc17_putreg(USBDEV_INT_EPRLZED,LPC17_USBDEV_INTCLR); } /******************************************************************************* * Name: lpc17_epclrinterrupt * * Description: * Clear the EP interrupt flag and return the current EP status * *******************************************************************************/ static uint8_t lpc17_epclrinterrupt(uint8_t epphy) { /* Clear the endpoint interrupt */ lpc17_putreg(1 << epphy, LPC17_USBDEV_EPINTCLR); /* Wait for data in the command data register */ while ((lpc17_getreg(LPC17_USBDEV_INTST) & USBDEV_INT_CDFULL) == 0); /* Return the value of the command data register */ return lpc17_getreg(LPC17_USBDEV_CMDDATA); } /******************************************************************************* * Name: lpc17_ep0configure * * Description: * Configure endpoint 0 * *******************************************************************************/ static inline void lpc17_ep0configure(struct lpc17_usbdev_s *priv) { uint32_t inten; /* EndPoint 0 initialization */ lpc17_eprealize(&priv->eplist[LPC17_CTRLEP_OUT], 0, CONFIG_LPC17_USBDEV_EP0_MAXSIZE); lpc17_eprealize(&priv->eplist[LPC17_CTRLEP_IN], 1, CONFIG_LPC17_USBDEV_EP0_MAXSIZE); /* Enable EP0 interrupts (not DMA) */ inten = lpc17_getreg(LPC17_USBDEV_EPINTEN); inten |= 3; /* EP0 Rx and Tx */ lpc17_putreg(inten, LPC17_USBDEV_EPINTEN); } /******************************************************************************* * Name: lpc17_dmareset * * Description: Reset USB DMA * *******************************************************************************/ #ifdef CONFIG_LPC17_USBDEV_DMA static inline void lpc17_dmareset(uint32_t enable) { int i; /* Disable All DMA interrupts */ lpc17_putreg(0, LPC17_USBDEV_DMAINTEN); /* DMA Disable */ lpc17_putreg(0xffffffff, LPC17_USBDEV_EPDMADIS); /* DMA Request clear */ putreq32(0xffffffff, LPC17_USBDEV_DMARCLR); /* End of Transfer Interrupt Clear */ putreq32(0xffffffff, LPC17_USBDEV_EOTINTCLR); /* New DD Request Interrupt Clear */ putreq32(0xffffffff, LPC17_USBDEV_NDDRINTCLR); /* System Error Interrupt Clear */ putreq32(0xffffffff, LPC17_USBDEV_SYSERRINTCLR); /* Nullify all pointers in the UDCA */ for (i = 0; i < LPC17_NPHYSENDPOINTS; ++i) { g_udca[i] = NULL; } /* Set USB UDCA Head register */ lpc17_putreg((uint32_t)g_udca, LPC17_USBDEV_UDCAH); /* Invalidate all DMA descriptors */ for (i = 0; i < CONFIG_LPC17_USBDEV_NDMADESCRIPTORS; ++i) { memset(&g_usbddesc[i], 0, sizeof(struct lpc17_dmadesc_s)); } /* Enable DMA interrupts */ lpc17_putreg(enable, LPC17_USBDEV_DMAINTEN); } #endif /******************************************************************************* * Name: lpc17_usbreset * * Description: * Reset Usb engine * *******************************************************************************/ static void lpc17_usbreset(struct lpc17_usbdev_s *priv) { /* Disable all endpoint interrupts */ lpc17_putreg(0, LPC17_USBDEV_EPINTEN); /* Frame is Hp interrupt */ lpc17_putreg(USBDEV_INT_FRAME, LPC17_USBDEV_INTPRI); /* Clear all pending interrupts */ lpc17_putreg(0xffffffff, LPC17_USBDEV_EPINTCLR); lpc17_putreg(0xffffffff, LPC17_USBDEV_INTCLR); /* Periperhal address is needed */ priv->paddrset = 0; /* Endpoints not yet configured */ lpc17_usbcmd(CMD_USBDEV_CONFIG, 0); /* EndPoint 0 initialization */ lpc17_ep0configure(priv); #ifdef CONFIG_LPC17_USBDEV_DMA /* Enable End_of_Transfer_Interrupt and System_Error_Interrupt USB DMA * interrupts */ lpc17_dmareset(CONFIG_LPC17_USBDEV_DMAINT_MASK); #endif /* Enable Device interrupts */ lpc17_putreg(USB_SLOW_INT|USB_DEVSTATUS_INT|USB_FAST_INT|USB_FRAME_INT|USB_ERROR_INT, LPC17_USBDEV_INTEN); /* Tell the class driver that we are disconnected. The class * driver should then accept any new configurations. */ if (priv->driver) { CLASS_DISCONNECT(priv->driver, &priv->usbdev); } } /******************************************************************************* * Name: lpc17_dispatchrequest * * Description: * Provide unhandled setup actions to the class driver. This is logically part * of the USB interrupt handler. * *******************************************************************************/ static void lpc17_dispatchrequest(struct lpc17_usbdev_s *priv, const struct usb_ctrlreq_s *ctrl) { int ret; usbtrace(TRACE_INTDECODE(LPC17_TRACEINTID_DISPATCH), 0); if (priv && priv->driver) { /* Forward to the control request to the class driver implementation */ ret = CLASS_SETUP(priv->driver, &priv->usbdev, ctrl, NULL, 0); if (ret < 0) { /* Stall on failure */ usbtrace(TRACE_DEVERROR(LPC17_TRACEERR_DISPATCHSTALL), 0); priv->stalled = 1; } } } /******************************************************************************* * Name: lpc17_ep0setup * * Description: * USB Ctrl EP Setup Event. This is logically part of the USB interrupt * handler. This event occurs when a setup packet is receive on EP0 OUT. * *******************************************************************************/ static inline void lpc17_ep0setup(struct lpc17_usbdev_s *priv) { struct lpc17_ep_s *ep0 = &priv->eplist[LPC17_EP0_OUT]; struct lpc17_ep_s *privep; struct lpc17_req_s *privreq = lpc17_rqpeek(ep0); struct usb_ctrlreq_s ctrl; uint16_t value; uint16_t index; uint16_t len; uint8_t response[2]; int ret; /* Starting a control request? */ if (priv->usbdev.speed == USB_SPEED_UNKNOWN) { priv->usbdev.speed = USB_SPEED_FULL; lpc17_usbcmd(CMD_USBDEV_CONFIG, 1); } /* Terminate any pending requests */ while (!lpc17_rqempty(ep0)) { int16_t result = OK; if (privreq->req.xfrd != privreq->req.len) { result = -EPROTO; } usbtrace(TRACE_COMPLETE(ep0->epphy), privreq->req.xfrd); lpc17_reqcomplete(ep0, result); } /* Assume NOT stalled */ ep0->stalled = 0; priv->stalled = 0; /* Read EP0 data */ ret = lpc17_epread(LPC17_EP0_OUT, (uint8_t*)&ctrl, USB_SIZEOF_CTRLREQ); if (ret <= 0) { return; } /* And extract the little-endian 16-bit values to host order */ value = GETUINT16(ctrl.value); index = GETUINT16(ctrl.index); len = GETUINT16(ctrl.len); ullvdbg("type=%02x req=%02x value=%04x index=%04x len=%04x\n", ctrl.type, ctrl.req, value, index, len); /* Dispatch any non-standard requests */ if ((ctrl.type & USB_REQ_TYPE_MASK) != USB_REQ_TYPE_STANDARD) { lpc17_dispatchrequest(priv, &ctrl); return; } /* Handle standard request. Pick off the things of interest to the * USB device controller driver; pass what is left to the class driver */ switch (ctrl.req) { case USB_REQ_GETSTATUS: { /* type: device-to-host; recipient = device, interface, endpoint * value: 0 * index: zero interface endpoint * len: 2; data = status */ usbtrace(TRACE_INTDECODE(LPC17_TRACEINTID_GETSTATUS), 0); if (!priv->paddrset || len != 2 || (ctrl.type & USB_REQ_DIR_IN) == 0 || value != 0) { priv->stalled = 1; } else { switch (ctrl.type & USB_REQ_RECIPIENT_MASK) { case USB_REQ_RECIPIENT_ENDPOINT: { usbtrace(TRACE_INTDECODE(LPC17_TRACEINTID_EPGETSTATUS), 0); privep = lpc17_epfindbyaddr(priv, index); if (!privep) { usbtrace(TRACE_DEVERROR(LPC17_TRACEERR_BADEPGETSTATUS), 0); priv->stalled = 1; } else { if ((lpc17_usbcmd(CMD_USBDEV_EPSELECT|privep->epphy, 0) & CMD_EPSELECT_ST) != 0) { response[0] = 1; /* Stalled */ } else { response[0] = 0; /* Not stalled */ } response[1] = 0; lpc17_epwrite(LPC17_EP0_IN, response, 2); priv->ep0state = LPC17_EP0SHORTWRITE; } } break; case USB_REQ_RECIPIENT_DEVICE: { if (index == 0) { usbtrace(TRACE_INTDECODE(LPC17_TRACEINTID_DEVGETSTATUS), 0); /* Features: Remote Wakeup=YES; selfpowered=? */ response[0] = (priv->selfpowered << USB_FEATURE_SELFPOWERED) | (1 << USB_FEATURE_REMOTEWAKEUP); response[1] = 0; lpc17_epwrite(LPC17_EP0_IN, response, 2); priv->ep0state = LPC17_EP0SHORTWRITE; } else { usbtrace(TRACE_DEVERROR(LPC17_TRACEERR_BADDEVGETSTATUS), 0); priv->stalled = 1; } } break; case USB_REQ_RECIPIENT_INTERFACE: { usbtrace(TRACE_INTDECODE(LPC17_TRACEINTID_IFGETSTATUS), 0); response[0] = 0; response[1] = 0; lpc17_epwrite(LPC17_EP0_IN, response, 2); priv->ep0state = LPC17_EP0SHORTWRITE; } break; default: { usbtrace(TRACE_DEVERROR(LPC17_TRACEERR_BADGETSTATUS), 0); priv->stalled = 1; } break; } } } break; case USB_REQ_CLEARFEATURE: { /* type: host-to-device; recipient = device, interface or endpoint * value: feature selector * index: zero interface endpoint; * len: zero, data = none */ usbtrace(TRACE_INTDECODE(LPC17_TRACEINTID_CLEARFEATURE), 0); if ((ctrl.type & USB_REQ_RECIPIENT_MASK) != USB_REQ_RECIPIENT_ENDPOINT) { lpc17_dispatchrequest(priv, &ctrl); } else if (priv->paddrset != 0 && value == USB_FEATURE_ENDPOINTHALT && len == 0 && (privep = lpc17_epfindbyaddr(priv, index)) != NULL) { privep->halted = 0; ret = lpc17_epstall(&privep->ep, true); lpc17_epwrite(LPC17_EP0_IN, NULL, 0); priv->ep0state = LPC17_EP0STATUSIN; } else { usbtrace(TRACE_DEVERROR(LPC17_TRACEERR_BADCLEARFEATURE), 0); priv->stalled = 1; } } break; case USB_REQ_SETFEATURE: { /* type: host-to-device; recipient = device, interface, endpoint * value: feature selector * index: zero interface endpoint; * len: 0; data = none */ usbtrace(TRACE_INTDECODE(LPC17_TRACEINTID_SETFEATURE), 0); if (((ctrl.type & USB_REQ_RECIPIENT_MASK) == USB_REQ_RECIPIENT_DEVICE) && value == USB_FEATURE_TESTMODE) { ullvdbg("test mode: %d\n", index); } else if ((ctrl.type & USB_REQ_RECIPIENT_MASK) != USB_REQ_RECIPIENT_ENDPOINT) { lpc17_dispatchrequest(priv, &ctrl); } else if (priv->paddrset != 0 && value == USB_FEATURE_ENDPOINTHALT && len == 0 && (privep = lpc17_epfindbyaddr(priv, index)) != NULL) { privep->halted = 1; lpc17_epwrite(LPC17_EP0_IN, NULL, 0); priv->ep0state = LPC17_EP0STATUSIN; } else { usbtrace(TRACE_DEVERROR(LPC17_TRACEERR_BADSETFEATURE), 0); priv->stalled = 1; } } break; case USB_REQ_SETADDRESS: { /* type: host-to-device; recipient = device * value: device address * index: 0 * len: 0; data = none */ usbtrace(TRACE_INTDECODE(LPC17_TRACEINTID_EP0SETUPSETADDRESS), value); if ((ctrl.type & USB_REQ_RECIPIENT_MASK) == USB_REQ_RECIPIENT_DEVICE && index == 0 && len == 0 && value < 128) { /* Save the address. We cannot actually change to the next address until * the completion of the status phase. */ priv->paddr = ctrl.value[0]; /* Note that if we send the SETADDRESS command twice, that will force the * address change. Otherwise, the hardware will automatically set the * address at the end of the status phase. */ lpc17_usbcmd(CMD_USBDEV_SETADDRESS, CMD_USBDEV_SETADDRESS_DEVEN | priv->paddr); /* Send a NULL packet. The status phase completes when the null packet has * been sent successfully. */ lpc17_epwrite(LPC17_EP0_IN, NULL, 0); priv->ep0state = LPC17_EP0SETADDRESS; } else { usbtrace(TRACE_DEVERROR(LPC17_TRACEERR_BADSETADDRESS), 0); priv->stalled = 1; } } break; case USB_REQ_GETDESCRIPTOR: /* type: device-to-host; recipient = device * value: descriptor type and index * index: 0 or language ID; * len: descriptor len; data = descriptor */ case USB_REQ_SETDESCRIPTOR: /* type: host-to-device; recipient = device * value: descriptor type and index * index: 0 or language ID; * len: descriptor len; data = descriptor */ { usbtrace(TRACE_INTDECODE(LPC17_TRACEINTID_GETSETDESC), 0); if ((ctrl.type & USB_REQ_RECIPIENT_MASK) == USB_REQ_RECIPIENT_DEVICE) { lpc17_dispatchrequest(priv, &ctrl); } else { usbtrace(TRACE_DEVERROR(LPC17_TRACEERR_BADGETSETDESC), 0); priv->stalled = 1; } } break; case USB_REQ_GETCONFIGURATION: /* type: device-to-host; recipient = device * value: 0; * index: 0; * len: 1; data = configuration value */ { usbtrace(TRACE_INTDECODE(LPC17_TRACEINTID_GETCONFIG), 0); if (priv->paddrset && (ctrl.type & USB_REQ_RECIPIENT_MASK) == USB_REQ_RECIPIENT_DEVICE && value == 0 && index == 0 && len == 1) { lpc17_dispatchrequest(priv, &ctrl); } else { usbtrace(TRACE_DEVERROR(LPC17_TRACEERR_BADGETCONFIG), 0); priv->stalled = 1; } } break; case USB_REQ_SETCONFIGURATION: /* type: host-to-device; recipient = device * value: configuration value * index: 0; * len: 0; data = none */ { usbtrace(TRACE_INTDECODE(LPC17_TRACEINTID_SETCONFIG), 0); if ((ctrl.type & USB_REQ_RECIPIENT_MASK) == USB_REQ_RECIPIENT_DEVICE && index == 0 && len == 0) { lpc17_dispatchrequest(priv, &ctrl); } else { usbtrace(TRACE_DEVERROR(LPC17_TRACEERR_BADSETCONFIG), 0); priv->stalled = 1; } } break; case USB_REQ_GETINTERFACE: /* type: device-to-host; recipient = interface * value: 0 * index: interface; * len: 1; data = alt interface */ case USB_REQ_SETINTERFACE: /* type: host-to-device; recipient = interface * value: alternate setting * index: interface; * len: 0; data = none */ { usbtrace(TRACE_INTDECODE(LPC17_TRACEINTID_GETSETIF), 0); lpc17_dispatchrequest(priv, &ctrl); } break; case USB_REQ_SYNCHFRAME: /* type: device-to-host; recipient = endpoint * value: 0 * index: endpoint; * len: 2; data = frame number */ { usbtrace(TRACE_INTDECODE(LPC17_TRACEINTID_SYNCHFRAME), 0); } break; default: { usbtrace(TRACE_DEVERROR(LPC17_TRACEERR_INVALIDCTRLREQ), 0); priv->stalled = 1; } break; } if (priv->stalled) { usbtrace(TRACE_DEVERROR(LPC17_TRACEERR_EP0SETUPSTALLED), priv->ep0state); lpc17_epstall(&priv->eplist[LPC17_EP0_IN].ep, false); lpc17_epstall(&priv->eplist[LPC17_EP0_OUT].ep, false); } } /******************************************************************************* * Name: lpc17_ep0dataoutinterrupt * * Description: * USB Ctrl EP Data OUT Event. This is logically part of the USB interrupt * handler. Each non-isochronous OUT endpoint gives an interrupt when they * receive a packet without error. * *******************************************************************************/ static inline void lpc17_ep0dataoutinterrupt(struct lpc17_usbdev_s *priv) { uint32_t pktlen; /* Copy new setup packet into setup buffer */ switch (priv->ep0state) { case LPC17_EP0SHORTWRITE: { priv->ep0state = LPC17_EP0STATUSOUT; pktlen = lpc17_epread(LPC17_EP0_OUT, NULL, CONFIG_LPC17_USBDEV_EP0_MAXSIZE); if (LPC17_READOVERRUN(pktlen)) { lpc17_ep0setup(priv); } } break; case LPC17_EP0SHORTWRSENT: { priv->ep0state = LPC17_EP0REQUEST; pktlen = lpc17_epread(LPC17_EP0_OUT, NULL, CONFIG_LPC17_USBDEV_EP0_MAXSIZE); if (LPC17_READOVERRUN(pktlen)) { lpc17_ep0setup(priv); } } break; case LPC17_EP0REQUEST: { /* Process the next request action (if any) */ lpc17_rdrequest(&priv->eplist[LPC17_EP0_OUT]); } break; default: priv->stalled = 1; break; } if (priv->stalled) { usbtrace(TRACE_DEVERROR(LPC17_TRACEERR_EP0OUTSTALLED), priv->ep0state); lpc17_epstall(&priv->eplist[LPC17_EP0_IN].ep, false); lpc17_epstall(&priv->eplist[LPC17_EP0_OUT].ep, false); } } /******************************************************************************* * Name: lpc17_ep0dataininterrupt * * Description: * USB Ctrl EP Data IN Event. This is logically part of the USB interrupt * handler. All non-isochronous IN endpoints give this interrupt when a * packet is successfully transmitted (OR a NAK handshake is sent on the bus * provided that the interrupt on NAK feature is enabled). * *******************************************************************************/ static inline void lpc17_ep0dataininterrupt(struct lpc17_usbdev_s *priv) { struct lpc17_ep_s *ep0; switch (priv->ep0state) { case LPC17_EP0STATUSOUT: case LPC17_EP0STATUSIN: priv->ep0state = LPC17_EP0REQUEST; break; case LPC17_EP0SHORTWRITE: priv->ep0state = LPC17_EP0SHORTWRSENT; break; case LPC17_EP0SETADDRESS: { /* If the address was set to a non-zero value, then thiscompletes the * default phase, and begins the address phase (still not fully configured) */ usbtrace(TRACE_INTDECODE(LPC17_TRACEINTID_EP0INSETADDRESS), (uint16_t)priv->paddr); lpc17_usbcmd(CMD_USBDEV_CONFIG, 0); if (priv->paddr) { priv->paddrset = 1; priv->ep0state = LPC17_EP0REQUEST; } } break; case LPC17_EP0REQUEST: { /* Process the next request action (if any) */ ep0 = &priv->eplist[LPC17_EP0_IN]; ep0->txbusy = 0; lpc17_wrrequest(ep0); } break; default: priv->stalled = 1; break; } if (priv->stalled) { usbtrace(TRACE_DEVERROR(LPC17_TRACEERR_EP0INSTALLED), priv->ep0state); lpc17_epstall(&priv->eplist[LPC17_EP0_IN].ep, false); lpc17_epstall(&priv->eplist[LPC17_EP0_OUT].ep, false); } } /******************************************************************************* * Name: lpc17_usbinterrupt * * Description: * USB interrupt handler * *******************************************************************************/ static int lpc17_usbinterrupt(int irq, FAR void *context) { struct lpc17_usbdev_s *priv = &g_usbdev; struct lpc17_ep_s *privep ; uint32_t devintstatus; /* Sampled state of the device interrupt status register */ uint32_t epintstatus; /* Sampled state of the endpoint interrupt status register */ #ifdef CONFIG_LPC17_USBDEV_DMA uint32_t usbintstatus; /* Sampled state is SYSCON USB interrupt status */ uint32_t dmaintstatus; /* Sampled state of dma interrupt status register */ #endif uint32_t softprio; /* Current priority interrupt bitset */ uint32_t pending; /* Pending subset of priority interrupt bitset */ uint8_t epphy; /* Physical endpoint number being processed */ int i; /* Read the device interrupt status register */ devintstatus = lpc17_getreg(LPC17_USBDEV_INTST); usbtrace(TRACE_INTENTRY(LPC17_TRACEINTID_USB), (uint16_t)devintstatus); #ifdef CONFIG_LPC17_USBDEV_DMA /* Check for low priority and high priority (non-DMA) interrupts */ usbintstatus = lpc17_getreg(LPC17_SYSCON_USBINTST); if ((usbintstatus & (SYSCON_USBINTST_REQLP|SYSCON_USBINTST_REQHP)) != 0) { #endif #ifdef CONFIG_LPC17_USBDEV_EPFAST_INTERRUPT /* Fast EP interrupt */ if ((devintstatus & USBDEV_INT_EPFAST) != 0) { /* Clear Fast EP interrupt */ lpc17_putreg(USBDEV_INT_EPFAST, LPC17_USBDEV_INTCLR); usbtrace(TRACE_INTDECODE(LPC17_TRACEINTID_EPFAST), 0); /* Do what? */ } #endif #if CONFIG_DEBUG /* USB engine error interrupt */ if ((devintstatus & USBDEV_INT_ERRINT) != 0) { uint8_t errcode; /* Clear the error interrupt */ lpc17_putreg(USBDEV_INT_ERRINT, LPC17_USBDEV_INTCLR); /* And show what error occurred */ errcode = (uint8_t)lpc17_usbcmd(CMD_USBDEV_READERRORSTATUS, 0) & CMD_READERRORSTATUS_ALLERRS; usbtrace(TRACE_INTDECODE(LPC17_TRACEINTID_ERRINT), (uint16_t)errcode); } #endif #ifdef CONFIG_LPC17_USBDEV_FRAME_INTERRUPT /* Frame interrupt */ if ((devintstatus & USBDEV_INT_FRAME) != 0) { /* Clear the frame interrupt */ lpc17_putreg(USBDEV_INT_FRAME, LPC17_USBDEV_INTCLR); usbtrace(TRACE_INTDECODE(LPC17_TRACEINTID_FRAME), 0); /* Then read the start of frame value */ priv->sof = (uint16_t)lpc17_usbcmd(CMD_USBDEV_READFRAMENO, 0); } #endif /* Device Status interrupt */ if ((devintstatus & USBDEV_INT_DEVSTAT) != 0) { /* Clear Device status interrupt */ lpc17_putreg(USBDEV_INT_DEVSTAT, LPC17_USBDEV_INTCLR); /* Get device status */ g_usbdev.devstatus = (uint8_t)lpc17_usbcmd(CMD_USBDEV_GETSTATUS, 0); usbtrace(TRACE_INTDECODE(LPC17_TRACEINTID_DEVSTAT), (uint16_t)g_usbdev.devstatus); /* Device connection status */ if (DEVSTATUS_CONNCHG(g_usbdev.devstatus)) { usbtrace(TRACE_INTDECODE(LPC17_TRACEINTID_CONNECTCHG), (uint16_t)g_usbdev.devstatus); if (DEVSTATUS_CONNECT(g_usbdev.devstatus)) { /* Host is connected */ if (!priv->attached) { /* We have a transition from unattached to attached */ usbtrace(TRACE_INTDECODE(LPC17_TRACEINTID_CONNECTED), (uint16_t)g_usbdev.devstatus); priv->usbdev.speed = USB_SPEED_UNKNOWN; lpc17_usbcmd(CMD_USBDEV_CONFIG, 0); priv->attached = 1; } } /* Otherwise the host is not attached */ else if (priv->attached) { usbtrace(TRACE_INTDECODE(LPC17_TRACEINTID_DISCONNECTED), (uint16_t)g_usbdev.devstatus); priv->usbdev.speed = USB_SPEED_UNKNOWN; lpc17_usbcmd(CMD_USBDEV_CONFIG, 0); priv->attached = 0; priv->paddrset = 0; } } /* Device suspend status */ if (DEVSTATUS_SUSPCHG(g_usbdev.devstatus)) { usbtrace(TRACE_INTDECODE(LPC17_TRACEINTID_SUSPENDCHG), (uint16_t)g_usbdev.devstatus); /* Inform the Class driver of the change */ if (priv->driver) { if (DEVSTATUS_SUSPEND(g_usbdev.devstatus)) { CLASS_SUSPEND(priv->driver, &priv->usbdev); } else { CLASS_RESUME(priv->driver, &priv->usbdev); } } /* TODO: Perform power management operations here. */ } /* Device reset */ if (DEVSTATUS_RESET(g_usbdev.devstatus)) { usbtrace(TRACE_INTDECODE(LPC17_TRACEINTID_DEVRESET), (uint16_t)g_usbdev.devstatus); lpc17_usbreset(priv); } } /* Slow EP interrupt */ if ((devintstatus & USBDEV_INT_EPSLOW) != 0) { /* Clear Slow EP interrupt */ lpc17_putreg(USBDEV_INT_EPSLOW, LPC17_USBDEV_INTCLR); usbtrace(TRACE_INTDECODE(LPC17_TRACEINTID_EPSLOW), 0); do { /* Read the endpoint interrupt status register */ epintstatus = lpc17_getreg(LPC17_USBDEV_EPINTST); /* Loop twice: Process software high priority interrupts * on the first pass and low priority interrupts on the * second. */ softprio = priv->softprio; for (i = 0; i < 2; i++, softprio = ~softprio) { /* On the first time through the loop, pending will be * the bitset of high priority pending interrupts; on the * second time throught it will be the bitset of low * priority interrupts. */ pending = epintstatus & softprio; /* EP0 OUT interrupt indicated by bit0 == 1 */ if ((pending & 1) != 0) { /* Clear the endpoint interrupt */ uint32_t result = lpc17_epclrinterrupt(LPC17_CTRLEP_OUT); if (result & CMD_EPSELECT_STP) { usbtrace(TRACE_INTDECODE(LPC17_TRACEINTID_EP0SETUP), (uint16_t)result); lpc17_ep0setup(priv); } else { usbtrace(TRACE_INTDECODE(LPC17_TRACEINTID_EP0OUT), priv->ep0state); lpc17_ep0dataoutinterrupt(priv); } break; } /* EP0 IN interrupt indicated by bit1 == 1 */ if ((pending & 2) != 0) { /* Clear the endpoint interrupt */ usbtrace(TRACE_INTDECODE(LPC17_TRACEINTID_EP0IN), priv->ep0state); (void)lpc17_epclrinterrupt(LPC17_CTRLEP_IN); lpc17_ep0dataininterrupt(priv); } pending >>= 2; /* All other endpoints EP 1-31 */ for (epphy = 2; pending; epphy++, pending >>= 1) { /* Is the endpoint interrupt pending? */ if ((pending & 1) != 0) { /* Yes.. clear the endpoint interrupt */ (void)lpc17_epclrinterrupt(epphy); /* Get the endpoint sructure corresponding to the physical * endpoint number. */ privep = &priv->eplist[epphy]; /* Check for complete on IN or OUT endpoint. Odd physical * endpoint addresses are IN endpoints. */ if ((epphy & 1) != 0) { /* IN: device-to-host */ usbtrace(TRACE_INTDECODE(LPC17_TRACEINTID_EPOUT), (uint16_t)epphy); if (priv->usbdev.speed == USB_SPEED_UNKNOWN) { priv->usbdev.speed = USB_SPEED_FULL; lpc17_usbcmd(CMD_USBDEV_CONFIG, 1); } /* Write host data from the current write request (if any) */ privep->txbusy = 0; lpc17_wrrequest(privep); } else { /* OUT: host-to-device */ usbtrace(TRACE_INTDECODE(LPC17_TRACEINTID_EPIN), (uint16_t)epphy); /* Read host data into the current read request */ if (!lpc17_rqempty(privep)) { lpc17_rdrequest(privep); } else { ullvdbg("Pending data on OUT endpoint\n"); priv->rxpending = 1; } } } } } } while (epintstatus); } #ifdef CONFIG_LPC17_USBDEV_DMA } /* Check for DMA interrupts */ if (usbintstatus & SYSCON_USBINTST_REQDMA) != 0) { /* First Software High priority and then low priority */ uint32_t tmp; /* Collect the DMA interrupt sources */ dmaintstatus = 0; tmp = lpc17_getreg(LPC17_USBDEV_EOTINTST); if (lpc17_getreg(LPC17_USBDEV_DMAINTEN) & 1) { dmaintstatus |= tmp; } lpc17_putreg(tmp, LPC17_USBDEV_EOTINTCLR); tmp = lpc17_getreg(LPC17_USBDEV_NDDRINTST); if (lpc17_getreg(LPC17_USBDEV_DMAINTEN) & 2) { dmaintstatus |= tmp; } lpc17_putreg(tmp, LPC17_USBDEV_NDDRINTCLR); tmp = lpc17_getreg(LPC17_USBDEV_SYSERRINTST); if (lpc17_getreg(LPC17_USBDEV_DMAINTEN) & 4) { dmaintstatus |= tmp; } lpc17_putreg(tmp, LPC17_USBDEV_SYSERRINTCLR); /* Loop twice: Process software high priority interrupts on the * first pass and low priority interrupts on the second. */ softprio = priv->softprio; for (i = 0; i < 2; i++, softprio = ~softprio) { /* On the first time through the loop, pending will be * the bitset of high priority pending interrupts; on the * second time throught it will be the bitset of low * priority interrupts. Note that EP0 IN and OUT are * omitted. */ pending = (dmaintstatus & softprio) >> 2; for (epphy = 2; pending; epphy++, pending >>= 1) { if ((pending & 1) != 0) { usbtrace(TRACE_INTDECODE(LPC17_TRACEINTID_EPDMA), (uint16_t)epphy); #warning DO WHAT? } } } } #endif usbtrace(TRACE_INTEXIT(LPC17_TRACEINTID_USB), 0); return OK; } /******************************************************************************* * Name: lpc17_dmasetup * * Description: * Setup for DMA Transfer * *******************************************************************************/ #ifdef CONFIG_LPC17_USBDEV_DMA static int lpc17_dmasetup(struct lpc17_usbdev_s *priv, uint8_t epphy, uint32_t epmaxsize, uint32_t nbytes, uint32_t *isocpacket, bool isochronous); { struct lpc17_dmadesc_s *dmadesc = priv; uint32_t regval; #ifdef CONFIG_DEBUG if (!priv || epphy < 2) { usbtrace(TRACE_DEVERROR(LPC17_TRACEERR_INVALIDPARMS), 0); return -EINVAL; } #endif /* Check if a DMA descriptor has been assigned. If not, than that indicates * that we will have to do parallel I/O */ if (!dmadesc) { usbtrace(TRACE_DEVERROR(LPC17_TRACEERR_NODMADESC), 0); return -EBUSY; } /* Verify that the DMA descriptor is available */ if ((dmadesc->status & USB_DMADESC_STATUS_MASK) == USB_DMADESC_BEINGSERVICED) { usbtrace(TRACE_DEVERROR(LPC17_TRACEERR_DMABUSY), 0); return -EBUSY; /* Shouldn't happen */ } /* Init DMA Descriptor */ dmadesc->nexdesc = 0; dmadesc->config = USB_DMADESC_MODENORMAL | ((epmaxsize << USB_DMADESC_PKTSIZE_SHIFT) & USB_DMADESC_PKTSIZE_MASK) | ((nbytes << USB_DMADESC_BUFLEN_SHIFT) & USB_DMADESC_BUFLEN_MASK); #ifdef CONFIG_USBDEV_ISOCHRONOUS if (isochronous) { dmadesc->config |= USB_DMADESC_ISCOEP; } #endif dmadesc->start = (uint32_t)&dmadesc->buffer; dmadesc->status = 0; #ifdef CONFIG_USBDEV_ISOCHRONOUS dmadesc->size = (uint32_t)packet; #endif /* Enable DMA tranfer for this endpoint */ putreq32(1 << epphy, LPC17_USBDEV_EPDMAEN); /* Check state of IN/OUT Ep buffer */ regval = lpc17_usbcmd(CMD_USBDEV_EPSELECT | epphy, 0); if ((LPC17_EPPHYIN(epphy) && (regval & 0x60) == 0) || (LPC17_EPPHYOUT(epphy) && (regval & 0x60) == 0x60)) { /* DMA should be "being serviced" */ if ((dmadesc->status & USB_DMADESC_STATUS_MASK) != USB_DMADESC_BEINGSERVICED)) { /* Re-trigger the DMA Transfer */ putreq32(1 << epphy, LPC17_USBDEV_DMARCLR); putreq32(1 << epphy, LPC17_USBDEV_EPDMAEN); } } return OK; } #endif /* CONFIG_LPC17_USBDEV_DMA */ /******************************************************************************* * Name: lpc17_dmarestart * * Description: * Restart DMA Transfer * *******************************************************************************/ #ifdef CONFIG_LPC17_USBDEV_DMA static void lpc17_dmarestart(uint8_t epphy, uint32_t descndx) { uint32_t regval; /* Clear DMA descriptor status */ USB_DmaDesc[descndx].status = 0; /* Enable DMA transfer on the endpoint */ lpc17_putreg(1 << epph, LPC17_USBDEV_EPDMAEN); /* Check the state of IN/OUT EP buffer */ uint32_t regval = lpc17_usbcmd(CMD_USBDEV_EPSELECT | epphy, 0); if ((LPC17_EPPHYIN(epphy) && (regval & 0x60) == 0) || (LPC17_EPPHYIN(epphy) && (regval & 0x60) == 0x60)) { /* Re-trigger the DMA Transfer */ putreq32(1 << epphy, LPC17_USBDEV_DMARCLR); putreq32(1 << epphy, LPC17_USBDEV_EPDMAEN); } } #endif /* CONFIG_LPC17_USBDEV_DMA */ /******************************************************************************* * Name: lpc17_dmadisable * * Description: * Disable DMA transfer for the EP * *******************************************************************************/ #ifdef CONFIG_LPC17_USBDEV_DMA static void lpc17_dmadisable(uint8_t epphy) { EPDMADIS = 1 << epphy; } #endif /* CONFIG_LPC17_USBDEV_DMA */ /******************************************************************************* * Endpoint operations *******************************************************************************/ /******************************************************************************* * Name: lpc17_epconfigure * * Description: * Configure endpoint, making it usable * * Input Parameters: * ep - the struct usbdev_ep_s instance obtained from allocep() * desc - A struct usb_epdesc_s instance describing the endpoint * last - true if this this last endpoint to be configured. Some hardware * needs to take special action when all of the endpoints have been * configured. * *******************************************************************************/ static int lpc17_epconfigure(FAR struct usbdev_ep_s *ep, FAR const struct usb_epdesc_s *desc, bool last) { FAR struct lpc17_ep_s *privep = (FAR struct lpc17_ep_s *)ep; uint32_t inten; usbtrace(TRACE_EPCONFIGURE, privep->epphy); DEBUGASSERT(desc->addr == ep->eplog); /* Realize the endpoint */ lpc17_eprealize(privep, 1, GETUINT16(desc->mxpacketsize)); /* Enable and reset EP -- twice */ lpc17_usbcmd(CMD_USBDEV_EPSETSTATUS | privep->epphy, 0); lpc17_usbcmd(CMD_USBDEV_EPSETSTATUS | privep->epphy, 0); #ifdef CONFIG_LPC17_USBDEV_DMA /* Enable DMA Ep interrupt (WO) */ lpc17_putreg(1 << privep->epphy, LPC17_USBDEV_EPDMAEN); #else /* Enable Ep interrupt (R/W) */ inten = lpc17_getreg(LPC17_USBDEV_EPINTEN); inten |= (1 << privep->epphy); lpc17_putreg(inten, LPC17_USBDEV_EPINTEN); #endif /* If all of the endpoints have been configured, then tell the USB controller * to enable normal activity on all realized endpoints. */ if (last) { lpc17_usbcmd(CMD_USBDEV_CONFIG, 1); } return OK; } /******************************************************************************* * Name: lpc17_epdisable * * Description: * The endpoint will no longer be used * *******************************************************************************/ static int lpc17_epdisable(FAR struct usbdev_ep_s *ep) { FAR struct lpc17_ep_s *privep = (FAR struct lpc17_ep_s *)ep; irqstate_t flags; uint32_t mask = (1 << privep->epphy); uint32_t regval; #ifdef CONFIG_DEBUG if (!ep) { usbtrace(TRACE_DEVERROR(LPC17_TRACEERR_INVALIDPARMS), 0); return -EINVAL; } #endif usbtrace(TRACE_EPDISABLE, privep->epphy); /* Cancel any ongoing activity */ flags = irqsave(); lpc17_cancelrequests(privep); /* Disable endpoint and interrupt */ regval = lpc17_getreg(LPC17_USBDEV_REEP); regval &= ~mask; lpc17_putreg(regval, LPC17_USBDEV_REEP); lpc17_putreg(mask, LPC17_USBDEV_EPDMADIS); regval = lpc17_getreg(LPC17_USBDEV_EPINTEN); regval &= ~mask; lpc17_putreg(regval, LPC17_USBDEV_EPINTEN); irqrestore(flags); return OK; } /******************************************************************************* * Name: lpc17_epallocreq * * Description: * Allocate an I/O request * *******************************************************************************/ static FAR struct usbdev_req_s *lpc17_epallocreq(FAR struct usbdev_ep_s *ep) { FAR struct lpc17_req_s *privreq; #ifdef CONFIG_DEBUG if (!ep) { usbtrace(TRACE_DEVERROR(LPC17_TRACEERR_INVALIDPARMS), 0); return NULL; } #endif usbtrace(TRACE_EPALLOCREQ, ((FAR struct lpc17_ep_s *)ep)->epphy); privreq = (FAR struct lpc17_req_s *)kmalloc(sizeof(struct lpc17_req_s)); if (!privreq) { usbtrace(TRACE_DEVERROR(LPC17_TRACEERR_ALLOCFAIL), 0); return NULL; } memset(privreq, 0, sizeof(struct lpc17_req_s)); return &privreq->req; } /******************************************************************************* * Name: lpc17_epfreereq * * Description: * Free an I/O request * *******************************************************************************/ static void lpc17_epfreereq(FAR struct usbdev_ep_s *ep, FAR struct usbdev_req_s *req) { FAR struct lpc17_req_s *privreq = (FAR struct lpc17_req_s *)req; #ifdef CONFIG_DEBUG if (!ep || !req) { usbtrace(TRACE_DEVERROR(LPC17_TRACEERR_INVALIDPARMS), 0); return; } #endif usbtrace(TRACE_EPFREEREQ, ((FAR struct lpc17_ep_s *)ep)->epphy); kfree(privreq); } /******************************************************************************* * Name: lpc17_epallocbuffer * * Description: * Allocate an I/O buffer * *******************************************************************************/ #ifdef CONFIG_USBDEV_DMA static FAR void *lpc17_epallocbuffer(FAR struct usbdev_ep_s *ep, uint16_t nbytes) { #if defined(CONFIG_LPC17_USBDEV_DMA) FAR struct lpc17_ep_s *privep = (FAR struct lpc17_ep_s *)ep; int descndx; usbtrace(TRACE_EPALLOCBUFFER, privep->epphy); /* Find a free DMA description */ #error "LOGIC INCOMPLETE" /* Set UDCA to the allocated DMA descriptor for this endpoint */ g_udca[privep->epphy] = &g_usbddesc[descndx]; return &g_usbddesc[descndx] #elif defined(CONFIG_USBDEV_DMAMEMORY) usbtrace(TRACE_EPALLOCBUFFER, privep->epphy); return usbdev_dma_alloc(bytes); #else usbtrace(TRACE_EPALLOCBUFFER, privep->epphy); return kmalloc(bytes); #endif } #endif /******************************************************************************* * Name: lpc17_epfreebuffer * * Description: * Free an I/O buffer * *******************************************************************************/ #ifdef CONFIG_USBDEV_DMA static void lpc17_epfreebuffer(FAR struct usbdev_ep_s *ep, FAR void *buf) { #if defined(CONFIG_LPC17_USBDEV_DMA) FAR struct lpc17_ep_s *privep = (FAR struct lpc17_ep_s *)ep; usbtrace(TRACE_EPFREEBUFFER, privep->epphy); /* Indicate that there is no DMA descriptor associated with this endpoint */ g_udca[privep->epphy] = NULL; /* Mark the DMA descriptor as free for re-allocation */ # error "LOGIC INCOMPLETE" #elif defined(CONFIG_USBDEV_DMAMEMORY) usbtrace(TRACE_EPFREEBUFFER, privep->epphy); usbdev_dma_free(buf); #else usbtrace(TRACE_EPFREEBUFFER, privep->epphy); kfree(buf); #endif } #endif /******************************************************************************* * Name: lpc17_epsubmit * * Description: * Submit an I/O request to the endpoint * *******************************************************************************/ static int lpc17_epsubmit(FAR struct usbdev_ep_s *ep, FAR struct usbdev_req_s *req) { FAR struct lpc17_req_s *privreq = (FAR struct lpc17_req_s *)req; FAR struct lpc17_ep_s *privep = (FAR struct lpc17_ep_s *)ep; FAR struct lpc17_usbdev_s *priv; irqstate_t flags; int ret = OK; #ifdef CONFIG_DEBUG if (!req || !req->callback || !req->buf || !ep) { usbtrace(TRACE_DEVERROR(LPC17_TRACEERR_INVALIDPARMS), 0); ullvdbg("req=%p callback=%p buf=%p ep=%p\n", req, req->callback, req->buf, ep); return -EINVAL; } #endif usbtrace(TRACE_EPSUBMIT, privep->epphy); priv = privep->dev; if (!priv->driver || priv->usbdev.speed == USB_SPEED_UNKNOWN) { usbtrace(TRACE_DEVERROR(LPC17_TRACEERR_NOTCONFIGURED), priv->usbdev.speed); return -ESHUTDOWN; } /* Handle the request from the class driver */ req->result = -EINPROGRESS; req->xfrd = 0; flags = irqsave(); /* If we are stalled, then drop all requests on the floor */ if (privep->stalled) { lpc17_abortrequest(privep, privreq, -EBUSY); ret = -EBUSY; } /* Handle IN (device-to-host) requests */ else if (LPC17_EPPHYIN(privep->epphy)) { /* Add the new request to the request queue for the IN endpoint */ lpc17_rqenqueue(privep, privreq); usbtrace(TRACE_INREQQUEUED(privep->epphy), privreq->req.len); /* If the IN endpoint FIFO is available, then transfer the data now */ if (privep->txbusy == 0) { ret = lpc17_wrrequest(privep); } } /* Handle OUT (host-to-device) requests */ else { /* Add the new request to the request queue for the OUT endpoint */ privep->txnullpkt = 0; lpc17_rqenqueue(privep, privreq); usbtrace(TRACE_OUTREQQUEUED(privep->epphy), privreq->req.len); /* This there a incoming data pending the availability of a request? */ if (priv->rxpending) { ret = lpc17_rdrequest(privep); priv->rxpending = 0; } } irqrestore(flags); return ret; } /******************************************************************************* * Name: lpc17_epcancel * * Description: * Cancel an I/O request previously sent to an endpoint * *******************************************************************************/ static int lpc17_epcancel(FAR struct usbdev_ep_s *ep, FAR struct usbdev_req_s *req) { FAR struct lpc17_ep_s *privep = (FAR struct lpc17_ep_s *)ep; FAR struct lpc17_usbdev_s *priv; irqstate_t flags; #ifdef CONFIG_DEBUG if (!ep || !req) { usbtrace(TRACE_DEVERROR(LPC17_TRACEERR_INVALIDPARMS), 0); return -EINVAL; } #endif usbtrace(TRACE_EPCANCEL, privep->epphy); priv = privep->dev; flags = irqsave(); lpc17_cancelrequests(privep); irqrestore(flags); return OK; } /******************************************************************************* * Name: lpc17_epstall * * Description: * Stall or resume and endpoint * *******************************************************************************/ static int lpc17_epstall(FAR struct usbdev_ep_s *ep, bool resume) { FAR struct lpc17_ep_s *privep = (FAR struct lpc17_ep_s *)ep; irqstate_t flags; /* STALL or RESUME the endpoint */ flags = irqsave(); usbtrace(resume ? TRACE_EPRESUME : TRACE_EPSTALL, privep->epphy); lpc17_usbcmd(CMD_USBDEV_EPSETSTATUS | privep->epphy, (resume ? 0 : CMD_SETSTAUS_ST)); /* If the endpoint of was resumed, then restart any queue write requests */ if (resume) { (void)lpc17_wrrequest(privep); } irqrestore(flags); return OK; } /******************************************************************************* * Device operations *******************************************************************************/ /******************************************************************************* * Name: lpc17_allocep * * Description: * Allocate an endpoint matching the parameters. * * Input Parameters: * eplog - 7-bit logical endpoint number (direction bit ignored). Zero means * that any endpoint matching the other requirements will suffice. The * assigned endpoint can be found in the eplog field. * in - true: IN (device-to-host) endpoint requested * eptype - Endpoint type. One of {USB_EP_ATTR_XFER_ISOC, USB_EP_ATTR_XFER_BULK, * USB_EP_ATTR_XFER_INT} * *******************************************************************************/ static FAR struct usbdev_ep_s *lpc17_allocep(FAR struct usbdev_s *dev, uint8_t eplog, bool in, uint8_t eptype) { FAR struct lpc17_usbdev_s *priv = (FAR struct lpc17_usbdev_s *)dev; uint32_t epset = LPC17_EPALLSET & ~LPC17_EPCTRLSET; irqstate_t flags; int epndx = 0; usbtrace(TRACE_DEVALLOCEP, (uint16_t)eplog); /* Ignore any direction bits in the logical address */ eplog = USB_EPNO(eplog); /* A logical address of 0 means that any endpoint will do */ if (eplog > 0) { /* Otherwise, we will return the endpoint structure only for the requested * 'logical' endpoint. All of the other checks will still be performed. * * First, verify that the logical endpoint is in the range supported by * by the hardware. */ if (eplog >= LPC17_NLOGENDPOINTS) { usbtrace(TRACE_DEVERROR(LPC17_TRACEERR_BADEPNO), (uint16_t)eplog); return NULL; } /* Convert the logical address to a physical OUT endpoint address and * remove all of the candidate endpoints from the bitset except for the * the IN/OUT pair for this logical address. */ epset &= 3 << (eplog << 1); } /* Get the subset matching the requested direction */ if (in) { epset &= LPC17_EPINSET; } else { epset &= LPC17_EPOUTSET; } /* Get the subset matching the requested type */ switch (eptype) { case USB_EP_ATTR_XFER_INT: /* Interrupt endpoint */ epset &= LPC17_EPINTRSET; break; case USB_EP_ATTR_XFER_BULK: /* Bulk endpoint */ epset &= LPC17_EPBULKSET; break; case USB_EP_ATTR_XFER_ISOC: /* Isochronous endpoint */ epset &= LPC17_EPISOCSET; break; case USB_EP_ATTR_XFER_CONTROL: /* Control endpoint -- not a valid choice */ default: usbtrace(TRACE_DEVERROR(LPC17_TRACEERR_BADEPTYPE), (uint16_t)eptype); return NULL; } /* Is the resulting endpoint supported by the LPC17xx? */ if (epset) { /* Yes.. now see if any of the request endpoints are available */ flags = irqsave(); epset &= priv->epavail; if (epset) { /* Select the lowest bit in the set of matching, available endpoints */ for (epndx = 2; epndx < LPC17_NPHYSENDPOINTS; epndx++) { uint32_t bit = 1 << epndx; if ((epset & bit) != 0) { /* Mark the IN/OUT endpoint no longer available */ priv->epavail &= ~(3 << (bit & ~1)); irqrestore(flags); /* And return the pointer to the standard endpoint structure */ return &priv->eplist[epndx].ep; } } /* Shouldn't get here */ } irqrestore(flags); } usbtrace(TRACE_DEVERROR(LPC17_TRACEERR_NOEP), (uint16_t)eplog); return NULL; } /******************************************************************************* * Name: lpc17_freeep * * Description: * Free the previously allocated endpoint * *******************************************************************************/ static void lpc17_freeep(FAR struct usbdev_s *dev, FAR struct usbdev_ep_s *ep) { FAR struct lpc17_usbdev_s *priv = (FAR struct lpc17_usbdev_s *)dev; FAR struct lpc17_ep_s *privep = (FAR struct lpc17_ep_s *)ep; irqstate_t flags; usbtrace(TRACE_DEVFREEEP, (uint16_t)privep->epphy); if (priv && privep) { /* Mark the endpoint as available */ flags = irqsave(); priv->epavail |= (1 << privep->epphy); irqrestore(flags); } } /******************************************************************************* * Name: lpc17_getframe * * Description: * Returns the current frame number * *******************************************************************************/ static int lpc17_getframe(struct usbdev_s *dev) { #ifdef CONFIG_LPC17_USBDEV_FRAME_INTERRUPT FAR struct lpc17_usbdev_s *priv = (FAR struct lpc17_usbdev_s *)dev; /* Return last valid value of SOF read by the interrupt handler */ usbtrace(TRACE_DEVGETFRAME, (uint16_t)priv->sof); return priv->sof; #else /* Return the last frame number detected by the hardware */ usbtrace(TRACE_DEVGETFRAME, 0); return (int)lpc17_usbcmd(CMD_USBDEV_READFRAMENO, 0); #endif } /******************************************************************************* * Name: lpc17_wakeup * * Description: * Tries to wake up the host connected to this device * *******************************************************************************/ static int lpc17_wakeup(struct usbdev_s *dev) { uint8_t arg = CMD_STATUS_SUSPEND; irqstate_t flags; usbtrace(TRACE_DEVWAKEUP, (uint16_t)g_usbdev.devstatus); flags = irqsave(); if (DEVSTATUS_CONNECT(g_usbdev.devstatus)) { arg |= CMD_STATUS_CONNECT; } lpc17_usbcmd(CMD_USBDEV_SETSTATUS, arg); irqrestore(flags); return OK; } /******************************************************************************* * Name: lpc17_selfpowered * * Description: * Sets/clears the device selfpowered feature * *******************************************************************************/ static int lpc17_selfpowered(struct usbdev_s *dev, bool selfpowered) { FAR struct lpc17_usbdev_s *priv = (FAR struct lpc17_usbdev_s *)dev; usbtrace(TRACE_DEVSELFPOWERED, (uint16_t)selfpowered); #ifdef CONFIG_DEBUG if (!dev) { usbtrace(TRACE_DEVERROR(LPC17_TRACEERR_INVALIDPARMS), 0); return -ENODEV; } #endif priv->selfpowered = selfpowered; return OK; } /******************************************************************************* * Name: lpc17_pullup * * Description: * Software-controlled connect to/disconnect from USB host * *******************************************************************************/ static int lpc17_pullup(struct usbdev_s *dev, bool enable) { usbtrace(TRACE_DEVPULLUP, (uint16_t)enable); /* The CMD_STATUS_CONNECT bit in the CMD_USBDEV_SETSTATUS command * controls the LPC17xx SoftConnect_N output pin that is used for SoftConnect. */ lpc17_usbcmd(CMD_USBDEV_SETSTATUS, (enable ? CMD_STATUS_CONNECT : 0)); return OK; } /******************************************************************************* * Public Functions *******************************************************************************/ /******************************************************************************* * Name: up_usbinitialize * * Description: * Initialize USB hardware. * * Assumptions: * This function is called very early in the initialization sequence in order * to initialize the USB device functionality. * *******************************************************************************/ void up_usbinitialize(void) { struct lpc17_usbdev_s *priv = &g_usbdev; uint32_t regval; irqstate_t flags; int i; usbtrace(TRACE_DEVINIT, 0); /* Step 1: Enable power by setting PCUSB in the PCONP register */ flags = irqsave(); regval = lpc17_getreg(LPC17_SYSCON_PCONP); regval |= SYSCON_PCONP_PCUSB; lpc17_putreg(regval, LPC17_SYSCON_PCONP); /* Step 2: Enable clocking on USB (USB PLL clocking was initialized in * in very low-level clock setup logic (see lpc17_clockconfig.c)). We * do still need to set up USBCLKCTRL to enable device and AHB clocking. */ lpc17_putreg(LPC17_CLKCTRL_ENABLES, LPC17_USBDEV_CLKCTRL); /* Then wait for the clocks to be reported as "ON" */ do { regval = lpc17_getreg(LPC17_USBDEV_CLKST); } while ((regval & LPC17_CLKCTRL_ENABLES) != LPC17_CLKCTRL_ENABLES); /* Step 3: Configure I/O pins */ usbdev_dumpgpio(); #ifndef CONFIG_LPC17_USBDEV_NOVBUS lpc17_configgpio(GPIO_USB_VBUS); /* VBUS status input */ #endif lpc17_configgpio(GPIO_USB_CONNECT); /* SoftConnect control signal */ #ifndef CONFIG_LPC17_USBDEV_NOLED lpc17_configgpio(GPIO_USB_UPLED); /* GoodLink LED control signal */ #endif lpc17_configgpio(GPIO_USB_DP); /* Positive differential data */ lpc17_configgpio(GPIO_USB_DM); /* Negative differential data */ usbdev_dumpgpio(); /* Disable USB interrupts */ regval = lpc17_getreg(LPC17_SYSCON_USBINTST); regval &= ~SYSCON_USBINTST_ENINTS; lpc17_putreg(regval, LPC17_SYSCON_USBINTST); irqrestore(flags); /* Initialize the device state structure */ memset(priv, 0, sizeof(struct lpc17_usbdev_s)); priv->usbdev.ops = &g_devops; priv->usbdev.ep0 = &priv->eplist[LPC17_EP0_IN].ep; priv->epavail = LPC17_EPALLSET; /* Initialize the endpoint list */ for (i = 0; i < LPC17_NPHYSENDPOINTS; i++) { uint32_t bit = 1 << i; /* Set endpoint operations, reference to driver structure (not * really necessary because there is only one controller), and * the physical endpoint number (which is just the index to the * endpoint). */ priv->eplist[i].ep.ops = &g_epops; priv->eplist[i].dev = priv; /* The index, i, is the physical endpoint address; Map this * to a logical endpoint address usable by the class driver. */ priv->eplist[i].epphy = i; if (LPC17_EPPHYIN(i)) { priv->eplist[i].ep.eplog = LPC17_EPPHYIN2LOG(i); } else { priv->eplist[i].ep.eplog = LPC17_EPPHYOUT2LOG(i); } /* The maximum packet size may depend on the type of endpoint */ if ((LPC17_EPCTRLSET & bit) != 0) { priv->eplist[i].ep.maxpacket = LPC17_EP0MAXPACKET; } else if ((LPC17_EPINTRSET & bit) != 0) { priv->eplist[i].ep.maxpacket = LPC17_INTRMAXPACKET; } else if ((LPC17_EPBULKSET & bit) != 0) { priv->eplist[i].ep.maxpacket = LPC17_BULKMAXPACKET; } else /* if ((LPC17_EPISOCSET & bit) != 0) */ { priv->eplist[i].ep.maxpacket = LPC17_ISOCMAXPACKET; } } /* Make sure all USB interrupts are disabled and cleared */ lpc17_putreg(0, LPC17_USBDEV_INTEN); lpc17_putreg(0xffffffff, LPC17_USBDEV_INTCLR); lpc17_putreg(0, LPC17_USBDEV_INTPRI); lpc17_putreg(0, LPC17_USBDEV_EPINTEN); lpc17_putreg(0xffffffff, LPC17_USBDEV_EPINTCLR); lpc17_putreg(0, LPC17_USBDEV_EPINTPRI); /* Interrupt only on ACKs */ lpc17_usbcmd(CMD_USBDEV_SETMODE, 0); /* Attach USB controller interrupt handler */ if (irq_attach(LPC17_IRQ_USB, lpc17_usbinterrupt) != 0) { usbtrace(TRACE_DEVERROR(LPC17_TRACEERR_IRQREGISTRATION), (uint16_t)LPC17_IRQ_USB); goto errout; } /* Enable USB interrupts at the controller -- but do not enable * the ARM interrupt until the device is bound to the class * driver */ flags = irqsave(); regval = lpc17_getreg(LPC17_SYSCON_USBINTST); regval |= SYSCON_USBINTST_ENINTS; lpc17_putreg(regval, LPC17_SYSCON_USBINTST); irqrestore(flags); /* Disconnect device */ lpc17_pullup(&priv->usbdev, false); /* Enable EP0 for OUT (host-to-device) */ lpc17_usbcmd(CMD_USBDEV_SETADDRESS, CMD_USBDEV_SETADDRESS_DEVEN|0); lpc17_usbcmd(CMD_USBDEV_SETADDRESS, CMD_USBDEV_SETADDRESS_DEVEN|0); /* Reset/Re-initialize the USB hardware */ lpc17_usbreset(priv); /* Init Device state structure */ priv->devstatus = lpc17_usbcmd(CMD_USBDEV_GETSTATUS, 0); return; errout: up_usbuninitialize(); } /******************************************************************************* * Name: up_usbuninitialize *******************************************************************************/ void up_usbuninitialize(void) { struct lpc17_usbdev_s *priv = &g_usbdev; uint32_t regval; irqstate_t flags; usbtrace(TRACE_DEVUNINIT, 0); if (priv->driver) { usbtrace(TRACE_DEVERROR(LPC17_TRACEERR_DRIVERREGISTERED), 0); usbdev_unregister(priv->driver); } /* Disconnect device */ flags = irqsave(); lpc17_pullup(&priv->usbdev, false); priv->usbdev.speed = USB_SPEED_UNKNOWN; lpc17_usbcmd(CMD_USBDEV_CONFIG, 0); /* Disable and detach IRQs */ up_disable_irq(LPC17_IRQ_USB); irq_detach(LPC17_IRQ_USB); /* Turn off USB power and clocking */ regval = lpc17_getreg(LPC17_SYSCON_PCONP); regval &= ~SYSCON_PCONP_PCUSB; lpc17_putreg(regval, LPC17_SYSCON_PCONP); irqrestore(flags); } /******************************************************************************* * Name: usbdev_register * * Description: * Register a USB device class driver. The class driver's bind() method will be * called to bind it to a USB device driver. * *******************************************************************************/ int usbdev_register(struct usbdevclass_driver_s *driver) { int ret; usbtrace(TRACE_DEVREGISTER, 0); #ifdef CONFIG_DEBUG if (!driver || !driver->ops->bind || !driver->ops->unbind || !driver->ops->disconnect || !driver->ops->setup) { usbtrace(TRACE_DEVERROR(LPC17_TRACEERR_INVALIDPARMS), 0); return -EINVAL; } if (g_usbdev.driver) { usbtrace(TRACE_DEVERROR(LPC17_TRACEERR_DRIVER), 0); return -EBUSY; } #endif /* First hook up the driver */ g_usbdev.driver = driver; /* Then bind the class driver */ ret = CLASS_BIND(driver, &g_usbdev.usbdev); if (ret) { usbtrace(TRACE_DEVERROR(LPC17_TRACEERR_BINDFAILED), (uint16_t)-ret); g_usbdev.driver = NULL; } else { /* Enable USB controller interrupts */ up_enable_irq(LPC17_IRQ_USB); } return ret; } /******************************************************************************* * Name: usbdev_unregister * * Description: * Un-register usbdev class driver.If the USB device is connected to a USB host, * it will first disconnect(). The driver is also requested to unbind() and clean * up any device state, before this procedure finally returns. * *******************************************************************************/ int usbdev_unregister(struct usbdevclass_driver_s *driver) { usbtrace(TRACE_DEVUNREGISTER, 0); #ifdef CONFIG_DEBUG if (driver != g_usbdev.driver) { usbtrace(TRACE_DEVERROR(LPC17_TRACEERR_INVALIDPARMS), 0); return -EINVAL; } #endif /* Unbind the class driver */ CLASS_UNBIND(driver, &g_usbdev.usbdev); /* Disable USB controller interrupts */ up_disable_irq(LPC17_IRQ_USB); /* Unhook the driver */ g_usbdev.driver = NULL; return OK; }
gpl-3.0